From e271f15da0f65f1cc18382f954b3d8252de76220 Mon Sep 17 00:00:00 2001 From: Brian Sam-Bodden Date: Tue, 14 May 2024 12:09:58 -0700 Subject: [PATCH] refactor: IDE auto code cleanup --- README.md | 186 +- demos/roms-documents/pom.xml | 22 +- .../documents/RomsDocumentsApplication.java | 14 +- .../controllers/CompanyController.java | 16 +- .../controllers/EventController.java | 15 +- .../controllers/PersonController.java | 10 +- .../redis/om/documents/domain/Company.java | 6 +- .../com/redis/om/documents/domain/Event.java | 18 +- .../com/redis/om/documents/domain/Person.java | 6 +- .../repositories/CompanyRepository.java | 12 +- .../om/documents/service/EventService.java | 2 +- .../service/impl/EventServiceImpl.java | 12 +- .../om/documents/AbstractDocumentTest.java | 13 +- .../com/redis/om/documents/AbstractTest.java | 48 +- .../RomsDocumentsApplicationTests.java | 6 +- .../com/redis/om/documents/TestConfig.java | 48 +- .../controllers/EventControllerTest.java | 76 +- demos/roms-hashes/README.md | 3 +- .../om/hashes/RomsHashesApplication.java | 8 +- .../om/hashes/controllers/UserController.java | 6 +- .../java/com/redis/om/hashes/domain/Role.java | 7 +- .../java/com/redis/om/hashes/domain/User.java | 31 +- .../hashes/repositories/UserRepository.java | 4 +- .../om/hashes/RomsHashesApplicationTests.java | 6 +- demos/roms-permits/README.md | 4 +- .../redis/om/permits/PermitsApplication.java | 75 +- .../controlllers/PermitController.java | 26 +- .../repositories/PermitRepository.java | 16 +- .../om/permits/PermitsApplicationTests.java | 6 +- demos/roms-vss/README.md | 9 +- ...RomsVectorSimilaritySearchApplication.java | 27 +- .../om/vss/controllers/ProductController.java | 94 +- .../java/com/redis/om/vss/domain/Product.java | 13 +- .../om/hashes/RomsHashesApplicationTests.java | 6 +- .../spring/CustomRedisKeyValueTemplate.java | 8 +- .../com/redis/om/spring/DistanceMetric.java | 4 +- .../redis/om/spring/RediSearchIndexer.java | 143 +- .../spring/RedisEnhancedKeyValueAdapter.java | 136 +- .../om/spring/RedisJSONKeyValueAdapter.java | 61 +- .../om/spring/RedisModulesConfiguration.java | 203 +- .../redis/om/spring/RedisOMProperties.java | 412 ++-- .../RedisRepositoriesExcludeFilter.java | 2 +- .../com/redis/om/spring/SentinelConfig.java | 7 +- .../java/com/redis/om/spring/VectorType.java | 3 +- .../om/spring/annotations/Aggregation.java | 9 + .../redis/om/spring/annotations/Apply.java | 1 + .../annotations/AutoCompletePayload.java | 1 + .../redis/om/spring/annotations/Bloom.java | 2 + .../redis/om/spring/annotations/Cuckoo.java | 4 + .../redis/om/spring/annotations/Document.java | 15 +- .../om/spring/annotations/EmbeddingType.java | 5 +- .../EnableRedisDocumentRepositories.java | 12 +- .../EnableRedisEnhancedRepositories.java | 16 +- .../om/spring/annotations/GeoIndexed.java | 2 + .../redis/om/spring/annotations/GroupBy.java | 1 + .../com/redis/om/spring/annotations/Load.java | 1 + .../om/spring/annotations/NumericIndexed.java | 3 + .../redis/om/spring/annotations/Query.java | 5 + .../redis/om/spring/annotations/Reducer.java | 2 + .../redis/om/spring/annotations/SortBy.java | 1 + .../om/spring/annotations/TagIndexed.java | 3 + .../om/spring/annotations/TextIndexed.java | 6 + .../om/spring/annotations/Vectorize.java | 1 + .../redis/om/spring/audit/EntityAuditor.java | 6 +- .../autocomplete/AutoCompleteAspect.java | 60 +- .../redis/om/spring/bloom/BloomAspect.java | 34 +- .../om/spring/client/RedisModulesClient.java | 26 +- .../convert/BooleanToBytesConverter.java | 6 +- .../BytesToOffsetDateTimeConverter.java | 1 + .../convert/MappingRedisOMConverter.java | 271 +-- .../OffsetDateTimeToStringConverter.java | 12 +- .../spring/convert/PointToBytesConverter.java | 4 +- .../convert/RedisOMCustomConversions.java | 2 +- .../spring/convert/UlidToBytesConverter.java | 2 +- .../redis/om/spring/cuckoo/CuckooAspect.java | 34 +- .../java/com/redis/om/spring/id/OsTools.java | 17 +- .../com/redis/om/spring/id/SecureRandom.java | 31 +- .../om/spring/id/ULIDIdentifierGenerator.java | 4 +- .../metamodel/IllegalJavaBeanException.java | 7 +- .../om/spring/metamodel/MetamodelField.java | 8 +- .../spring/metamodel/MetamodelGenerator.java | 1324 +++++++------ .../om/spring/metamodel/MetamodelUtils.java | 9 +- .../spring/metamodel/SearchFieldAccessor.java | 1 - .../spring/metamodel/indexed/DateField.java | 42 +- .../om/spring/metamodel/indexed/GeoField.java | 44 +- .../metamodel/indexed/NumericField.java | 46 +- .../metamodel/indexed/ReferenceField.java | 8 +- .../spring/metamodel/indexed/TextField.java | 51 +- .../metamodel/indexed/TextTagField.java | 8 +- .../spring/metamodel/indexed/VectorField.java | 10 +- .../nonindexed/NonIndexedNumericField.java | 2 +- .../nonindexed/NonIndexedTextField.java | 1 - .../om/spring/ops/RedisModulesOperations.java | 3 +- .../spring/ops/json/JSONOperationsImpl.java | 64 +- .../om/spring/ops/pds/BloomOperations.java | 30 +- .../ops/pds/CountMinSketchOperations.java | 16 +- .../ops/pds/CountMinSketchOperationsImpl.java | 14 +- .../ops/pds/CuckooFilterOperations.java | 14 + .../spring/ops/search/SearchOperations.java | 28 +- .../ops/search/SearchOperationsImpl.java | 21 +- .../RedisEnhancedRepositoriesRegistrar.java | 2 +- .../RedisJSONRepositoriesRegistrar.java | 4 +- ...sJSONRepositoryConfigurationExtension.java | 18 +- .../spring/repository/query/QueryUtils.java | 23 +- .../repository/query/RediSearchQuery.java | 145 +- .../query/RediSearchQueryCreator.java | 1 - .../repository/query/RedisEnhancedQuery.java | 140 +- .../om/spring/repository/query/Sort.java | 9 +- .../autocomplete/AutoCompleteOptions.java | 24 +- .../AutoCompleteQueryExecutor.java | 13 +- .../query/bloom/BloomQueryExecutor.java | 13 +- .../repository/query/clause/QueryClause.java | 165 +- .../query/clause/QueryClauseTemplate.java | 23 +- .../query/cuckoo/CuckooQueryExecutor.java | 9 +- .../RedisDocumentRepositoryFactory.java | 170 +- .../RedisDocumentRepositoryFactoryBean.java | 10 +- .../RedisEnhancedRepositoryFactory.java | 144 +- .../RedisEnhancedRepositoryFactoryBean.java | 40 +- .../SimpleRedisDocumentRepository.java | 85 +- .../SimpleRedisEnhancedRepository.java | 61 +- .../spring/search/stream/AggregationPage.java | 31 +- .../search/stream/AggregationStream.java | 4 +- .../search/stream/AggregationStreamImpl.java | 169 +- .../search/stream/ExampleToNodeConverter.java | 57 +- .../search/stream/FluentQueryByExample.java | 18 +- .../stream/ReturnFieldsSearchStreamImpl.java | 52 +- .../om/spring/search/stream/SearchStream.java | 9 +- .../search/stream/SearchStreamImpl.java | 183 +- .../spring/search/stream/SummarizeParams.java | 16 +- .../search/stream/WrapperSearchStream.java | 12 +- .../stream/actions/BaseAbstractAction.java | 2 +- .../predicates/BaseAbstractPredicate.java | 32 +- .../fulltext/ContainingPredicate.java | 4 +- .../fulltext/EndsWithPredicate.java | 4 +- .../predicates/fulltext/EqualPredicate.java | 4 +- .../predicates/fulltext/InPredicate.java | 3 +- .../predicates/fulltext/LikePredicate.java | 5 +- .../fulltext/NotContainingPredicate.java | 6 +- .../fulltext/NotEqualPredicate.java | 6 +- .../predicates/fulltext/NotLikePredicate.java | 6 +- .../fulltext/StartsWithPredicate.java | 4 +- .../stream/predicates/geo/EqualPredicate.java | 4 +- .../stream/predicates/geo/NearPredicate.java | 6 +- .../predicates/geo/NotEqualPredicate.java | 6 +- .../predicates/geo/OutsideOfPredicate.java | 6 +- .../predicates/jedis/DateRangeValue.java | 5 +- .../predicates/numeric/BetweenPredicate.java | 8 +- .../predicates/numeric/NotEqualPredicate.java | 14 +- .../predicates/reference/EqualPredicate.java | 3 +- .../reference/NotEqualPredicate.java | 14 +- .../predicates/tag/ContainsAllPredicate.java | 3 +- .../predicates/tag/EndsWithPredicate.java | 6 +- .../stream/predicates/tag/EqualPredicate.java | 3 +- .../stream/predicates/tag/InPredicate.java | 3 +- .../predicates/tag/NotEqualPredicate.java | 7 +- .../predicates/tag/StartsWithPredicate.java | 6 +- .../predicates/vector/KNNPredicate.java | 3 +- .../serialization/gson/DateTypeAdapter.java | 14 +- .../serialization/gson/EnumTypeAdapter.java | 9 +- .../GsonReferenceSerializerRegistrar.java | 15 +- ...erencesSerializationExclusionStrategy.java | 4 +- .../gson/InstantTypeAdapter.java | 10 +- .../gson/LocalDateTimeTypeAdapter.java | 16 +- .../gson/LocalDateTypeAdapter.java | 17 +- .../gson/OffsetDateTimeTypeAdapter.java | 21 +- .../serialization/gson/PointTypeAdapter.java | 16 +- .../gson/ReferenceDeserializer.java | 22 +- .../serialization/gson/UlidTypeAdapter.java | 16 +- .../com/redis/om/spring/tuple/Decuple.java | 82 +- .../com/redis/om/spring/tuple/Duodecuple.java | 96 +- .../com/redis/om/spring/tuple/Fields.java | 103 +- .../redis/om/spring/tuple/GenericTuple.java | 4 +- .../com/redis/om/spring/tuple/Hextuple.java | 50 +- .../com/redis/om/spring/tuple/Nonuple.java | 74 +- .../redis/om/spring/tuple/Novemdecuple.java | 140 +- .../redis/om/spring/tuple/Octodecuple.java | 134 +- .../com/redis/om/spring/tuple/Octuple.java | 66 +- .../java/com/redis/om/spring/tuple/Pair.java | 18 +- .../java/com/redis/om/spring/tuple/Quad.java | 34 +- .../om/spring/tuple/Quattuordecuple.java | 108 +- .../redis/om/spring/tuple/Quindecuple.java | 114 +- .../com/redis/om/spring/tuple/Quintuple.java | 42 +- .../redis/om/spring/tuple/Septendecuple.java | 128 +- .../com/redis/om/spring/tuple/Septuple.java | 58 +- .../com/redis/om/spring/tuple/Sexdecuple.java | 120 +- .../com/redis/om/spring/tuple/Single.java | 10 +- .../com/redis/om/spring/tuple/Tredecuple.java | 102 +- .../com/redis/om/spring/tuple/Triple.java | 26 +- .../java/com/redis/om/spring/tuple/Tuple.java | 4 +- .../com/redis/om/spring/tuple/Tuples.java | 313 +-- .../com/redis/om/spring/tuple/Undecuple.java | 90 +- .../com/redis/om/spring/tuple/Vigintuple.java | 146 +- .../spring/tuple/accessor/FifthAccessor.java | 8 +- .../spring/tuple/accessor/FourthAccessor.java | 8 +- .../spring/tuple/accessor/TupleAccessor.java | 1 - .../om/spring/tuple/impl/AbstractTuple.java | 2 +- .../om/spring/tuple/impl/DecupleImpl.java | 2 +- .../om/spring/tuple/impl/DuodecupleImpl.java | 5 +- .../om/spring/tuple/impl/HextupleImpl.java | 2 +- .../om/spring/tuple/impl/NonupleImpl.java | 2 +- .../spring/tuple/impl/NovemdecupleImpl.java | 11 +- .../om/spring/tuple/impl/OctodecupleImpl.java | 11 +- .../om/spring/tuple/impl/OctupleImpl.java | 2 +- .../tuple/impl/QuattuordecupleImpl.java | 6 +- .../om/spring/tuple/impl/QuindecupleImpl.java | 6 +- .../spring/tuple/impl/SeptendecupleImpl.java | 9 +- .../om/spring/tuple/impl/SeptupleImpl.java | 2 +- .../om/spring/tuple/impl/SexdecupleImpl.java | 7 +- .../om/spring/tuple/impl/TredecupleImpl.java | 7 +- .../om/spring/tuple/impl/TripleImpl.java | 1 - .../om/spring/tuple/impl/UndecupleImpl.java | 3 +- .../om/spring/tuple/impl/VigintupleImpl.java | 13 +- .../tuple/impl/mapper/DecupleMapperImpl.java | 10 +- .../impl/mapper/DuodecupleMapperImpl.java | 10 +- .../impl/mapper/EmptyTupleMapperImpl.java | 21 +- .../tuple/impl/mapper/HextupleMapperImpl.java | 6 +- .../tuple/impl/mapper/NonupleMapperImpl.java | 6 +- .../impl/mapper/NovemdecupleMapperImpl.java | 18 +- .../impl/mapper/OctodecupleMapperImpl.java | 18 +- .../tuple/impl/mapper/OctupleMapperImpl.java | 6 +- .../mapper/QuattuordecupleMapperImpl.java | 12 +- .../impl/mapper/QuindecupleMapperImpl.java | 14 +- .../impl/mapper/QuintupleMapperImpl.java | 7 +- .../impl/mapper/SeptendecupleMapperImpl.java | 16 +- .../tuple/impl/mapper/SeptupleMapperImpl.java | 6 +- .../impl/mapper/SexdecupleMapperImpl.java | 14 +- .../tuple/impl/mapper/SingleMapperImpl.java | 27 +- .../impl/mapper/TredecupleMapperImpl.java | 10 +- .../impl/mapper/UndecupleMapperImpl.java | 157 +- .../impl/mapper/VigintupleMapperImpl.java | 22 +- .../com/redis/om/spring/util/ObjectUtils.java | 96 +- .../redis/om/spring/util/SpringContext.java | 12 +- .../vectorize/DefaultFeatureExtractor.java | 35 +- .../face/FaceDetectionTranslator.java | 304 ++- .../vectorize/face/FaceFeatureTranslator.java | 41 +- .../AbstractBaseDocumentSentinelTest.java | 31 +- .../om/spring/AbstractBaseDocumentTest.java | 12 +- .../spring/AbstractBaseEnhancedRedisTest.java | 12 +- .../redis/om/spring/AbstractBaseOMTest.java | 16 +- .../RedisEnhancedKeyValueAdapterTest.java | 41 +- .../spring/RedisJSONKeyValueAdapterTest.java | 18 +- .../java/com/redis/om/spring/TestConfig.java | 4 +- .../com/redis/om/spring/annotations/Doc.java | 2 +- .../DocRepositoriesAutoDiscoveryTest.java | 18 +- .../DocRepositoryBasePackageClassesTest.java | 22 +- .../HashRepositoriesAutoDiscoveryTest.java | 20 +- .../HashRepositoryBasePackageClassesTest.java | 24 +- .../AutoCompleteDeletionTest.java | 16 +- .../autocompletable/AutoCompleteTest.java | 16 +- .../RedisHashAutocompleteTest.java | 5 +- .../spring/annotations/bloom/BloomTest.java | 9 +- .../spring/annotations/cuckoo/CuckooTest.java | 8 +- .../document/AggregationAnnotationTest.java | 298 +-- .../BasicRedisDocumentMappingTest.java | 242 +-- .../document/ComplexDocumentSearchTest.java | 173 +- .../document/DocumentLanguageTest.java | 69 +- .../document/DocumentTTLTests.java | 28 +- .../annotations/document/EnumeratedTest.java | 26 +- .../ExplicitPrefixesDocumentTest.java | 3 +- .../ExplicitelyIndexedIdFieldsTest.java | 27 +- .../spring/annotations/document/IdTests.java | 1 - .../annotations/document/IndexFilterTest.java | 3 +- .../NonStandardDocumentSearchTest.java | 28 +- .../document/OptimisticLockingTest.java | 4 +- ...disDocumentCustomFallbackKeySpaceTest.java | 44 +- .../RedisDocumentQueryByExampleTest.java | 73 +- .../document/RedisDocumentSearchTest.java | 125 +- .../document/RedisDocumentWithAliasTest.java | 24 +- .../annotations/document/ReferenceTest.java | 57 +- .../document/RepositoryIssuesTest.java | 23 +- .../document/fixtures/Airport.java | 9 +- .../document/fixtures/AirportsRepository.java | 3 +- .../document/fixtures/BadDocRepository.java | 3 +- .../document/fixtures/CityRepository.java | 2 +- .../document/fixtures/CompanyRepository.java | 1 + .../document/fixtures/ComplexRepository.java | 2 +- .../document/fixtures/CountryRepository.java | 2 +- .../annotations/document/fixtures/Custom.java | 2 +- .../fixtures/CustomIndexDocRepository.java | 3 +- .../document/fixtures/CustomRepository.java | 3 +- .../DeepNestNonIndexedRepository.java | 3 +- .../document/fixtures/DeepNestRepository.java | 3 +- .../document/fixtures/DeveloperState.java | 3 +- .../document/fixtures/DeveloperType.java | 4 +- .../document/fixtures/Direccion.java | 3 +- .../document/fixtures/Doc2Repository.java | 3 +- .../document/fixtures/Doc3Repository.java | 3 +- .../document/fixtures/DocRepository.java | 3 +- .../document/fixtures/DocWithBoolean.java | 24 +- .../fixtures/DocWithBooleanRepository.java | 3 +- .../DocWithColonInPrefixRepository.java | 2 +- .../fixtures/DocWithCustomNameId.java | 3 +- .../DocWithCustomNameIdRepository.java | 3 +- .../document/fixtures/DocWithDate.java | 12 +- .../fixtures/DocWithDateRepository.java | 3 +- .../fixtures/DocWithEnumRepository.java | 3 +- .../fixtures/DocWithExplicitUlidId.java | 3 +- .../DocWithExplicitUlidIdRepository.java | 3 +- .../fixtures/DocWithIntegerIdRepository.java | 3 +- .../fixtures/DocWithLongRepository.java | 3 +- .../fixtures/DocWithSetsRepository.java | 6 +- .../document/fixtures/DocWithoutId.java | 2 +- .../document/fixtures/DocumentProjection.java | 7 +- .../fixtures/DocumentProjectionPojo.java | 14 +- .../DocumentProjectionRepository.java | 8 +- .../document/fixtures/ExpiringPerson.java | 11 +- .../ExpiringPersonDifferentTimeUnit.java | 8 +- ...ringPersonDifferentTimeUnitRepository.java | 4 +- .../fixtures/ExpiringPersonRepository.java | 3 +- .../fixtures/ExpiringPersonWithDefault.java | 3 +- .../ExpiringPersonWithDefaultRepository.java | 4 +- .../document/fixtures/FilmRepository.java | 2 + .../document/fixtures/FruitRepository.java | 6 +- .../document/fixtures/GameRepository.java | 436 +++-- .../fixtures/KitchenSinkRepository.java | 3 +- .../document/fixtures/Metadata.java | 6 +- .../document/fixtures/MetadataRepository.java | 3 +- .../document/fixtures/MovieRepository.java | 2 +- .../fixtures/MultiLingualDocRepository.java | 3 +- .../annotations/document/fixtures/MyDoc.java | 8 +- .../document/fixtures/MyDocQueriesImpl.java | 6 +- .../document/fixtures/MyDocRepository.java | 9 +- .../document/fixtures/MyJavaEnum.java | 4 +- .../fixtures/NiCompanyRepository.java | 3 +- .../document/fixtures/PermitRepository.java | 21 +- .../annotations/document/fixtures/Person.java | 23 +- .../document/fixtures/PersonAddress.java | 24 +- .../document/fixtures/PersonRepository.java | 2 +- .../document/fixtures/PizzaOrder.java | 21 +- .../fixtures/PizzaOrderRepository.java | 2 +- .../document/fixtures/Product.java | 24 +- .../document/fixtures/RefRepository.java | 2 +- .../document/fixtures/SomeDocument.java | 70 +- .../fixtures/SomeDocumentRepository.java | 3 +- .../fixtures/SpanishDocRepository.java | 3 +- .../document/fixtures/StateRepository.java | 2 +- .../document/fixtures/StatesRepository.java | 2 +- .../fixtures/TooManyReferencesRepository.java | 2 +- .../annotations/document/fixtures/User.java | 6 +- .../annotations/document/fixtures/User2.java | 2 +- .../document/fixtures/User2Repository.java | 9 +- .../document/fixtures/UserRepository.java | 3 +- .../document/fixtures/VersionedEntity.java | 4 +- .../document/fixtures/WithAlias.java | 3 +- .../fixtures/WithAliasRepository.java | 3 +- .../WithNestedListOfUUIDsRepository.java | 2 +- .../WithNestedListOfUlidsRepository.java | 2 +- .../document/fixtures/ZipCode.java | 3 +- .../document/sentinel/BasicSentinelTest.java | 4 +- .../serialization/SerializationTest.java | 65 +- .../vectorize/VectorizeDocumentTest.java | 90 +- .../hash/AggregationAnnotationTest.java | 256 +-- .../hash/BasicRedisHashMappingTest.java | 204 +- .../hash/ExplicitPrefixesHashTest.java | 3 +- .../hash/RedisHashQueryByExampleTest.java | 49 +- .../annotations/hash/RedisHashSearchTest.java | 113 +- .../annotations/hash/RedisHashTTLTests.java | 33 +- .../hash/RedisHashVSSIndexCreationTest.java | 68 +- .../hash/RedisHashWithAliasTest.java | 23 +- .../hash/fixtures/CompanyRepository.java | 6 +- .../hash/fixtures/CountryRepository.java | 2 +- .../annotations/hash/fixtures/Direccion.java | 3 +- .../hash/fixtures/EmailTakenImpl.java | 5 +- .../hash/fixtures/ExpiringPerson.java | 8 +- .../ExpiringPersonDifferentTimeUnit.java | 8 +- ...ringPersonDifferentTimeUnitRepository.java | 5 +- .../fixtures/ExpiringPersonRepository.java | 3 +- .../fixtures/ExpiringPersonWithDefault.java | 3 +- .../ExpiringPersonWithDefaultRepository.java | 5 +- .../hash/fixtures/GameRepository.java | 405 ++-- .../hash/fixtures/HashProjectionPojo.java | 14 +- .../fixtures/HashProjectionRepository.java | 8 +- .../fixtures/HashWithByteArrayFlatVector.java | 13 +- ...HashWithByteArrayFlatVectorRepository.java | 3 +- .../fixtures/HashWithByteArrayHNSWVector.java | 13 +- ...HashWithByteArrayHNSWVectorRepository.java | 3 +- .../HashWithColonInPrefixRepository.java | 2 +- .../hash/fixtures/HashWithVectors.java | 18 +- .../hash/fixtures/KitchenSink.java | 4 +- .../hash/fixtures/KitchenSinkRepository.java | 4 +- .../annotations/hash/fixtures/MyHash.java | 10 +- .../hash/fixtures/MyHashQueriesImpl.java | 6 +- .../hash/fixtures/MyHashRepository.java | 29 +- .../fixtures/NonIndexedHashRepository.java | 3 +- .../annotations/hash/fixtures/Person.java | 18 +- .../annotations/hash/fixtures/Person2.java | 14 +- .../hash/fixtures/Person2Repository.java | 3 +- .../hash/fixtures/PersonRepository.java | 7 +- .../annotations/hash/fixtures/Product.java | 24 +- .../annotations/hash/fixtures/Student.java | 2 - .../hash/fixtures/StudentRepository.java | 1 - .../annotations/hash/fixtures/WithAlias.java | 3 +- .../hash/fixtures/WithAliasRepository.java | 3 +- .../hash/serialization/SerializationTest.java | 131 +- .../hash/vectorize/VectorizeHashTest.java | 87 +- .../vectorize/face/FaceDetectionTest.java | 20 +- .../spring/client/RedisModulesClientTest.java | 27 +- .../om/spring/id/ULIDIdentifierTest.java | 49 +- .../metamodel/MetamodelGeneratorTest.java | 505 ++--- .../om/spring/ops/json/OpsForJSONTest.java | 200 +- .../om/spring/ops/pds/OpsForBloomTest.java | 16 +- .../ops/pds/OpsForCountMinSketchTest.java | 4 +- .../om/spring/ops/pds/OpsForPDSesTest.java | 15 +- .../om/spring/ops/search/JSONSearchTest.java | 56 +- .../spring/repository/AbstractDocument.java | 40 +- .../repository/DocumentProjectionTest.java | 89 +- .../spring/repository/HashProjectionTest.java | 92 +- .../spring/repository/InheritingDocument.java | 24 +- .../repository/InheritingDocumentTest.java | 93 +- .../om/spring/repository/SimpleDocument.java | 22 +- .../spring/repository/SimpleDocumentTest.java | 42 +- .../om/spring/repository/SimpleHash.java | 22 +- .../om/spring/repository/SimpleHashTest.java | 42 +- .../repository/query/QueryUtilsTest.java | 2 +- .../query/clause/QueryClauseTest.java | 25 +- .../search/stream/DialectSwitchTest.java | 44 +- .../search/stream/EntityStreamDocsTest.java | 1691 +++++++++-------- .../search/stream/EntityStreamHashTest.java | 1130 ++++++----- .../stream/EntityStreamHighlightHashTest.java | 40 +- ...tityStreamsAggregationsDocsPagingTest.java | 64 +- .../EntityStreamsAggregationsDocsTest.java | 964 +++++----- ...tityStreamsAggregationsHashPagingTest.java | 68 +- .../stream/EntityStreamsHashVSSTests.java | 89 +- .../stream/EntityStreamsIssuesTest.java | 540 +++--- ...ityStreamsZipCodeDataAggregationsTest.java | 183 +- .../stream/TestTupleJsonSerialization.java | 27 +- .../stream/WrapperSearchStreamTest.java | 308 +-- .../com/redis/om/spring/tuple/FieldsTest.java | 117 +- .../com/redis/om/spring/tuple/TupleTest.java | 1341 ++++++------- .../com/redis/om/spring/tuple/TuplesTest.java | 769 +++----- .../redis/om/spring/util/ObjectUtilsTest.java | 77 +- ...esultRawResponseToObjectConverterTest.java | 31 +- .../data/metamodel/ValidDocumentIndexed.java | 2 +- .../metamodel/ValidDocumentUnindexed.java | 6 +- 434 files changed, 11387 insertions(+), 10916 deletions(-) diff --git a/README.md b/README.md index d1f99c7a..fb64a63b 100644 --- a/README.md +++ b/README.md @@ -10,16 +10,17 @@ --- -**Redis OM Spring** extends [Spring Data Redis](https://spring.io/projects/spring-data-redis) to take full advantage of Redis and [Redis Stack](https://redis.io/docs/stack/). +**Redis OM Spring** extends [Spring Data Redis](https://spring.io/projects/spring-data-redis) to take full advantage of +Redis and [Redis Stack](https://redis.io/docs/stack/). | Stage | Release | Snapshot | Issues | Resolution | Code QL | License | SDR Ver. | -|---------------------------------------------------| -------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------- | ------------------------------------------------------- | +|---------------------------------------------------|----------------------------------------------|-------------------------------------------------|----------------------------------------------------------------------|---------------------------------------------------------------------------------|----------------------------------------------|------------------------------------------|---------------------------------------------------------| | [![Project stage][badge-stage]][badge-stage-page] | [![Releases][badge-releases]][link-releases] | [![Snapshots][badge-snapshots]][link-snapshots] | [![Percentage of issues still open][badge-open-issues]][open-issues] | [![Average time to resolve an issue][badge-issue-resolution]][issue-resolution] | [![CodeQL][badge-codeql]][badge-codeql-page] | [![License][license-image]][license-url] | [![SDR Version][sdr-badge-releases]][sdr-link-releases] | Learn / Discuss / Collaborate | Discord | Twitch | YouTube | Twitter | -| ----------------------------------------- | -------------------------------------- | ----------------------------------------- | ----------------------------------------- | +|-------------------------------------------|----------------------------------------|-------------------------------------------|-------------------------------------------| | [![Discord][discord-shield]][discord-url] | [![Twitch][twitch-shield]][twitch-url] | [![YouTube][youtube-shield]][youtube-url] | [![Twitter][twitter-shield]][twitter-url] |
@@ -31,23 +32,23 @@ Learn / Discuss / Collaborate - [💡 Why Redis OM?](#-why-redis-om) - [🍀 Redis OM Spring](#-redis-om-spring) - [🏁 Getting Started](#-getting-started) - - [🚀 Launch Redis](#-launch-redis) - - [The SpringBoot App](#the-springboot-app) - - [💁‍♂️ The Mapped Model](#-the-mapped-model) - - [🧰 The Repository](#-the-repository) - - [🚤 Querying with Entity Streams](#-querying-with-entity-streams) - - [👭 Entity Meta-model](#-entity-meta-model) + - [🚀 Launch Redis](#-launch-redis) + - [The SpringBoot App](#the-springboot-app) + - [💁‍♂️ The Mapped Model](#-the-mapped-model) + - [🧰 The Repository](#-the-repository) + - [🚤 Querying with Entity Streams](#-querying-with-entity-streams) + - [👭 Entity Meta-model](#-entity-meta-model) - [💻 Maven configuration](#-maven-configuration) - - [Official Releases](#official-releases) - - [Explicitly configuring OM as an annotation processor](#explicitly-configuring-om-as-an-annotation-processor) - - [Snapshots](#snapshots) + - [Official Releases](#official-releases) + - [Explicitly configuring OM as an annotation processor](#explicitly-configuring-om-as-an-annotation-processor) + - [Snapshots](#snapshots) - [🐘 Gradle configuration](#-gradle-configuration) - - [Add Repository - Snapshots Only](#add-repository---snapshots-only) - - [Dependency](#dependency) + - [Add Repository - Snapshots Only](#add-repository---snapshots-only) + - [Dependency](#dependency) - [📚 Documentation](#-documentation) - [Demos](#demos) - - [Embedded Demos](#embedded-demos) - - [External Demos](#external-demos) + - [Embedded Demos](#embedded-demos) + - [External Demos](#external-demos) - [⛏️ Troubleshooting](#-troubleshooting) - [✨ So How Do You Get RediSearch and RedisJSON?](#-so-how-do-you-get-redisearch-and-redisjson) - [💖 Contributing](#-contributing) @@ -60,23 +61,27 @@ Learn / Discuss / Collaborate ## 💡 Why Redis OM? -The Redis OM family of client libraries provide high-level abstractions, idiomatically implemented for your language and platform of choice. We currently cater to the Node, Python, .NET, and Spring communities. +The Redis OM family of client libraries provide high-level abstractions, idiomatically implemented for your language and +platform of choice. We currently cater to the Node, Python, .NET, and Spring communities. ## 🍀 Redis OM Spring -Redis OM Spring provides powerful repository and custom object-mapping abstractions built on top of the Spring Data Redis ([SDR](https://spring.io/projects/spring-data-redis)) framework. +Redis OM Spring provides powerful repository and custom object-mapping abstractions built on top of the Spring Data +Redis ([SDR](https://spring.io/projects/spring-data-redis)) framework. This **preview** release provides all Spring Data Redis, plus: * `@Document` annotation to map Spring Data models to Redis JSON documents * Enhancement to the Spring Data Redis `@RedisHash` via `@EnableRedisEnhancedRepositories`: - - uses Redis' native search engine (RediSearch) for secondary indexing - - uses [ULID](https://github.com/ulid/spec) for `@Id` annotated fields -* `RedisDocumentRepository` with automatic implementation of Repository interfaces for complex querying capabilities using `@EnableRedisDocumentRepositories` + - uses Redis' native search engine (RediSearch) for secondary indexing + - uses [ULID](https://github.com/ulid/spec) for `@Id` annotated fields +* `RedisDocumentRepository` with automatic implementation of Repository interfaces for complex querying capabilities + using `@EnableRedisDocumentRepositories` * Declarative search indexes via `@Indexed` * Full-text search indexes via `@Searchable` * `EntityStream`s: Streams-based Query and Aggregations Builder -* `@Bloom` annotation to determine very fast, with and with high degree of certainty, whether a value is in a collection. +* `@Bloom` annotation to determine very fast, with and with high degree of certainty, whether a value is in a + collection. * `@Vectorize` annotation to generate embeddings for text and images for use in Vector Similarity Searches * Vector Similarity Search API (See [Redis Stack Vectors](https://redis.io/docs/stack/search/reference/vectors/)) @@ -140,7 +145,8 @@ spring: ### The SpringBoot App Use the `@EnableRedisDocumentRepositories` annotation to scan for `@Document` annotated Spring models, -Inject repositories beans implementing `RedisDocumentRepository` which you can use for CRUD operations and custom queries (all by declaring Spring Data Query Interfaces): +Inject repositories beans implementing `RedisDocumentRepository` which you can use for CRUD operations and custom +queries (all by declaring Spring Data Query Interfaces): ```java package com.redis.om.documents; @@ -198,7 +204,8 @@ public class RomsDocumentsApplication { ### 💁‍♂️ The Mapped Model Like many other Spring Data projects, an annotation at the class level determines how instances -of the class are persisted. Redis OM Spring provides the `@Document` annotation to persist models as JSON documents using RedisJSON: +of the class are persisted. Redis OM Spring provides the `@Document` annotation to persist models as JSON documents +using RedisJSON: ```java package com.redis.om.documents.domain; @@ -226,14 +233,18 @@ import lombok.*; } ``` -Redis OM Spring, replaces the conventional `UUID` primary key strategy generation with a `ULID` (Universally Unique Lexicographically Sortable Identifier) which is faster to generate and easier on the eyes. +Redis OM Spring, replaces the conventional `UUID` primary key strategy generation with a `ULID` (Universally Unique +Lexicographically Sortable Identifier) which is faster to generate and easier on the eyes. ### 🧰 The Repository -Redis OM Spring data repository's goal, like other Spring Data repositories, is to significantly reduce the amount of boilerplate code required to implement data access. Simply create a Java interface -that extends `RedisDocumentRepository` that takes the domain class to manage as well as the ID type of the domain class as type arguments. `RedisDocumentRepository` extends the Spring Data class `PagingAndSortingRepository`. +Redis OM Spring data repository's goal, like other Spring Data repositories, is to significantly reduce the amount of +boilerplate code required to implement data access. Simply create a Java interface +that extends `RedisDocumentRepository` that takes the domain class to manage as well as the ID type of the domain class +as type arguments. `RedisDocumentRepository` extends the Spring Data class `PagingAndSortingRepository`. -Declare query methods on the interface. You can both, expose CRUD methods or create declarations for complex queries that Redis OM Spring will fulfill at runtime: +Declare query methods on the interface. You can both, expose CRUD methods or create declarations for complex queries +that Redis OM Spring will fulfill at runtime: ```java package com.redis.om.documents.repositories; @@ -277,11 +288,17 @@ The repository proxy has two ways to derive a store-specific query from the meth ### 🚤 Querying with Entity Streams -Redis OM Spring Entity Streams provides a Java 8 Streams interface to Query Redis JSON documents using RediSearch. Entity Streams allow you to process data in a type safe declarative way similar to SQL statements. Streams can be used to express a query as a chain of operations. +Redis OM Spring Entity Streams provides a Java 8 Streams interface to Query Redis JSON documents using RediSearch. +Entity Streams allow you to process data in a type safe declarative way similar to SQL statements. Streams can be used +to express a query as a chain of operations. -Entity Streams in Redis OM Spring provides the same semantics as Java 8 streams. Streams can be made of Redis Mapped entities (`@Document`) or one or more properties of an Entity. Entity Streams progressively build the query until a terminal operation is invoked (such as `collect`). Whenever a Terminal operation is applied to a Stream, the Stream cannot accept additional operations to its pipeline and it also means that the Stream is started. +Entity Streams in Redis OM Spring provides the same semantics as Java 8 streams. Streams can be made of Redis Mapped +entities (`@Document`) or one or more properties of an Entity. Entity Streams progressively build the query until a +terminal operation is invoked (such as `collect`). Whenever a Terminal operation is applied to a Stream, the Stream +cannot accept additional operations to its pipeline and it also means that the Stream is started. -Let's start with a simple example, a Spring `@Service` which includes `EntityStream` to query for instances of the mapped class `Person`: +Let's start with a simple example, a Spring `@Service` which includes `EntityStream` to query for instances of the +mapped class `Person`: ```java package com.redis.om.skeleton.services; @@ -310,13 +327,19 @@ public class PeopleService { } ``` -The `EntityStream` is injected into the `PeopleService` using `@Autowired`. We can then get a stream for `Person` objects by using `entityStream.of(Person.class)`. At this point the stream represents the equivalent of a `SELECT * FROM Person` on a relational database. The call to `collect` will then execute the underlying query and return a collection of all `Person` objects in Redis. +The `EntityStream` is injected into the `PeopleService` using `@Autowired`. We can then get a stream for `Person` +objects by using `entityStream.of(Person.class)`. At this point the stream represents the equivalent of +a `SELECT * FROM Person` on a relational database. The call to `collect` will then execute the underlying query and +return a collection of all `Person` objects in Redis. #### 👭 Entity Meta-model -To produce more elaborate queries, you're provided with a generated metamodel, which is a class with the same name as your model but ending with a dollar sign. In the -example below, our entity model is `Person` therefore we get a metamodel named `Person$`. With the metamodel you have access to the operations related to the -underlying search engine field. For example, in the example we have an `age` property which is an integer. Therefore, our metamodel has an `AGE` property which has +To produce more elaborate queries, you're provided with a generated metamodel, which is a class with the same name as +your model but ending with a dollar sign. In the +example below, our entity model is `Person` therefore we get a metamodel named `Person$`. With the metamodel you have +access to the operations related to the +underlying search engine field. For example, in the example we have an `age` property which is an integer. Therefore, +our metamodel has an `AGE` property which has numeric operations we can use with the stream's `filter` method such as `between`. ```java @@ -330,9 +353,11 @@ public Iterable findByAgeBetween(int minAge, int maxAge) { } ``` -In this example we also make use of the Streams `sorted` method to declare that our stream will be sorted by the `Person$.AGE` in `ASC`ending order. +In this example we also make use of the Streams `sorted` method to declare that our stream will be sorted by +the `Person$.AGE` in `ASC`ending order. -Check out the full set of tests for [EntityStreams](https://github.com/redis/redis-om-spring/tree/main/redis-om-spring/src/test/java/com/redis/om/spring/search/stream) +Check out the full set of tests +for [EntityStreams](https://github.com/redis/redis-om-spring/tree/main/redis-om-spring/src/test/java/com/redis/om/spring/search/stream) ### 👯‍️ Querying by Example (QBE) @@ -343,10 +368,13 @@ write queries by using store-specific query languages at all. #### QBE Usage The Query by Example API consists of four parts: + * **Probe**: The actual example of a domain object with populated fields. -* **ExampleMatcher**: The `ExampleMatcher` carries details on how to match particular fields. It can be reused across multiple `Examples`. +* **ExampleMatcher**: The `ExampleMatcher` carries details on how to match particular fields. It can be reused across + multiple `Examples`. * **Example**: An Example consists of the probe and the ExampleMatcher. It is used to create the query. -* **FetchableFluentQuery**: A `FetchableFluentQuery` offers a fluent API, that allows further customization of a query derived from an `Example`. +* **FetchableFluentQuery**: A `FetchableFluentQuery` offers a fluent API, that allows further customization of a query + derived from an `Example`. Using the fluent API lets you specify ordering projection and result processing for your query. Query by Example is well suited for several use cases: @@ -355,7 +383,8 @@ Query by Example is well suited for several use cases: * Frequent refactoring of the domain objects without worrying about breaking existing queries. * Working independently of the underlying data store API. -For example, if you have an `@Document` or `@RedisHash` annotated entity you can create an instance, partially populate its +For example, if you have an `@Document` or `@RedisHash` annotated entity you can create an instance, partially populate +its properties, create an `Example` from it, and used the `findAll` method to query for similar entities: ```java @@ -407,7 +436,7 @@ inherited from the parent poms): com.redis.om redis-om-spring - 0.9.1-SNAPSHOT + 0.9.1 @@ -451,9 +480,10 @@ repositories { ``` ### Dependency + ```groovy ext { - redisOmVersion = '0.9.1-SNAPSHOT' + redisOmVersion = '0.9.1' } dependencies { @@ -473,35 +503,36 @@ The Redis OM documentation is available [here](docs/index.md). These can be found in the `/demos` folder: - **roms-documents**: - - Simple API example of `@Document` mapping, Spring Repositories and Querying. - - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-documents` + - Simple API example of `@Document` mapping, Spring Repositories and Querying. + - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-documents` - **roms-hashes**: - - Simple API example of `@RedisHash`, enhanced secondary indices and querying. - - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-hashes` + - Simple API example of `@RedisHash`, enhanced secondary indices and querying. + - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-hashes` - **roms-permits**: - - Port of [Elena Kolevska's](https://github.com/elena-kolevska) Quick Start: Using RediSearch with JSON [Demo][redisearch-json] to Redis OM Spring. - - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-permits` + - Port of [Elena Kolevska's](https://github.com/elena-kolevska) Quick Start: Using RediSearch with + JSON [Demo][redisearch-json] to Redis OM Spring. + - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-permits` - **roms-vss**: - - Port of [Redis Vector Search Demo](https://github.com/RedisVentures/redis-product-search). - - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-vss` + - Port of [Redis Vector Search Demo](https://github.com/RedisVentures/redis-product-search). + - Run with `./mvnw install -Dmaven.test.skip && ./mvnw spring-boot:run -pl demos/roms-vss` ### External Demos - **redis-om-spring-skeleton-app**: - - Redis OM Spring Skeleton App - - Repo: https://github.com/redis-developer/redis-om-spring-skeleton-app + - Redis OM Spring Skeleton App + - Repo: https://github.com/redis-developer/redis-om-spring-skeleton-app - **redis-om-spring-react-todomvc**: - - Redis OM Spring to build a RESTful API that satisfies the simple web API spec set by - the Todo-Backend project using JSON Documents stored in Redis. - - Repo: https://github.com/redis-developer/redis-om-spring-react-todomvc + - Redis OM Spring to build a RESTful API that satisfies the simple web API spec set by + the Todo-Backend project using JSON Documents stored in Redis. + - Repo: https://github.com/redis-developer/redis-om-spring-react-todomvc - **redis-om-autocomplete-demo**: - - A Spring Boot demo of autocomplete functionality using Redis OM Spring. - - Repo: https://github.com/redis-developer/redis-om-autocomplete-demo + - A Spring Boot demo of autocomplete functionality using Redis OM Spring. + - Repo: https://github.com/redis-developer/redis-om-autocomplete-demo ## ⛏️ Troubleshooting @@ -514,7 +545,8 @@ hit us up on the [Redis Discord Server](http://discord.gg/redis). Redis OM relies on two source available Redis modules: [RediSearch][redisearch-url] and [RedisJSON][redis-json-url]. -You can run these modules in your self-hosted Redis deployment, or you can use [Redis Enterprise][redis-enterprise-url], which includes both modules. +You can run these modules in your self-hosted Redis deployment, or you can use [Redis Enterprise][redis-enterprise-url], +which includes both modules. To learn more, read [our documentation](docs/redis_modules.md). @@ -522,9 +554,11 @@ To learn more, read [our documentation](docs/redis_modules.md). We'd love your contributions! -**Bug reports** are especially helpful at this stage of the project. [You can open a bug report on GitHub](https://github.com/redis-om/redis-om-spring/issues/new). +**Bug reports** are especially helpful at this stage of the +project. [You can open a bug report on GitHub](https://github.com/redis-om/redis-om-spring/issues/new). -You can also **contribute documentation** -- or just let us know if something needs more detail. [Open an issue on GitHub](https://github.com/redis-om/redis-om-spring/issues/new) to get started. +You can also **contribute documentation** -- or just let us know if something needs more +detail. [Open an issue on GitHub](https://github.com/redis-om/redis-om-spring/issues/new) to get started. ## 🧑‍🤝‍🧑 Sibling Projects @@ -539,41 +573,73 @@ Redis OM uses the [MIT license][license-url]. [ci-url]: https://github.com/redis-developer/redis-om-spring/actions/workflows/ci.yml + [badge-stage]: https://img.shields.io/badge/Project%20Stage-Development-green.svg + [badge-stage-page]: https://github.com/redis/redis-om-spring/wiki/Project-Stages + [badge-snapshots]: https://img.shields.io/nexus/s/https/s01.oss.sonatype.org/com.redis.om/redis-om-spring.svg + [badge-releases]: https://img.shields.io/maven-central/v/com.redis.om/redis-om-spring + [badge-open-issues]: http://isitmaintained.com/badge/open/redis/redis-om-spring.svg + [badge-issue-resolution]: http://isitmaintained.com/badge/resolution/redis/redis-om-spring.svg + [badge-codeql]: https://github.com/redis/redis-om-spring/actions/workflows/codeql-analysis.yml/badge.svg + [badge-codeql-page]: https://github.com/redis/redis-om-spring/actions/workflows/codeql-analysis.yml + [license-image]: https://img.shields.io/github/license/redis/redis-om-spring + [license-url]: LICENSE + [sdr-badge-releases]: https://img.shields.io/maven-central/v/org.springframework.data/spring-data-redis/3.1.2 + [discord-shield]: https://img.shields.io/discord/697882427875393627?style=social&logo=discord + [twitch-shield]: https://img.shields.io/twitch/status/redisinc?style=social + [twitter-shield]: https://img.shields.io/twitter/follow/redisinc?style=social + [youtube-shield]: https://img.shields.io/youtube/channel/views/UCD78lHSwYqMlyetR0_P4Vig?style=social [redis-om-website]: https://developer.redis.com + [redis-om-python]: https://github.com/redis-om/redis-om-python + [redis-om-js]: https://github.com/redis-om/redis-om-js + [redis-om-dotnet]: https://github.com/redis-om/redis-om-dotnet + [redisearch-url]: https://oss.redis.com/redisearch/ + [redis-json-url]: https://oss.redis.com/redisjson/ + [ulid-url]: https://github.com/ulid/spec + [redis-enterprise-url]: https://redis.com/try-free/ + [link-snapshots]: https://s01.oss.sonatype.org/content/repositories/snapshots/com/redis/om/redis-om-spring/ + [link-releases]: https://repo1.maven.org/maven2/com/redis/om/redis-om-spring/ + [open-issues]: http://isitmaintained.com/project/redis/redis-om-spring + [issue-resolution]: http://isitmaintained.com/project/redis/redis-om-spring + [redisearch-json]: https://github.com/redislabs-training/mod-devcap-redisjson-getting-started/blob/master/articles/QuickStart-RediSearchWithJSON.md + [sdr-link-releases]: https://repo1.maven.org/maven2/org/springframework/data/spring-data-redis/3.0.1/ + [discord-url]: http://discord.gg/redis + [twitch-url]: https://www.twitch.tv/redisinc + [twitter-url]: https://twitter.com/redisinc + [youtube-url]: https://www.youtube.com/redisinc diff --git a/demos/roms-documents/pom.xml b/demos/roms-documents/pom.xml index a1cdbed5..c9281585 100644 --- a/demos/roms-documents/pom.xml +++ b/demos/roms-documents/pom.xml @@ -1,13 +1,13 @@ - + 4.0.0 org.springframework.boot spring-boot-starter-parent 3.2.5 - + com.redis.om @@ -31,7 +31,7 @@ com.redis.om redis-om-spring - 0.9.1-SNAPSHOT + 0.9.1 org.springframework.boot @@ -65,11 +65,11 @@ ${testcontainers.redis.version} test - - - - - + + + + + @@ -147,7 +147,7 @@ com.redis.om redis-om-spring - 0.9.1-SNAPSHOT + 0.9.1 diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/RomsDocumentsApplication.java b/demos/roms-documents/src/main/java/com/redis/om/documents/RomsDocumentsApplication.java index c1c5a342..cd113e7d 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/RomsDocumentsApplication.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/RomsDocumentsApplication.java @@ -25,14 +25,20 @@ public class RomsDocumentsApplication { @Autowired PersonRepository personRepo; + public static void main(String[] args) { + SpringApplication.run(RomsDocumentsApplication.class, args); + } + @Bean CommandLineRunner loadTestData() { return args -> { companyRepo.deleteAll(); - Company redis = Company.of("Redis", "https://redis.com", new Point(-122.066540, 37.377690), 526, 2011, Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag")))); + Company redis = Company.of("Redis", "https://redis.com", new Point(-122.066540, 37.377690), 526, 2011, + Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag")))); redis.setTags(Set.of("fast", "scalable", "reliable")); - Company microsoft = Company.of("Microsoft", "https://microsoft.com", new Point(-122.124500, 47.640160), 182268, 1975, Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag")))); + Company microsoft = Company.of("Microsoft", "https://microsoft.com", new Point(-122.124500, 47.640160), 182268, + 1975, Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag")))); microsoft.setTags(Set.of("innovative", "reliable")); companyRepo.save(redis); @@ -46,8 +52,4 @@ CommandLineRunner loadTestData() { }; } - public static void main(String[] args) { - SpringApplication.run(RomsDocumentsApplication.class, args); - } - } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/CompanyController.java b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/CompanyController.java index eeeb293d..808a72f9 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/CompanyController.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/CompanyController.java @@ -18,22 +18,22 @@ public class CompanyController { @Autowired CompanyRepository repository; - + @GetMapping("employees/count/{count}") Iterable byNumberOfEmployees(@PathVariable("count") int count) { return repository.findByNumberOfEmployees(count); } - + @GetMapping("employees/range/{low}/{high}") Iterable byNumberOfEmployeesRange(@PathVariable("low") int low, @PathVariable("high") int high) { return repository.findByNumberOfEmployeesBetween(low, high); } - + @GetMapping("all") Page all(Pageable pageable) { return repository.findAll(pageable); } - + @GetMapping("all-ids") Page allIds(Pageable pageable) { return repository.getIds(pageable); @@ -41,12 +41,12 @@ Page allIds(Pageable pageable) { @GetMapping("near") Iterable byLocationNear(// - @RequestParam("lat") double lat, // - @RequestParam("lon") double lon, // - @RequestParam("d") double distance) { + @RequestParam("lat") double lat, // + @RequestParam("lon") double lon, // + @RequestParam("d") double distance) { return repository.findByLocationNear(new Point(lon, lat), new Distance(distance, Metrics.MILES)); } - + @GetMapping("name/starts/{prefix}") Iterable byNameStartingWith(@PathVariable("prefix") String prefix) { return repository.findByNameStartingWith(prefix); diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/EventController.java b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/EventController.java index 2aaec5e7..438e9b2a 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/EventController.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/EventController.java @@ -17,14 +17,13 @@ @RequiredArgsConstructor public class EventController { - private final EventService eventService; + private final EventService eventService; - @GetMapping("between") - List byNumberOfEmployees(@RequestParam("start") - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start, - @RequestParam("end") - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) { - return eventService.searchByBeginDateBetween(start, end); - } + @GetMapping("between") + List byNumberOfEmployees( + @RequestParam("start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start, + @RequestParam("end") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) { + return eventService.searchByBeginDateBetween(start, end); + } } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/PersonController.java b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/PersonController.java index 5d3d3b20..eef650dc 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/PersonController.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/controllers/PersonController.java @@ -20,23 +20,23 @@ public class PersonController { @Autowired PersonRepository repository; - + @GetMapping("all") Page all(Pageable pageable) { return repository.findAll(pageable); } - + @GetMapping("all-ids") Page allIds(Pageable pageable) { return repository.getIds(pageable); } - + @GetMapping("name/{last}/{first}") List byLastAndFirst(// - @PathVariable("last") String last, @PathVariable("first") String first) { + @PathVariable("last") String last, @PathVariable("first") String first) { return repository.findByLastNameAndFirstName(last, first); } - + @GetMapping("{id}") Optional byId(@PathVariable("id") String id) { return repository.findById(id); diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Company.java b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Company.java index 5a749e42..a1b35ee4 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Company.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Company.java @@ -49,12 +49,12 @@ public class Company { private Set metaList; private boolean publiclyListed; - + // audit fields - + @CreatedDate private Date createdDate; - + @LastModifiedDate private Date lastModifiedDate; } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Event.java b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Event.java index 082ccc1f..dd53d522 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Event.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Event.java @@ -14,17 +14,17 @@ @AllArgsConstructor @Document public class Event { - @Id - private String id; + @Id + private String id; - @NonNull - @Searchable - private String name; + @NonNull + @Searchable + private String name; - @Indexed - private LocalDateTime beginDate; + @Indexed + private LocalDateTime beginDate; - @Indexed - private LocalDateTime endDate; + @Indexed + private LocalDateTime endDate; } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Person.java b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Person.java index 1eda0c69..0a24198d 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Person.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/domain/Person.java @@ -14,15 +14,15 @@ public class Person { @Id private String id; - + @NonNull @TextIndexed private String firstName; - + @NonNull @TextIndexed private String lastName; - + @NonNull @TagIndexed private String email; diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/repositories/CompanyRepository.java b/demos/roms-documents/src/main/java/com/redis/om/documents/repositories/CompanyRepository.java index e4b90b5b..f8904a8c 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/repositories/CompanyRepository.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/repositories/CompanyRepository.java @@ -13,20 +13,20 @@ public interface CompanyRepository extends RedisDocumentRepository { // find one by property Optional findOneByName(String name); - + // geospatial query - Iterable findByLocationNear(Point point, Distance distance); - + Iterable findByLocationNear(Point point, Distance distance); + // find by tag field, using JRediSearch "native" annotation @Query("@tags:{$tags}") Iterable findByTags(@Param("tags") Set tags); - + // find by numeric property Iterable findByNumberOfEmployees(int noe); - + // find by numeric property range Iterable findByNumberOfEmployeesBetween(int noeGT, int noeLT); - + // starting with/ending with Iterable findByNameStartingWith(String prefix); } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/service/EventService.java b/demos/roms-documents/src/main/java/com/redis/om/documents/service/EventService.java index 779b320f..c5ad6286 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/service/EventService.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/service/EventService.java @@ -6,5 +6,5 @@ import java.util.List; public interface EventService { - List searchByBeginDateBetween(LocalDateTime start, LocalDateTime end); + List searchByBeginDateBetween(LocalDateTime start, LocalDateTime end); } diff --git a/demos/roms-documents/src/main/java/com/redis/om/documents/service/impl/EventServiceImpl.java b/demos/roms-documents/src/main/java/com/redis/om/documents/service/impl/EventServiceImpl.java index 6ff6d324..513627d8 100644 --- a/demos/roms-documents/src/main/java/com/redis/om/documents/service/impl/EventServiceImpl.java +++ b/demos/roms-documents/src/main/java/com/redis/om/documents/service/impl/EventServiceImpl.java @@ -15,13 +15,11 @@ @RequiredArgsConstructor public class EventServiceImpl implements EventService { - private final EntityStream entityStream; + private final EntityStream entityStream; - @Override - public List searchByBeginDateBetween(LocalDateTime start, LocalDateTime end) { + @Override + public List searchByBeginDateBetween(LocalDateTime start, LocalDateTime end) { - return entityStream.of(Event.class) - .filter(Event$.BEGIN_DATE.between(start, end)) - .collect(Collectors.toList()); - } + return entityStream.of(Event.class).filter(Event$.BEGIN_DATE.between(start, end)).collect(Collectors.toList()); + } } diff --git a/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractDocumentTest.java b/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractDocumentTest.java index be9e915a..74f84fdc 100644 --- a/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractDocumentTest.java +++ b/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractDocumentTest.java @@ -10,13 +10,12 @@ @Testcontainers @DirtiesContext @SpringBootTest( - classes = AbstractDocumentTest.Config.class, - properties = {"spring.main.allow-bean-definition-overriding=true"} + classes = AbstractDocumentTest.Config.class, properties = { "spring.main.allow-bean-definition-overriding=true" } ) public abstract class AbstractDocumentTest extends AbstractTest { - @SpringBootApplication - @Configuration - @EnableRedisDocumentRepositories - static class Config extends TestConfig { - } + @SpringBootApplication + @Configuration + @EnableRedisDocumentRepositories + static class Config extends TestConfig { + } } diff --git a/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractTest.java b/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractTest.java index d52141c9..d914afb4 100644 --- a/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractTest.java +++ b/demos/roms-documents/src/test/java/com/redis/om/documents/AbstractTest.java @@ -18,36 +18,36 @@ @Testcontainers(disabledWithoutDocker = true) @DirtiesContext public abstract class AbstractTest { - @Container - static final RedisStackContainer REDIS; + @Container + static final RedisStackContainer REDIS; - static { - REDIS = new RedisStackContainer(DEFAULT_IMAGE_NAME.withTag("edge")).withReuse(true); - REDIS.start(); - } + static { + REDIS = new RedisStackContainer(DEFAULT_IMAGE_NAME.withTag("edge")).withReuse(true); + REDIS.start(); + } - @Autowired - protected StringRedisTemplate template; + @Autowired + protected StringRedisTemplate template; - @Autowired - protected RedisModulesOperations modulesOperations; + @Autowired + protected RedisModulesOperations modulesOperations; - @Autowired - @Qualifier("redisCustomKeyValueTemplate") - protected CustomRedisKeyValueTemplate kvTemplate; + @Autowired + @Qualifier("redisCustomKeyValueTemplate") + protected CustomRedisKeyValueTemplate kvTemplate; - @Autowired - protected RediSearchIndexer indexer; + @Autowired + protected RediSearchIndexer indexer; - @DynamicPropertySource - static void properties(DynamicPropertyRegistry registry) { - registry.add("spring.redis.host", REDIS::getHost); - registry.add("spring.redis.port", REDIS::getFirstMappedPort); - } + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("spring.redis.host", REDIS::getHost); + registry.add("spring.redis.port", REDIS::getFirstMappedPort); + } - protected void flushSearchIndexFor(Class entityClass) { - indexer.dropIndexAndDocumentsFor(entityClass); - indexer.createIndexFor(entityClass); - } + protected void flushSearchIndexFor(Class entityClass) { + indexer.dropIndexAndDocumentsFor(entityClass); + indexer.createIndexFor(entityClass); + } } diff --git a/demos/roms-documents/src/test/java/com/redis/om/documents/RomsDocumentsApplicationTests.java b/demos/roms-documents/src/test/java/com/redis/om/documents/RomsDocumentsApplicationTests.java index abb19c78..104a2fe7 100644 --- a/demos/roms-documents/src/test/java/com/redis/om/documents/RomsDocumentsApplicationTests.java +++ b/demos/roms-documents/src/test/java/com/redis/om/documents/RomsDocumentsApplicationTests.java @@ -5,8 +5,8 @@ //@SpringBootTest class RomsDocumentsApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/demos/roms-documents/src/test/java/com/redis/om/documents/TestConfig.java b/demos/roms-documents/src/test/java/com/redis/om/documents/TestConfig.java index 1cc434f3..2f365701 100644 --- a/demos/roms-documents/src/test/java/com/redis/om/documents/TestConfig.java +++ b/demos/roms-documents/src/test/java/com/redis/om/documents/TestConfig.java @@ -13,36 +13,36 @@ import java.time.Duration; public class TestConfig { - @Autowired - Environment env; + @Autowired + Environment env; - @Bean - public JedisConnectionFactory jedisConnectionFactory() { - String host = env.getProperty("spring.redis.host", "localhost"); - int port = env.getProperty("spring.redis.port", Integer.class, 6379); + @Bean + public JedisConnectionFactory jedisConnectionFactory() { + String host = env.getProperty("spring.redis.host", "localhost"); + int port = env.getProperty("spring.redis.port", Integer.class, 6379); - RedisStandaloneConfiguration conf = new RedisStandaloneConfiguration(host, port); + RedisStandaloneConfiguration conf = new RedisStandaloneConfiguration(host, port); - final JedisPoolConfig poolConfig = new JedisPoolConfig(); - poolConfig.setTestWhileIdle(false); - poolConfig.setMinEvictableIdleDuration(Duration.ofMillis(60000)); - poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(30000)); - poolConfig.setNumTestsPerEvictionRun(-1); + final JedisPoolConfig poolConfig = new JedisPoolConfig(); + poolConfig.setTestWhileIdle(false); + poolConfig.setMinEvictableIdleDuration(Duration.ofMillis(60000)); + poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(30000)); + poolConfig.setNumTestsPerEvictionRun(-1); - final int timeout = 10000; + final int timeout = 10000; - final JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder() - .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout)).usePooling() - .poolConfig(poolConfig).build(); + final JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder() + .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout)).usePooling() + .poolConfig(poolConfig).build(); - return new JedisConnectionFactory(conf, jedisClientConfiguration); - } + return new JedisConnectionFactory(conf, jedisClientConfiguration); + } - @Bean - public StringRedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { - StringRedisTemplate template = new StringRedisTemplate(); - template.setConnectionFactory(connectionFactory); + @Bean + public StringRedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { + StringRedisTemplate template = new StringRedisTemplate(); + template.setConnectionFactory(connectionFactory); - return template; - } + return template; + } } diff --git a/demos/roms-documents/src/test/java/com/redis/om/documents/controllers/EventControllerTest.java b/demos/roms-documents/src/test/java/com/redis/om/documents/controllers/EventControllerTest.java index 27364c91..639e17d3 100644 --- a/demos/roms-documents/src/test/java/com/redis/om/documents/controllers/EventControllerTest.java +++ b/demos/roms-documents/src/test/java/com/redis/om/documents/controllers/EventControllerTest.java @@ -20,57 +20,49 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @AutoConfigureMockMvc class EventControllerTest extends AbstractDocumentTest { - @Autowired - private MockMvc mvc; - @Autowired - private EventRepository eventRepository; - - @BeforeEach - void init() { - var event1 = new Event("1", "event 1", LocalDateTime.parse("2023-01-01T00:00:00.000"), LocalDateTime.parse("2023-01-02T00:00:00.000")); - var event2 = new Event("2", "event 2", LocalDateTime.parse("2023-03-08T00:00:00.000"), LocalDateTime.parse("2023-03-09T00:00:00.000")); + @Autowired + private MockMvc mvc; + @Autowired + private EventRepository eventRepository; - eventRepository.saveAll(List.of(event1, event2)); - } + @BeforeEach + void init() { + var event1 = new Event("1", "event 1", LocalDateTime.parse("2023-01-01T00:00:00.000"), + LocalDateTime.parse("2023-01-02T00:00:00.000")); + var event2 = new Event("2", "event 2", LocalDateTime.parse("2023-03-08T00:00:00.000"), + LocalDateTime.parse("2023-03-09T00:00:00.000")); - @AfterEach - void clear() { - eventRepository.deleteAll(); - } + eventRepository.saveAll(List.of(event1, event2)); + } - @Test - void shouldReturnAllEvents() throws Exception { - var all = eventRepository.findAll(); - assertEquals(2, all.size()); + @AfterEach + void clear() { + eventRepository.deleteAll(); + } - mvc.perform(MockMvcRequestBuilders - .get("/api/events/between") - .param("start", LocalDateTime.parse("2023-02-01T00:00:00.000").toString()) - .param("end", LocalDateTime.parse("2023-04-01T00:00:00.000").toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id", - equalTo("2")) - ); - } + @Test + void shouldReturnAllEvents() throws Exception { + var all = eventRepository.findAll(); + assertEquals(2, all.size()); - @Test - void shouldReturnEmpty() throws Exception { - var all = eventRepository.findAll(); - assertEquals(2, all.size()); + mvc.perform(MockMvcRequestBuilders.get("/api/events/between") + .param("start", LocalDateTime.parse("2023-02-01T00:00:00.000").toString()) + .param("end", LocalDateTime.parse("2023-04-01T00:00:00.000").toString())).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id", equalTo("2"))); + } - mvc.perform(MockMvcRequestBuilders - .get("/api/events/between") - .param("start", LocalDateTime.parse("2023-03-09T00:00:00.000").toString()) - .param("end", LocalDateTime.parse("2023-04-01T00:00:00.000").toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(0))); - } + @Test + void shouldReturnEmpty() throws Exception { + var all = eventRepository.findAll(); + assertEquals(2, all.size()); + mvc.perform(MockMvcRequestBuilders.get("/api/events/between") + .param("start", LocalDateTime.parse("2023-03-09T00:00:00.000").toString()) + .param("end", LocalDateTime.parse("2023-04-01T00:00:00.000").toString())).andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(0))); + } } \ No newline at end of file diff --git a/demos/roms-hashes/README.md b/demos/roms-hashes/README.md index ebcc97fa..b951864b 100644 --- a/demos/roms-hashes/README.md +++ b/demos/roms-hashes/README.md @@ -1,3 +1,4 @@ # Redis OM Spring Demo - Hashes -Demonstrates secondary indexes using RediSearch via the enhanced Redis OM Spring `@Indexed` annotation (`com.redis.om.spring.annotations.Indexed`) on `@RediHash` mapped models. \ No newline at end of file +Demonstrates secondary indexes using RediSearch via the enhanced Redis OM Spring `@Indexed` +annotation (`com.redis.om.spring.annotations.Indexed`) on `@RediHash` mapped models. \ No newline at end of file diff --git a/demos/roms-hashes/src/main/java/com/redis/om/hashes/RomsHashesApplication.java b/demos/roms-hashes/src/main/java/com/redis/om/hashes/RomsHashesApplication.java index 6934862e..3b4f31f0 100644 --- a/demos/roms-hashes/src/main/java/com/redis/om/hashes/RomsHashesApplication.java +++ b/demos/roms-hashes/src/main/java/com/redis/om/hashes/RomsHashesApplication.java @@ -23,6 +23,10 @@ public class RomsHashesApplication { @Autowired private RoleRepository roleRepo; + public static void main(String[] args) { + SpringApplication.run(RomsHashesApplication.class, args); + } + @Bean CommandLineRunner loadTestData() { return args -> { @@ -43,8 +47,4 @@ CommandLineRunner loadTestData() { }; } - public static void main(String[] args) { - SpringApplication.run(RomsHashesApplication.class, args); - } - } diff --git a/demos/roms-hashes/src/main/java/com/redis/om/hashes/controllers/UserController.java b/demos/roms-hashes/src/main/java/com/redis/om/hashes/controllers/UserController.java index ff59c551..6f5b9283 100644 --- a/demos/roms-hashes/src/main/java/com/redis/om/hashes/controllers/UserController.java +++ b/demos/roms-hashes/src/main/java/com/redis/om/hashes/controllers/UserController.java @@ -19,17 +19,17 @@ public class UserController { public User save(@RequestBody User user) { return userRepository.save(user); } - + @GetMapping("/q") public List findByName(@RequestParam String firstName, @RequestParam String lastName) { return userRepository.findByFirstNameAndLastName(firstName, lastName); } - + @GetMapping("/name/{lastName}") Optional byName(@PathVariable("lastName") String lastName) { return userRepository.findOneByLastName(lastName); } - + @GetMapping("/exists") boolean isEmailTaken(@RequestParam("email") String email) { return userRepository.existsByEmail(email); diff --git a/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/Role.java b/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/Role.java index 2b8950b3..ae7e0ff6 100644 --- a/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/Role.java +++ b/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/Role.java @@ -11,10 +11,11 @@ @NoArgsConstructor @RedisHash public class Role { - @Id + @Id private String id; - - @Indexed @NonNull + + @Indexed + @NonNull private String roleName; } diff --git a/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/User.java b/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/User.java index fdc9834e..baf7009e 100644 --- a/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/User.java +++ b/demos/roms-hashes/src/main/java/com/redis/om/hashes/domain/User.java @@ -17,32 +17,29 @@ @NoArgsConstructor @RedisHash public class User { - @Id + @NonNull + @Indexed + @Bloom(name = "bf_user_email", capacity = 100000, errorRate = 0.001) + String email; + @Id private String id; - - @Indexed @NonNull + @Indexed + @NonNull private String firstName; - - @Indexed + @Indexed private String middleName; - - @Indexed @NonNull - private String lastName; - - @NonNull @Indexed - @Bloom(name = "bf_user_email", capacity = 100000, errorRate = 0.001) - String email; - - @NonNull + @NonNull + private String lastName; + @NonNull @Reference private Role role; - + // audit fields - + @CreatedDate private Date createdDate; - + @LastModifiedDate private Date lastModifiedDate; } diff --git a/demos/roms-hashes/src/main/java/com/redis/om/hashes/repositories/UserRepository.java b/demos/roms-hashes/src/main/java/com/redis/om/hashes/repositories/UserRepository.java index ec5bf1b1..dbe2bd7d 100644 --- a/demos/roms-hashes/src/main/java/com/redis/om/hashes/repositories/UserRepository.java +++ b/demos/roms-hashes/src/main/java/com/redis/om/hashes/repositories/UserRepository.java @@ -9,10 +9,10 @@ @Repository public interface UserRepository extends CrudRepository { - + Optional findOneByLastName(String lastName); List findByFirstNameAndLastName(String firstName, String lastName); - + boolean existsByEmail(String email); } diff --git a/demos/roms-hashes/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java b/demos/roms-hashes/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java index e051b8f3..ac64f6c1 100644 --- a/demos/roms-hashes/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java +++ b/demos/roms-hashes/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java @@ -5,8 +5,8 @@ //@SpringBootTest class RomsHashesApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/demos/roms-permits/README.md b/demos/roms-permits/README.md index 86b78d38..293f14a6 100644 --- a/demos/roms-permits/README.md +++ b/demos/roms-permits/README.md @@ -1,3 +1,5 @@ # Redis OM Spring Demo - Permits -Port of [Elena Kolevska's](https://github.com/elena-kolevska) Quick Start: Using RediSearch with JSON [Demo](https://github.com/redislabs-training/mod-devcap-redisjson-getting-started/blob/master/articles/QuickStart-RediSearchWithJSON.md) to Redis OM Spring +Port of [Elena Kolevska's](https://github.com/elena-kolevska) Quick Start: Using RediSearch with +JSON [Demo](https://github.com/redislabs-training/mod-devcap-redisjson-getting-started/blob/master/articles/QuickStart-RediSearchWithJSON.md) +to Redis OM Spring diff --git a/demos/roms-permits/src/main/java/com/redis/om/permits/PermitsApplication.java b/demos/roms-permits/src/main/java/com/redis/om/permits/PermitsApplication.java index 03c90aad..01075a28 100644 --- a/demos/roms-permits/src/main/java/com/redis/om/permits/PermitsApplication.java +++ b/demos/roms-permits/src/main/java/com/redis/om/permits/PermitsApplication.java @@ -24,6 +24,10 @@ public class PermitsApplication { @Autowired PermitRepository repo; + public static void main(String[] args) { + SpringApplication.run(PermitsApplication.class, args); + } + @Bean CommandLineRunner loadTestData() { return args -> { @@ -33,64 +37,57 @@ CommandLineRunner loadTestData() { Address address1 = Address.of("Lisbon", "25 de Abril"); Order order1 = Order.of("O11", 1.5); Order order2 = Order.of("O12", 5.6); - Attribute attribute11 = Attribute.of("size","S", Lists.newArrayList(order1)); - Attribute attribute12 = Attribute.of("size","M", Lists.newArrayList(order2)); + Attribute attribute11 = Attribute.of("size", "S", Lists.newArrayList(order1)); + Attribute attribute12 = Attribute.of("size", "M", Lists.newArrayList(order2)); List attrList1 = Lists.newArrayList(attribute11, attribute12); Permit permit1 = Permit.of( // - address1, // - "To construct a single detached house with a front covered veranda.", // - "single detached house", // - Set.of("demolition", "reconstruction"), // - 42000L, // - new Point(38.7635877,-9.2018309), // - List.of("started", "in_progress", "approved"), // - attrList1 - ); + address1, // + "To construct a single detached house with a front covered veranda.", // + "single detached house", // + Set.of("demolition", "reconstruction"), // + 42000L, // + new Point(38.7635877, -9.2018309), // + List.of("started", "in_progress", "approved"), // + attrList1); // # Document 2 Address address2 = Address.of("Porto", "Av. da Liberdade"); Order order21 = Order.of("O21", 1.2); Order order22 = Order.of("O22", 5.6); - Attribute attribute21 = Attribute.of("color","red", Lists.newArrayList(order21)); - Attribute attribute22 = Attribute.of("color","blue", Lists.newArrayList(order22)); + Attribute attribute21 = Attribute.of("color", "red", Lists.newArrayList(order21)); + Attribute attribute22 = Attribute.of("color", "blue", Lists.newArrayList(order22)); List attrList2 = Lists.newArrayList(attribute21, attribute22); Permit permit2 = Permit.of( // - address2, // - "To construct a loft", // - "apartment", // - Set.of("construction"), // - 53000L, // - new Point(38.7205373,-9.148091), // - List.of("started", "in_progress", "rejected"), // - attrList2 - ); - + address2, // + "To construct a loft", // + "apartment", // + Set.of("construction"), // + 53000L, // + new Point(38.7205373, -9.148091), // + List.of("started", "in_progress", "rejected"), // + attrList2); + // # Document 3 Address address3 = Address.of("Lagos", "D. João"); Order order31 = Order.of("ABC", 1.6); Order order32 = Order.of("DEF", 1.3); Order order33 = Order.of("GHJ", 1.6); Order order34 = Order.of("VBN", 1.0); - Attribute attribute31 = Attribute.of("brand","A", Lists.newArrayList(order31, order33)); - Attribute attribute32 = Attribute.of("brand","B", Lists.newArrayList(order32, order34)); + Attribute attribute31 = Attribute.of("brand", "A", Lists.newArrayList(order31, order33)); + Attribute attribute32 = Attribute.of("brand", "B", Lists.newArrayList(order32, order34)); List attrList3 = Lists.newArrayList(attribute31, attribute32); Permit permit3 = Permit.of( // - address3, // - "New house build", // - "house", // - Set.of("construction", "design"), // - 260000L, // - new Point(37.0990749,-8.6868258), // - List.of("started", "in_progress", "postponed"), // - attrList3 - ); - + address3, // + "New house build", // + "house", // + Set.of("construction", "design"), // + 260000L, // + new Point(37.0990749, -8.6868258), // + List.of("started", "in_progress", "postponed"), // + attrList3); + repo.saveAll(List.of(permit1, permit2, permit3)); }; } - public static void main(String[] args) { - SpringApplication.run(PermitsApplication.class, args); - } - } diff --git a/demos/roms-permits/src/main/java/com/redis/om/permits/controlllers/PermitController.java b/demos/roms-permits/src/main/java/com/redis/om/permits/controlllers/PermitController.java index 0a380595..4e178434 100644 --- a/demos/roms-permits/src/main/java/com/redis/om/permits/controlllers/PermitController.java +++ b/demos/roms-permits/src/main/java/com/redis/om/permits/controlllers/PermitController.java @@ -12,48 +12,46 @@ public class PermitController { @Autowired PermitRepository repository; - + @GetMapping("value/{value}") Iterable byConstructionValue(@PathVariable("value") long value) { return repository.findByConstructionValue(value); } - + @GetMapping("search/{q}") Iterable fullTextSearch(@PathVariable("q") String q) { return repository.search(q); } - + @GetMapping("building_type/{type}") Iterable byBuildingType(@PathVariable("type") String type) { return repository.findByBuildingType(type); } - + @GetMapping("city/{city}") Iterable byCity(@PathVariable("city") String city) { return repository.findByAddress_City(city); } - + @GetMapping("worktypes") Iterable byTags(@RequestParam("types") Set wts) { return repository.findByWorkType(wts); } - + @GetMapping("worktypes/all") Iterable byAllTags(@RequestParam("types") Set wts) { return repository.findByWorkTypeContainingAll(wts); } - + @GetMapping("building_type_and_description") - Iterable byBuildingTypeAndDescription( - @RequestParam("buildingType") String buildingType, // - @RequestParam("description") String description) { + Iterable byBuildingTypeAndDescription(@RequestParam("buildingType") String buildingType, // + @RequestParam("description") String description) { return repository.findByBuildingTypeAndDescription(buildingType, description); } - + @GetMapping("city_or_description") - Iterable byCityOrDescription( - @RequestParam("city") String city, // - @RequestParam("description") String description) { + Iterable byCityOrDescription(@RequestParam("city") String city, // + @RequestParam("description") String description) { return repository.findByAddress_CityOrDescription(city, description); } } diff --git a/demos/roms-permits/src/main/java/com/redis/om/permits/repositories/PermitRepository.java b/demos/roms-permits/src/main/java/com/redis/om/permits/repositories/PermitRepository.java index f04892e9..9f1a07f2 100644 --- a/demos/roms-permits/src/main/java/com/redis/om/permits/repositories/PermitRepository.java +++ b/demos/roms-permits/src/main/java/com/redis/om/permits/repositories/PermitRepository.java @@ -12,36 +12,36 @@ public interface PermitRepository extends RedisDocumentRepository findByConstructionValue(long value); - + // Performing a text search on all text fields: // FT.SEARCH permits "veranda" // Result: Documents inside which the word 'veranda' occurs, so tst:permit:1. Iterable search(String text); - + // A fuzzy text search on all text fields: // FT.SEARCH permits "%%haus%%" // Result: Documents with words similar to 'haus' (tst:permit:1 and tst:permit:3). The number of % indicates the allowed Levenshtein distance (later more about it). So the query would also match on 'house' because 'haus' and 'house' have a distance of two. - + // Performing a text search on a specific field: // FT.SEARCH permits "@building_type:detached" Iterable findByBuildingType(String buildingType); - + // Performing a tag search // FT.SEARCH permits "@city:{Lisbon}" Iterable findByAddress_City(String city); - + // search documents that have one of multiple tags (OR condition) // FT.SEARCH permits "@work_type:{construction|design}" Iterable findByWorkType(Set workTypes); - + // Search documents that have all of the tags (AND condition): // FT.SEARCH permits "@work_type:{construction} @work_type:{design}" Iterable findByWorkTypeContainingAll(Set workTypes); - + // Performing a combined search on two fields (AND): // FT.SEARCH permits "@building_type:house @description:new" Iterable findByBuildingTypeAndDescription(String buildingType, String description); - + // Performing a combined search on two fields (OR): // FT.SEARCH permits "(@city:{Lagos})|(@description:detached)" Iterable findByAddress_CityOrDescription(String buildingType, String description); diff --git a/demos/roms-permits/src/test/java/com/redis/om/permits/PermitsApplicationTests.java b/demos/roms-permits/src/test/java/com/redis/om/permits/PermitsApplicationTests.java index 775a1085..06bf8b37 100644 --- a/demos/roms-permits/src/test/java/com/redis/om/permits/PermitsApplicationTests.java +++ b/demos/roms-permits/src/test/java/com/redis/om/permits/PermitsApplicationTests.java @@ -5,8 +5,8 @@ //@SpringBootTest class PermitsApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/demos/roms-vss/README.md b/demos/roms-vss/README.md index 45bbf82c..c55388a3 100644 --- a/demos/roms-vss/README.md +++ b/demos/roms-vss/README.md @@ -5,6 +5,7 @@ Through the RediSearch module, vector types and indexes can be added to Redis. T a highly performant vector database which can be used for all types of applications. The following Redis Stack capabilities are available in this demo: + - **Vector Similarity Search** - by image - by text @@ -19,7 +20,7 @@ This app was built as a Single Page Application (SPA) with the following compone - **[Redis OM Spring](https://redis.io/docs/stack/get-started/tutorials/stack-spring/)** for ORM - **[Docker Compose](https://docs.docker.com/compose/)** for development - **[Bootstrap](https://getbootstrap.com/)** Frontend toolkit -- **[HTMX](https://htmx.org)** markup-driven server-side SPAs +- **[HTMX](https://htmx.org)** markup-driven server-side SPAs ### Datasets @@ -28,14 +29,14 @@ The dataset was taken from the following Kaggle links. - [Large Dataset](https://www.kaggle.com/datasets/paramaggarwal/fashion-product-images-dataset) - [Smaller Dataset](https://www.kaggle.com/datasets/paramaggarwal/fashion-product-images-small) - ## Running the App + Before running the app, install [Docker Desktop](https://www.docker.com/products/docker-desktop/). The app can run with images from a CDN (slower to vectorize) or with local images that can be obtained from https://www.dropbox.com/s/9o59z8zbhknnmvx/product-images.zip?dl=0 -Unzip the file `product-images.zip` under `src/main/resources/static/` which will +Unzip the file `product-images.zip` under `src/main/resources/static/` which will result in the folder `src/main/resources/static/product-images` being created. #### Redis Cloud (recommended) @@ -49,7 +50,7 @@ result in the folder `src/main/resources/static/product-images` being created. spring.data.redis.password=xxxxxx spring.data.redis.username=default ``` -3. Configure whether to use local images or CDN images and how many images to +3. Configure whether to use local images or CDN images and how many images to load, the maximum being `3000` (in `applications.properties`): ``` com.redis.om.vss.useLocalImages=false diff --git a/demos/roms-vss/src/main/java/com/redis/om/vss/RomsVectorSimilaritySearchApplication.java b/demos/roms-vss/src/main/java/com/redis/om/vss/RomsVectorSimilaritySearchApplication.java index ffba99da..e6ac7f71 100644 --- a/demos/roms-vss/src/main/java/com/redis/om/vss/RomsVectorSimilaritySearchApplication.java +++ b/demos/roms-vss/src/main/java/com/redis/om/vss/RomsVectorSimilaritySearchApplication.java @@ -17,29 +17,34 @@ import java.util.List; import java.util.Objects; -@SpringBootApplication @EnableRedisEnhancedRepositories(basePackages = "com.redis.om.vss.*") public class RomsVectorSimilaritySearchApplication { +@SpringBootApplication +@EnableRedisEnhancedRepositories(basePackages = "com.redis.om.vss.*") +public class RomsVectorSimilaritySearchApplication { final Logger logger = LoggerFactory.getLogger(RomsVectorSimilaritySearchApplication.class); - @Value("${com.redis.om.vss.useLocalImages}") private boolean useLocalImages; + @Value("${com.redis.om.vss.useLocalImages}") + private boolean useLocalImages; - @Value("${com.redis.om.vss.maxLines}") private long maxLines; + @Value("${com.redis.om.vss.maxLines}") + private long maxLines; public static void main(String[] args) { SpringApplication.run(RomsVectorSimilaritySearchApplication.class, args); } - @Bean CommandLineRunner loadAndVectorizeProductData(ProductRepository repository, - @Value("classpath:/data/styles.csv") File dataFile) { + @Bean + CommandLineRunner loadAndVectorizeProductData(ProductRepository repository, + @Value("classpath:/data/styles.csv") File dataFile) { return args -> { if (repository.count() == 0) { logger.info("⚙️ Loading products..."); List data = Files // - .readLines(dataFile, StandardCharsets.UTF_8) // - .stream() // - .limit(maxLines) // - .map(line -> Product.fromCSV(line, useLocalImages)) // - .filter(Objects::nonNull) // - .toList(); + .readLines(dataFile, StandardCharsets.UTF_8) // + .stream() // + .limit(maxLines) // + .map(line -> Product.fromCSV(line, useLocalImages)) // + .filter(Objects::nonNull) // + .toList(); repository.saveAll(data); } logger.info("🏁 {} Products Available...", repository.count()); diff --git a/demos/roms-vss/src/main/java/com/redis/om/vss/controllers/ProductController.java b/demos/roms-vss/src/main/java/com/redis/om/vss/controllers/ProductController.java index e6d79ecc..ca52d4b6 100644 --- a/demos/roms-vss/src/main/java/com/redis/om/vss/controllers/ProductController.java +++ b/demos/roms-vss/src/main/java/com/redis/om/vss/controllers/ProductController.java @@ -25,10 +25,8 @@ @Controller @RequestMapping("/") public class ProductController { - final Logger logger = LoggerFactory.getLogger(ProductController.class); - private static final int K = 15; - + final Logger logger = LoggerFactory.getLogger(ProductController.class); @Autowired private ProductRepository repository; @@ -39,12 +37,10 @@ public class ProductController { public String index(Model model) { logger.info("🔎 index :: Showing first {} products...", K); - List products = entityStream.of(Product.class) - .limit(K) // - .collect(Collectors.toList()); + List products = entityStream.of(Product.class).limit(K) // + .collect(Collectors.toList()); - ProductsPageModel.of() - .model(model) // + ProductsPageModel.of().model(model) // .products(products) // .build().apply(); @@ -52,20 +48,17 @@ public String index(Model model) { } @GetMapping("/load") - public String load( - Model model, // - @RequestParam Optional gender, // - @RequestParam Optional category, // - @RequestParam(name = "skip") Optional skipParam // + public String load(Model model, // + @RequestParam Optional gender, // + @RequestParam Optional category, // + @RequestParam(name = "skip") Optional skipParam // ) { long count = repository.count(); long skip = skipParam.isPresent() && skipParam.get() < count - K ? skipParam.get() + K : 0; logger.info("🔎 load :: Showing {} products, starting at {}...", K, skip); - SearchStream stream = entityStream.of(Product.class) - .skip(skip) - .limit(K); + SearchStream stream = entityStream.of(Product.class).skip(skip).limit(K); applyFilters(stream, gender, category); @@ -75,8 +68,7 @@ public String load( skip = 0; } - ProductsPageModel.of() - .model(model) // + ProductsPageModel.of().model(model) // .products(products) // .category(category.orElse(null)) // .skip(skip) // @@ -86,34 +78,33 @@ public String load( } @GetMapping("/vss/text/{id}") - public String findSimilarByText( - Model model, // - @PathVariable("id") String id, // - @RequestParam Optional gender, // - @RequestParam Optional category, // - @RequestParam Optional skip // + public String findSimilarByText(Model model, // + @PathVariable("id") String id, // + @RequestParam Optional gender, // + @RequestParam Optional category, // + @RequestParam Optional skip // ) { Optional maybeProduct = repository.findById(id); if (maybeProduct.isPresent()) { Product product = maybeProduct.get(); - logger.info("🔎 vss :: Finding products with text similar to product {} ({})...", id, product.getProductDisplayName()); + logger.info("🔎 vss :: Finding products with text similar to product {} ({})...", id, + product.getProductDisplayName()); SearchStream stream = entityStream.of(Product.class); applyFilters(stream, gender, category); - List> productsAndScores = stream - .filter(Product$.SENTENCE_EMBEDDING.knn(K, product.getSentenceEmbedding())) // - .sorted(Product$._SENTENCE_EMBEDDING_SCORE) // - .limit(K) // - .map(Fields.of(Product$._THIS, Product$._SENTENCE_EMBEDDING_SCORE)) // - .collect(Collectors.toList()); + List> productsAndScores = stream.filter( + Product$.SENTENCE_EMBEDDING.knn(K, product.getSentenceEmbedding())) // + .sorted(Product$._SENTENCE_EMBEDDING_SCORE) // + .limit(K) // + .map(Fields.of(Product$._THIS, Product$._SENTENCE_EMBEDDING_SCORE)) // + .collect(Collectors.toList()); List products = productsAndScores.stream().map(Pair::getFirst).toList(); - List scores = productsAndScores.stream().map(Pair::getSecond).map(d -> 100.0 * (1 - d/2)).toList(); + List scores = productsAndScores.stream().map(Pair::getSecond).map(d -> 100.0 * (1 - d / 2)).toList(); - ProductsPageModel.of() - .model(model) // + ProductsPageModel.of().model(model) // .products(products) // .scores(scores) // .category(category.orElse(null)) // @@ -128,34 +119,33 @@ public String findSimilarByText( } @GetMapping("/vss/image/{id}") - public String findSimilarByImage( - Model model, // - @PathVariable("id") String id, // - @RequestParam Optional gender, // - @RequestParam Optional category, // - @RequestParam Optional skip // + public String findSimilarByImage(Model model, // + @PathVariable("id") String id, // + @RequestParam Optional gender, // + @RequestParam Optional category, // + @RequestParam Optional skip // ) { Optional maybeProduct = repository.findById(id); if (maybeProduct.isPresent()) { Product product = maybeProduct.get(); - logger.info("🔎 vss :: Finding products with images similar to product {} ({})...", id, product.getProductDisplayName()); + logger.info("🔎 vss :: Finding products with images similar to product {} ({})...", id, + product.getProductDisplayName()); SearchStream stream = entityStream.of(Product.class); applyFilters(stream, gender, category); - List> productsAndScores = stream - .filter(Product$.IMAGE_EMBEDDING.knn(K, product.getImageEmbedding())) // + List> productsAndScores = stream.filter( + Product$.IMAGE_EMBEDDING.knn(K, product.getImageEmbedding())) // .sorted(Product$._IMAGE_EMBEDDING_SCORE) // .limit(K) // .map(Fields.of(Product$._THIS, Product$._IMAGE_EMBEDDING_SCORE)) // .collect(Collectors.toList()); List products = productsAndScores.stream().map(Pair::getFirst).toList(); - List scores = productsAndScores.stream().map(Pair::getSecond).map(d -> 100.0 * (1 - d/2)).toList(); + List scores = productsAndScores.stream().map(Pair::getSecond).map(d -> 100.0 * (1 - d / 2)).toList(); - ProductsPageModel.of() - .model(model) // + ProductsPageModel.of().model(model) // .products(products) // .scores(scores) // .category(category.orElse(null)) // @@ -170,16 +160,14 @@ public String findSimilarByImage( } @GetMapping("/filters") - public String filters( - Model model, // - @RequestParam Optional gender, // - @RequestParam Optional category, // - @RequestParam Optional skip // + public String filters(Model model, // + @RequestParam Optional gender, // + @RequestParam Optional category, // + @RequestParam Optional skip // ) { logger.info("🔎️ :: Setting Filters. Gender → {}, Category → {}", gender, category); - ProductsPageModel.of() - .model(model) // + ProductsPageModel.of().model(model) // .category(category.orElse(null)) // .gender(gender.orElse(null)) // .skip(skip.orElse(null)) // diff --git a/demos/roms-vss/src/main/java/com/redis/om/vss/domain/Product.java b/demos/roms-vss/src/main/java/com/redis/om/vss/domain/Product.java index 8c383ce5..ea3856fa 100644 --- a/demos/roms-vss/src/main/java/com/redis/om/vss/domain/Product.java +++ b/demos/roms-vss/src/main/java/com/redis/om/vss/domain/Product.java @@ -61,7 +61,6 @@ public class Product { @NonNull private String productDisplayName; - @Indexed(// schemaFieldType = SchemaFieldType.VECTOR, // algorithm = VectorAlgorithm.HNSW, // @@ -98,18 +97,20 @@ public static Product fromCSV(String line, boolean useLocalImages) { String gender = values[1]; String masterCategory = values[2]; String subCategory = values[3]; - if (subCategory.equalsIgnoreCase("Innerwear")) return null; + if (subCategory.equalsIgnoreCase("Innerwear")) + return null; String articleType = values[4]; String baseColour = values[5]; String season = values[6]; String year = values[7]; - String usage = values[8]; + String usage = values[8]; String productDisplayName = values[9]; String imagePath = useLocalImages ? "classpath:/static/product-images/" + id + ".jpg" : values[10]; - String productText = Stream.of(productDisplayName, "category", masterCategory, "subcategory", subCategory, "color", baseColour, "gender", gender).map(String::toLowerCase).collect( - Collectors.joining(" ")); + String productText = Stream.of(productDisplayName, "category", masterCategory, "subcategory", subCategory, "color", + baseColour, "gender", gender).map(String::toLowerCase).collect(Collectors.joining(" ")); - Product p = Product.of(gender, masterCategory, subCategory, articleType, baseColour, season, year, usage, productDisplayName, imagePath, productText); + Product p = Product.of(gender, masterCategory, subCategory, articleType, baseColour, season, year, usage, + productDisplayName, imagePath, productText); p.setId(id); return p; } diff --git a/demos/roms-vss/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java b/demos/roms-vss/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java index e051b8f3..ac64f6c1 100644 --- a/demos/roms-vss/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java +++ b/demos/roms-vss/src/test/java/com/redis/om/hashes/RomsHashesApplicationTests.java @@ -5,8 +5,8 @@ //@SpringBootTest class RomsHashesApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/CustomRedisKeyValueTemplate.java b/redis-om-spring/src/main/java/com/redis/om/spring/CustomRedisKeyValueTemplate.java index 4ff90200..a92d724d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/CustomRedisKeyValueTemplate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/CustomRedisKeyValueTemplate.java @@ -25,15 +25,17 @@ public CustomRedisKeyValueTemplate(RedisKeyValueAdapter adapter, RedisMappingCon /** * Obtain the underlying redis specific * {@link org.springframework.data.convert.EntityConverter}. + * * @return the EntityConverter */ public RedisConverter getConverter() { return adapter.getConverter(); } - + /** * Obtain the underlying redis specific * {@link org.springframework.data.redis.core.RedisKeyValueAdapter}. + * * @return the KeyValueAdapter */ public RedisKeyValueAdapter getAdapter() { @@ -41,12 +43,12 @@ public RedisKeyValueAdapter getAdapter() { } /* (non-Javadoc) - * + * * @see * org.springframework.data.keyvalue.core.KeyValueTemplate#getMappingContext( * ) */ @Override - public RedisMappingContext getMappingContext() { + public RedisMappingContext getMappingContext() { return (RedisMappingContext) super.getMappingContext(); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/DistanceMetric.java b/redis-om-spring/src/main/java/com/redis/om/spring/DistanceMetric.java index b507de61..1c427213 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/DistanceMetric.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/DistanceMetric.java @@ -1,5 +1,7 @@ package com.redis.om.spring; public enum DistanceMetric { - L2, IP, COSINE + L2, + IP, + COSINE } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RediSearchIndexer.java b/redis-om-spring/src/main/java/com/redis/om/spring/RediSearchIndexer.java index 257de4c9..0601822e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RediSearchIndexer.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RediSearchIndexer.java @@ -219,26 +219,27 @@ private List findIndexFields(java.lang.reflect.Field field, String // of the value) // if (CharSequence.class.isAssignableFrom(fieldType) || // - (fieldType == Boolean.class) || (fieldType == UUID.class) || (fieldType == Ulid.class)) { - fields.add(indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), - indexed.arrayIndex(), indexed.alias())); + (fieldType == Boolean.class) || (fieldType == UUID.class) || (fieldType == Ulid.class)) { + fields.add( + indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), indexed.arrayIndex(), + indexed.alias())); } else if (fieldType.isEnum()) { if (Objects.requireNonNull(indexed.serializationHint()) == SerializationHint.ORDINAL) { fields.add(indexAsNumericFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.noindex(), - indexed.alias())); + indexed.alias())); gsonBuilder.registerTypeAdapter(fieldType, EnumTypeAdapter.of(fieldType)); } else { fields.add(indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), - indexed.arrayIndex(), indexed.alias())); + indexed.arrayIndex(), indexed.alias())); } } // // Any Numeric class -> Numeric Search Field // else if (Number.class.isAssignableFrom( - fieldType) || (fieldType == LocalDateTime.class) || (field.getType() == LocalDate.class) || (field.getType() == Date.class) || (field.getType() == Instant.class) || (field.getType() == OffsetDateTime.class)) { - fields.add(indexAsNumericFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.noindex(), - indexed.alias())); + fieldType) || (fieldType == LocalDateTime.class) || (field.getType() == LocalDate.class) || (field.getType() == Date.class) || (field.getType() == Instant.class) || (field.getType() == OffsetDateTime.class)) { + fields.add( + indexAsNumericFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.noindex(), indexed.alias())); } // // Set / List @@ -257,16 +258,16 @@ else if (Set.class.isAssignableFrom(fieldType) || List.class.isAssignableFrom(fi if (CharSequence.class.isAssignableFrom(collectionType) || (collectionType == Boolean.class)) { fields.add(indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), - indexed.arrayIndex(), indexed.alias())); + indexed.arrayIndex(), indexed.alias())); } else if (isDocument) { if (Number.class.isAssignableFrom(collectionType)) { - fields.add(indexAsNumericFieldFor(field, true, prefix, indexed.sortable(), indexed.noindex(), - indexed.alias())); + fields.add( + indexAsNumericFieldFor(field, true, prefix, indexed.sortable(), indexed.noindex(), indexed.alias())); } else if (collectionType == Point.class) { fields.add(indexAsGeoFieldFor(field, true, prefix, indexed.alias())); } else if (collectionType == UUID.class || collectionType == Ulid.class) { - fields.add(indexAsTagFieldFor(field, true, prefix, indexed.sortable(), indexed.separator(), 0, - indexed.alias())); + fields.add( + indexAsTagFieldFor(field, true, prefix, indexed.sortable(), indexed.separator(), 0, indexed.alias())); } else { // Index nested JSON fields logger.debug(String.format("Found nested field on field of type: %s", field.getType())); @@ -275,7 +276,7 @@ else if (Set.class.isAssignableFrom(fieldType) || List.class.isAssignableFrom(fi } } else { logger.debug(String.format("Could not determine the type of elements in the collection %s in entity %s", - field.getName(), field.getDeclaringClass().getSimpleName())); + field.getName(), field.getDeclaringClass().getSimpleName())); } } // @@ -290,29 +291,31 @@ else if (fieldType == Point.class) { else { for (java.lang.reflect.Field subfield : getDeclaredFieldsTransitively(field.getType())) { String subfieldPrefix = (prefix == null || prefix.isBlank()) ? - field.getName() : - String.join(".", prefix, field.getName()); + field.getName() : + String.join(".", prefix, field.getName()); fields.addAll(findIndexFields(subfield, subfieldPrefix, isDocument)); } } } else { // Schema field type hardcoded/set in @Indexed switch (indexed.schemaFieldType()) { - case TAG -> fields.add(indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), - indexed.arrayIndex(), indexed.alias())); + case TAG -> fields.add( + indexAsTagFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.separator(), indexed.arrayIndex(), + indexed.alias())); case NUMERIC -> fields.add( - indexAsNumericFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.noindex(), - indexed.alias())); + indexAsNumericFieldFor(field, isDocument, prefix, indexed.sortable(), indexed.noindex(), indexed.alias())); case GEO -> fields.add(indexAsGeoFieldFor(field, true, prefix, indexed.alias())); case VECTOR -> fields.add(indexAsVectorFieldFor(field, isDocument, prefix, indexed)); case NESTED -> { for (java.lang.reflect.Field subfield : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively( - field.getType())) { + field.getType())) { String subfieldPrefix = (prefix == null || prefix.isBlank()) ? - field.getName() : - String.join(".", prefix, field.getName()); + field.getName() : + String.join(".", prefix, field.getName()); fields.addAll(findIndexFields(subfield, subfieldPrefix, isDocument)); } } + default -> { + } // NOOP } } } @@ -357,8 +360,8 @@ private TagField indexAsTagFieldFor(java.lang.reflect.Field field, boolean isDoc String fieldPrefix = getFieldPrefix(prefix, isDocument); String fieldPostfix = (isDocument && typeInfo.isCollectionLike() && !field.isAnnotationPresent(JsonAdapter.class)) ? - "[*]" : - ""; + "[*]" : + ""; String name = fieldPrefix + field.getName() + fieldPostfix; String alias = ObjectUtils.isEmpty(ti.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ti.alias(); @@ -369,7 +372,7 @@ private TagField indexAsTagFieldFor(java.lang.reflect.Field field, boolean isDoc } private VectorField indexAsVectorFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - Indexed indexed) { + Indexed indexed) { String fieldPrefix = getFieldPrefix(prefix, isDocument); String fieldName = fieldPrefix + field.getName(); @@ -400,8 +403,8 @@ private VectorField indexAsVectorFieldFor(java.lang.reflect.Field field, boolean } String alias = ObjectUtils.isEmpty(indexed.alias()) ? - QueryUtils.searchIndexFieldAliasFor(field, prefix) : - indexed.alias(); + QueryUtils.searchIndexFieldAliasFor(field, prefix) : + indexed.alias(); VectorField vectorField = new VectorField(fieldName, indexed.algorithm(), attributes); vectorField.as(alias); @@ -410,13 +413,13 @@ private VectorField indexAsVectorFieldFor(java.lang.reflect.Field field, boolean } private VectorField indexAsVectorFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - VectorIndexed vi) { + VectorIndexed vi) { TypeInformation typeInfo = TypeInformation.of(field.getType()); String fieldPrefix = getFieldPrefix(prefix, isDocument); String fieldPostfix = (isDocument && typeInfo.isCollectionLike() && !field.isAnnotationPresent(JsonAdapter.class)) ? - "[*]" : - ""; + "[*]" : + ""; String fieldName = fieldPrefix + field.getName() + fieldPostfix; Map attributes = new HashMap<>(); @@ -454,19 +457,19 @@ private VectorField indexAsVectorFieldFor(java.lang.reflect.Field field, boolean } private SchemaField indexAsTagFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - boolean sortable, String separator, int arrayIndex, String annotationAlias) { + boolean sortable, String separator, int arrayIndex, String annotationAlias) { SerializedName serializedName = field.getAnnotation(SerializedName.class); String fname = (serializedName != null) ? serializedName.value() : field.getName(); TypeInformation typeInfo = TypeInformation.of(field.getType()); String fieldPrefix = getFieldPrefix(prefix, isDocument); String index = (arrayIndex != Integer.MIN_VALUE) ? ".[" + arrayIndex + "]" : "[*]"; String fieldPostfix = (isDocument && typeInfo.isCollectionLike() && !field.isAnnotationPresent(JsonAdapter.class)) ? - index : - ""; + index : + ""; String name = fieldPrefix + fname + fieldPostfix; String alias = (annotationAlias == null || annotationAlias.isBlank()) ? - QueryUtils.searchIndexFieldAliasFor(field, prefix) : - annotationAlias; + QueryUtils.searchIndexFieldAliasFor(field, prefix) : + annotationAlias; FieldName fieldName = FieldName.of(name); fieldName = fieldName.as(alias); @@ -474,9 +477,9 @@ private SchemaField indexAsTagFieldFor(java.lang.reflect.Field field, boolean is } private TextField indexAsTextFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - TextIndexed ti) { + TextIndexed ti) { var fieldName = getFieldName(field, isDocument, prefix, - ObjectUtils.isEmpty(ti.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ti.alias()); + ObjectUtils.isEmpty(ti.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ti.alias()); String phonetic = ObjectUtils.isEmpty(ti.phonetic()) ? null : ti.phonetic(); @@ -484,9 +487,9 @@ private TextField indexAsTextFieldFor(java.lang.reflect.Field field, boolean isD } private TextField indexAsTextFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - Searchable ti) { + Searchable ti) { var fieldName = getFieldName(field, isDocument, prefix, - ObjectUtils.isEmpty(ti.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ti.alias()); + ObjectUtils.isEmpty(ti.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ti.alias()); String phonetic = ObjectUtils.isEmpty(ti.phonetic()) ? null : ti.phonetic(); @@ -495,24 +498,24 @@ private TextField indexAsTextFieldFor(java.lang.reflect.Field field, boolean isD private GeoField indexAsGeoFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, GeoIndexed gi) { var fieldName = getFieldName(field, isDocument, prefix, - ObjectUtils.isEmpty(gi.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : gi.alias()); + ObjectUtils.isEmpty(gi.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : gi.alias()); return GeoField.of(fieldName); } private NumericField indexAsNumericFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - NumericIndexed ni) { + NumericIndexed ni) { var fieldName = getFieldName(field, isDocument, prefix, - ObjectUtils.isEmpty(ni.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ni.alias()); + ObjectUtils.isEmpty(ni.alias()) ? QueryUtils.searchIndexFieldAliasFor(field, prefix) : ni.alias()); return NumericField.of(fieldName); } private NumericField indexAsNumericFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - boolean sortable, boolean noIndex, String annotationAlias) { + boolean sortable, boolean noIndex, String annotationAlias) { String alias = (annotationAlias == null || annotationAlias.isBlank()) ? - QueryUtils.searchIndexFieldAliasFor(field, prefix) : - annotationAlias; + QueryUtils.searchIndexFieldAliasFor(field, prefix) : + annotationAlias; var fieldName = getFieldName(field, isDocument, prefix, alias); NumericField num = NumericField.of(fieldName); @@ -524,10 +527,10 @@ private NumericField indexAsNumericFieldFor(java.lang.reflect.Field field, boole } private GeoField indexAsGeoFieldFor(java.lang.reflect.Field field, boolean isDocument, String prefix, - String annotationAlias) { + String annotationAlias) { String alias = (annotationAlias == null || annotationAlias.isBlank()) ? - QueryUtils.searchIndexFieldAliasFor(field, prefix) : - annotationAlias; + QueryUtils.searchIndexFieldAliasFor(field, prefix) : + annotationAlias; var fieldName = getFieldName(field, isDocument, prefix, alias); return GeoField.of(fieldName); @@ -549,7 +552,7 @@ private FieldName getFieldName(java.lang.reflect.Field field, boolean isDocument } private List getNestedField(String fieldPrefix, java.lang.reflect.Field field, String prefix, - List fieldList) { + List fieldList) { if (fieldList == null) { fieldList = new ArrayList<>(); } @@ -557,7 +560,7 @@ private List getNestedField(String fieldPrefix, java.lang.reflect.F if (genericType instanceof ParameterizedType pt) { Class actualTypeArgument = (Class) pt.getActualTypeArguments()[0]; List subDeclaredFields = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively( - actualTypeArgument); + actualTypeArgument); String tempPrefix = ""; if (prefix == null) { prefix = field.getName(); @@ -569,7 +572,7 @@ private List getNestedField(String fieldPrefix, java.lang.reflect.F Optional> maybeCollectionType = getCollectionElementClass(subField); String suffix = (maybeCollectionType.isPresent() && (CharSequence.class.isAssignableFrom( - maybeCollectionType.get()) || (maybeCollectionType.get() == Boolean.class))) ? "[*]" : ""; + maybeCollectionType.get()) || (maybeCollectionType.get() == Boolean.class))) ? "[*]" : ""; if (subField.isAnnotationPresent(TagIndexed.class)) { TagIndexed ti = subField.getAnnotation(TagIndexed.class); @@ -583,9 +586,9 @@ private List getNestedField(String fieldPrefix, java.lang.reflect.F continue; } else if (subField.isAnnotationPresent(Indexed.class)) { boolean subFieldIsTagField = (subField.isAnnotationPresent( - Indexed.class) && (CharSequence.class.isAssignableFrom( - subField.getType()) || (subField.getType() == Boolean.class) || (subField.getType() == UUID.class) || (maybeCollectionType.isPresent() && (CharSequence.class.isAssignableFrom( - maybeCollectionType.get()) || (maybeCollectionType.get() == Boolean.class))))); + Indexed.class) && (CharSequence.class.isAssignableFrom( + subField.getType()) || (subField.getType() == Boolean.class) || (subField.getType() == UUID.class) || (maybeCollectionType.isPresent() && (CharSequence.class.isAssignableFrom( + maybeCollectionType.get()) || (maybeCollectionType.get() == Boolean.class))))); if (subFieldIsTagField) { Indexed indexed = subField.getAnnotation(Indexed.class); tempPrefix = field.getName() + "[0:]."; @@ -597,7 +600,7 @@ private List getNestedField(String fieldPrefix, java.lang.reflect.F fieldList.add(getTagField(fieldName, indexed.separator(), false)); continue; } else if (Number.class.isAssignableFrom( - subField.getType()) || (subField.getType() == LocalDateTime.class) || (subField.getType() == LocalDate.class) || (subField.getType() == Date.class)) { + subField.getType()) || (subField.getType() == LocalDateTime.class) || (subField.getType() == LocalDate.class) || (subField.getType() == Date.class)) { FieldName fieldName = FieldName.of(fieldPrefix + tempPrefix + subField.getName() + suffix); fieldName = fieldName.as(QueryUtils.searchIndexFieldAliasFor(subField, prefix)); @@ -612,12 +615,12 @@ private List getNestedField(String fieldPrefix, java.lang.reflect.F fieldName = fieldName.as(QueryUtils.searchIndexFieldAliasFor(subField, prefix)); logger.info( - String.format("Creating TEXT nested relationships: %s -> %s", field.getName(), subField.getName())); + String.format("Creating TEXT nested relationships: %s -> %s", field.getName(), subField.getName())); String phonetic = ObjectUtils.isEmpty(searchable.phonetic()) ? null : searchable.phonetic(); fieldList.add(getTextField(fieldName, searchable.weight(), searchable.sortable(), searchable.nostem(), - searchable.noindex(), phonetic)); + searchable.noindex(), phonetic)); continue; } @@ -643,7 +646,7 @@ private TagField getTagField(FieldName fieldName, String separator, boolean sort } private TextField getTextField(FieldName fieldName, double weight, boolean sortable, boolean noStem, boolean noIndex, - String phonetic) { + String phonetic) { TextField text = TextField.of(fieldName); text.weight(weight); if (sortable) @@ -722,17 +725,17 @@ private List processIndexedFields(List all private Optional getDocumentScoreField(List allClassFields, boolean isDocument) { return allClassFields.stream().filter(field -> field.isAnnotationPresent(DocumentScore.class)).findFirst() - .map(field -> (isDocument ? "$." : "") + field.getName()); + .map(field -> (isDocument ? "$." : "") + field.getName()); } private boolean isAnnotationPreset(java.lang.reflect.Field idField, List fields) { return (!idField.isAnnotationPresent(Indexed.class) && !idField.isAnnotationPresent( - Searchable.class) && !idField.isAnnotationPresent(TagIndexed.class) && !idField.isAnnotationPresent( - TextIndexed.class) && (fields.stream().noneMatch(f -> f.getName().equals(idField.getName())))); + Searchable.class) && !idField.isAnnotationPresent(TagIndexed.class) && !idField.isAnnotationPresent( + TextIndexed.class) && (fields.stream().noneMatch(f -> f.getName().equals(idField.getName())))); } private Optional createIndexedFieldForIdField(Class cl, List fields, - boolean isDocument) { + boolean isDocument) { Optional result = Optional.empty(); Optional maybeIdField = getIdFieldForEntityClass(cl); if (maybeIdField.isPresent()) { @@ -753,7 +756,7 @@ private Optional createIndexedFieldForIdField(Class cl, List createIndexedFieldForIdField(Class cl, List createIndexedFieldForReferenceIdField( // - java.lang.reflect.Field referenceIdField, // - boolean isDocument) { + java.lang.reflect.Field referenceIdField, // + boolean isDocument) { SerializedName serializedName = referenceIdField.getAnnotation(SerializedName.class); String fname = (serializedName != null) ? serializedName.value() : referenceIdField.getName(); @@ -770,7 +773,7 @@ private Optional createIndexedFieldForReferenceIdField( // FieldName fieldName = FieldName.of(fieldPrefix + fname); fieldName = fieldName.as(QueryUtils.searchIndexFieldAliasFor(referenceIdField, "")); return Optional.of( - isDocument ? TagField.of(fieldName).separator('|') : TagField.of(fieldName).separator('|').sortable()); + isDocument ? TagField.of(fieldName).separator('|') : TagField.of(fieldName).separator('|').sortable()); } private FTCreateParams createIndexDefinition(Class cl, IndexDataType idxType) { @@ -781,7 +784,7 @@ private FTCreateParams createIndexDefinition(Class cl, IndexDataType idxType) Document document = cl.getAnnotation(Document.class); Optional.ofNullable(document.filter()).filter(ObjectUtils::isNotEmpty).ifPresent(params::filter); Optional.ofNullable(document.language()).filter(ObjectUtils::isNotEmpty) - .ifPresent(lang -> params.language(lang.getValue())); + .ifPresent(lang -> params.language(lang.getValue())); Optional.ofNullable(document.languageField()).filter(ObjectUtils::isNotEmpty).ifPresent(params::languageField); params.score(document.score()); } @@ -790,7 +793,7 @@ private FTCreateParams createIndexDefinition(Class cl, IndexDataType idxType) } private void updateTTLSettings(Class cl, String entityPrefix, boolean isDocument, Optional document, - List allClassFields) { + List allClassFields) { if (isDocument) { KeyspaceSettings setting = new KeyspaceSettings(cl, entityPrefix); @@ -798,7 +801,7 @@ private void updateTTLSettings(Class cl, String entityPrefix, boolean isDocum document.filter(doc -> doc.timeToLive() > 0).ifPresent(doc -> setting.setTimeToLive(doc.timeToLive())); allClassFields.stream().filter(field -> field.isAnnotationPresent(TimeToLive.class)).findFirst() - .ifPresent(field -> setting.setTimeToLivePropertyName(field.getName())); + .ifPresent(field -> setting.setTimeToLivePropertyName(field.getName())); mappingContext.getMappingConfiguration().getKeyspaceConfiguration().addKeyspaceSettings(setting); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RedisEnhancedKeyValueAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/RedisEnhancedKeyValueAdapter.java index 64a8ea2b..09050759 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RedisEnhancedKeyValueAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RedisEnhancedKeyValueAdapter.java @@ -46,17 +46,16 @@ public class RedisEnhancedKeyValueAdapter extends RedisKeyValueAdapter { * Creates new {@link RedisKeyValueAdapter} with default * {@link RedisMappingContext} and default {@link RedisCustomConversions}. * - * @param redisOps must not be {@literal null}. - * @param rmo must not be {@literal null}. - * @param indexer must not be {@literal null}. + * @param redisOps must not be {@literal null}. + * @param rmo must not be {@literal null}. + * @param indexer must not be {@literal null}. */ public RedisEnhancedKeyValueAdapter( // - RedisOperations redisOps, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - RedisOMProperties redisOMProperties - ) { + RedisOperations redisOps, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + RedisOMProperties redisOMProperties) { this(redisOps, rmo, new RedisMappingContext(), indexer, featureExtractor, redisOMProperties); } @@ -64,50 +63,48 @@ public RedisEnhancedKeyValueAdapter( // * Creates new {@link RedisKeyValueAdapter} with default * {@link RedisCustomConversions}. * - * @param redisOps must not be {@literal null}. - * @param rmo must not be {@literal null}. - * @param mappingContext must not be {@literal null}. - * @param indexer must not be {@literal null}. + * @param redisOps must not be {@literal null}. + * @param rmo must not be {@literal null}. + * @param mappingContext must not be {@literal null}. + * @param indexer must not be {@literal null}. */ public RedisEnhancedKeyValueAdapter( // - RedisOperations redisOps, // - RedisModulesOperations rmo, // - RedisMappingContext mappingContext, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - RedisOMProperties redisOMProperties - ) { + RedisOperations redisOps, // + RedisModulesOperations rmo, // + RedisMappingContext mappingContext, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + RedisOMProperties redisOMProperties) { this(redisOps, rmo, mappingContext, new RedisOMCustomConversions(), indexer, featureExtractor, redisOMProperties); } /** * Creates new {@link RedisKeyValueAdapter}. * - * @param redisOps must not be {@literal null}. - * @param rmo must not be {@literal null}. - * @param mappingContext must not be {@literal null}. - * @param customConversions can be {@literal null}. - * @param indexer must not be {@literal null}. + * @param redisOps must not be {@literal null}. + * @param rmo must not be {@literal null}. + * @param mappingContext must not be {@literal null}. + * @param customConversions can be {@literal null}. + * @param indexer must not be {@literal null}. */ @SuppressWarnings("unchecked") public RedisEnhancedKeyValueAdapter( // - RedisOperations redisOps, // - RedisModulesOperations rmo, // - RedisMappingContext mappingContext, // - @Nullable CustomConversions customConversions, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - RedisOMProperties redisOMProperties - ) { + RedisOperations redisOps, // + RedisModulesOperations rmo, // + RedisMappingContext mappingContext, // + @Nullable CustomConversions customConversions, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + RedisOMProperties redisOMProperties) { super(redisOps, mappingContext, customConversions); Assert.notNull(redisOps, "RedisOperations must not be null!"); Assert.notNull(mappingContext, "RedisMappingContext must not be null!"); MappingRedisOMConverter mappingConverter = new MappingRedisOMConverter(mappingContext, - new ReferenceResolverImpl(redisOps)); - mappingConverter - .setCustomConversions(customConversions == null ? new RedisOMCustomConversions() : customConversions); + new ReferenceResolverImpl(redisOps)); + mappingConverter.setCustomConversions( + customConversions == null ? new RedisOMCustomConversions() : customConversions); mappingConverter.afterPropertiesSet(); this.converter = mappingConverter; @@ -185,8 +182,8 @@ public T get(Object id, String keyspace, Class type) { byte[] binId = createKey(stringKeyspace, stringId); - Map raw = redisOperations - .execute((RedisCallback>) connection -> connection.hashCommands().hGetAll(binId)); + Map raw = redisOperations.execute( + (RedisCallback>) connection -> connection.hashCommands().hGetAll(binId)); if (CollectionUtils.isEmpty(raw)) { return null; @@ -231,10 +228,8 @@ public List getAllIds(String keyspace, Class type) { keys = searchResult.getDocuments().stream() .map(d -> documentToObject(d, type, (MappingRedisOMConverter) converter)) - .map(e -> maybeIdField.map(field -> getIdFieldForEntity(field, e)).orElse(null)) - .filter(Objects::nonNull) - .map(Object::toString) - .toList(); + .map(e -> maybeIdField.map(field -> getIdFieldForEntity(field, e)).orElse(null)).filter(Objects::nonNull) + .map(Object::toString).toList(); } return keys; @@ -269,8 +264,8 @@ public List getAllOf(String keyspace, Class type, long offset, int row SearchResult searchResult = searchOps.search(query); result = (List) searchResult.getDocuments().stream() // - .map(d -> documentToObject(d, type, (MappingRedisOMConverter)converter)) // - .toList(); + .map(d -> documentToObject(d, type, (MappingRedisOMConverter) converter)) // + .toList(); } return result; @@ -302,7 +297,7 @@ public T delete(Object id, String keyspace, Class type) { /* * (non-Javadoc) - * + * * @see org.springframework.data.keyvalue.core.KeyValueAdapter#count(java.lang. * String) */ @@ -315,9 +310,9 @@ public long count(String keyspace) { // FT.SEARCH index * LIMIT 0 0 Query query = new Query("*"); query.limit(0, 0); - + SearchResult result = search.search(query); - + count = result.getTotalResults(); } return count; @@ -325,15 +320,15 @@ public long count(String keyspace) { /* * (non-Javadoc) - * + * * @see * org.springframework.data.keyvalue.core.KeyValueAdapter#contains(java.lang. * Object, java.lang.String) */ @Override public boolean contains(Object id, String keyspace) { - Boolean exists = redisOperations - .execute((RedisCallback) connection -> connection.keyCommands().exists(toBytes(getKey(keyspace, id)))); + Boolean exists = redisOperations.execute( + (RedisCallback) connection -> connection.keyCommands().exists(toBytes(getKey(keyspace, id)))); return exists != null && exists; } @@ -342,7 +337,7 @@ public boolean contains(Object id, String keyspace) { public void update(PartialUpdate update) { RedisPersistentEntity entity = this.converter.getMappingContext() - .getRequiredPersistentEntity(update.getTarget()); + .getRequiredPersistentEntity(update.getTarget()); String keyspace = sanitizeKeyspace(entity.getKeySpace()); Object id = update.getId(); @@ -360,10 +355,10 @@ public void update(PartialUpdate update) { String propertyPath = pUpdate.getPropertyPath(); - if (UpdateCommand.DEL.equals(pUpdate.getCmd()) || pUpdate.getValue() instanceof Collection - || pUpdate.getValue() instanceof Map - || (pUpdate.getValue() != null && pUpdate.getValue().getClass().isArray()) || (pUpdate.getValue() != null - && !converter.getConversionService().canConvert(pUpdate.getValue().getClass(), byte[].class))) { + if (UpdateCommand.DEL.equals( + pUpdate.getCmd()) || pUpdate.getValue() instanceof Collection || pUpdate.getValue() instanceof Map || (pUpdate.getValue() != null && pUpdate.getValue() + .getClass().isArray()) || (pUpdate.getValue() != null && !converter.getConversionService() + .canConvert(pUpdate.getValue().getClass(), byte[].class))) { redisUpdateObject = fetchDeletePathsFromHash(redisUpdateObject, propertyPath, connection); } @@ -371,14 +366,14 @@ public void update(PartialUpdate update) { if (!redisUpdateObject.fieldsToRemove.isEmpty()) { connection.hashCommands().hDel(redisKey, - redisUpdateObject.fieldsToRemove.toArray(new byte[redisUpdateObject.fieldsToRemove.size()][])); + redisUpdateObject.fieldsToRemove.toArray(new byte[redisUpdateObject.fieldsToRemove.size()][])); } if (!rdo.getBucket().isEmpty() && // - ( // - rdo.getBucket().size() > 1 || // - (rdo.getBucket().size() == 1 && !rdo.getBucket().asMap().containsKey("_class")) // - )) { + ( // + rdo.getBucket().size() > 1 || // + (rdo.getBucket().size() == 1 && !rdo.getBucket().asMap().containsKey("_class")) // + )) { connection.hashCommands().hMSet(redisKey, rdo.getBucket().rawMap()); } @@ -396,7 +391,7 @@ public void update(PartialUpdate update) { } private RedisUpdateObject fetchDeletePathsFromHash(RedisUpdateObject redisUpdateObject, String path, - RedisConnection connection) { + RedisConnection connection) { redisUpdateObject.addFieldToRemove(toBytes(path)); byte[] value = connection.hashCommands().hGet(redisUpdateObject.targetKey, toBytes(path)); @@ -429,7 +424,7 @@ private String asStringValue(Object value) { /** * Read back and set {@link TimeToLive} for the property. * - * @param key the key to read the TTL for. + * @param key the key to read the TTL for. * @param target the target object. * @return the target object with the TTL set. */ @@ -464,7 +459,7 @@ private T readTimeToLiveIfSet(@Nullable byte[] key, @Nullable T target) { PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(target); propertyAccessor.setProperty(ttlProperty, - converter.getConversionService().convert(timeout, ttlProperty.getType())); + converter.getConversionService().convert(timeout, ttlProperty.getType())); target = propertyAccessor.getBean(); } @@ -474,17 +469,19 @@ private T readTimeToLiveIfSet(@Nullable byte[] key, @Nullable T target) { } /** - * @return {@literal true} if {@link RedisData#getTimeToLive()} has a positive - * value. - * * @param data must not be {@literal null}. + * @return {@literal true} if {@link RedisData#getTimeToLive()} has a positive + * value. * @since 2.3.7 */ private boolean willExpire(RedisData data) { return data.getTimeToLive() != null && data.getTimeToLive() > 0; } - + protected String getKey(String keyspace, Object id) { + String sanitizedKeyspace = sanitizeKeyspace(keyspace); + return String.format("%s:%s", sanitizedKeyspace, id); + } /** * Container holding update information like fields to remove from the Redis @@ -505,9 +502,4 @@ void addFieldToRemove(byte[] field) { fieldsToRemove.add(field); } } - - protected String getKey(String keyspace, Object id) { - String sanitizedKeyspace = sanitizeKeyspace(keyspace); - return String.format("%s:%s", sanitizedKeyspace, id); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RedisJSONKeyValueAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/RedisJSONKeyValueAdapter.java index 7c5ef848..70865b79 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RedisJSONKeyValueAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RedisJSONKeyValueAdapter.java @@ -59,10 +59,10 @@ public class RedisJSONKeyValueAdapter extends RedisKeyValueAdapter { * Creates new {@link RedisKeyValueAdapter} with default * {@link RedisCustomConversions}. * - * @param redisOps must not be {@literal null}. - * @param rmo must not be {@literal null}. - * @param mappingContext must not be {@literal null}. - * @param keyspaceToIndexMap must not be {@literal null}. + * @param redisOps must not be {@literal null}. + * @param rmo must not be {@literal null}. + * @param mappingContext must not be {@literal null}. + * @param keyspaceToIndexMap must not be {@literal null}. */ @SuppressWarnings("unchecked") public RedisJSONKeyValueAdapter( // @@ -72,8 +72,7 @@ public RedisJSONKeyValueAdapter( // RediSearchIndexer keyspaceToIndexMap, // GsonBuilder gsonBuilder, // FeatureExtractor featureExtractor, // - RedisOMProperties redisOMProperties - ) { + RedisOMProperties redisOMProperties) { super(redisOps, mappingContext, new RedisOMCustomConversions()); this.modulesOperations = (RedisModulesOperations) rmo; this.redisJSONOperations = modulesOperations.opsForJSON(); @@ -96,8 +95,7 @@ public RedisJSONKeyValueAdapter( // @Override public Object put(Object id, Object item, String keyspace) { logger.debug(String.format("%s, %s, %s", id, item, keyspace)); - @SuppressWarnings("unchecked") - JSONOperations ops = (JSONOperations) redisJSONOperations; + @SuppressWarnings("unchecked") JSONOperations ops = (JSONOperations) redisJSONOperations; String key = getKey(keyspace, id); @@ -110,7 +108,10 @@ public Object put(Object id, Object item, String keyspace) { processReferences(key, item); redisOperations.execute((RedisCallback) connection -> { - maybeTtl.ifPresent(ttl -> { if (ttl > 0) connection.keyCommands().expire(toBytes(key), ttl); }); + maybeTtl.ifPresent(ttl -> { + if (ttl > 0) + connection.keyCommands().expire(toBytes(key), ttl); + }); return null; }); @@ -132,8 +133,7 @@ public T get(Object id, String keyspace, Class type) { @Nullable public T get(String key, Class type) { - @SuppressWarnings("unchecked") - JSONOperations ops = (JSONOperations) redisJSONOperations; + @SuppressWarnings("unchecked") JSONOperations ops = (JSONOperations) redisJSONOperations; return ops.get(key, type); } @@ -163,8 +163,8 @@ public List getAllOf(String keyspace, Class type, long offset, int row SearchResult searchResult = searchOps.search(query); Gson gson = gsonBuilder.create(); result = searchResult.getDocuments().stream() - .map(d -> gson.fromJson(SafeEncoder.encode((byte[])d.get("$")), type)) // - .toList(); + .map(d -> gson.fromJson(SafeEncoder.encode((byte[]) d.get("$")), type)) // + .toList(); } return result; @@ -182,10 +182,9 @@ public List getAllKeys(String keyspace, Class type) { Query query = new Query("*"); query.returnFields(idField); SearchResult searchResult = searchOps.search(query); - - keys = searchResult.getDocuments().stream() - .map(Document::getId) // - .toList(); + + keys = searchResult.getDocuments().stream().map(Document::getId) // + .toList(); } return keys; @@ -193,15 +192,14 @@ public List getAllKeys(String keyspace, Class type) { /* * (non-Javadoc) - * + * * @see * org.springframework.data.keyvalue.core.AbstractKeyValueAdapter#delete(java. * lang.Object, java.lang.String, java.lang.Class) */ @Override public T delete(Object id, String keyspace, Class type) { - @SuppressWarnings("unchecked") - JSONOperations ops = (JSONOperations) redisJSONOperations; + @SuppressWarnings("unchecked") JSONOperations ops = (JSONOperations) redisJSONOperations; T entity = get(id, keyspace, type); if (entity != null) { ops.del(getKey(keyspace, id), Path2.ROOT_PATH); @@ -230,7 +228,7 @@ public void deleteAllOf(String keyspace) { /* * (non-Javadoc) - * + * * @see org.springframework.data.keyvalue.core.KeyValueAdapter#count(java.lang. * String) */ @@ -243,9 +241,9 @@ public long count(String keyspace) { // FT.SEARCH index * LIMIT 0 0 Query query = new Query("*"); query.limit(0, 0); - + SearchResult result = search.search(query); - + count = result.getTotalResults(); } return count; @@ -253,15 +251,15 @@ public long count(String keyspace) { /* * (non-Javadoc) - * + * * @see * org.springframework.data.keyvalue.core.KeyValueAdapter#contains(java.lang. * Object, java.lang.String) */ @Override public boolean contains(Object id, String keyspace) { - Boolean exists = redisOperations - .execute((RedisCallback) connection -> connection.keyCommands().exists(toBytes(getKey(keyspace, id)))); + Boolean exists = redisOperations.execute( + (RedisCallback) connection -> connection.keyCommands().exists(toBytes(getKey(keyspace, id)))); return exists != null && exists; } @@ -303,15 +301,15 @@ private void processVersion(String key, Object item) { BeanWrapper wrapper = new BeanWrapperImpl(item); Field versionField = fields.get(0); String property = versionField.getName(); - if ((versionField.getType() == Integer.class || isPrimitiveOfType(versionField.getType(), Integer.class)) || - (versionField.getType() == Long.class || isPrimitiveOfType(versionField.getType(), Long.class))) { + if ((versionField.getType() == Integer.class || isPrimitiveOfType(versionField.getType(), + Integer.class)) || (versionField.getType() == Long.class || isPrimitiveOfType(versionField.getType(), + Long.class))) { Number version = (Number) wrapper.getPropertyValue(property); Number dbVersion = getEntityVersion(key, property); if (dbVersion != null && version != null && dbVersion.longValue() != version.longValue()) { throw new OptimisticLockingFailureException( - String.format("Cannot insert/update entity %s with version %s as it already exists", item, - version)); + String.format("Cannot insert/update entity %s with version %s as it already exists", item, version)); } else { Number nextVersion = version == null ? 0 : version.longValue() + 1; try { @@ -372,7 +370,8 @@ private Optional getTTLForEntity(Object entity) { @SuppressWarnings("unchecked") private Number getEntityVersion(String key, String versionProperty) { JSONOperations ops = (JSONOperations) redisJSONOperations; - Class type = new TypeToken() {}.getRawType(); + Class type = new TypeToken() { + }.getRawType(); Long[] dbVersionArray = (Long[]) ops.get(key, type, Path2.of("$." + versionProperty)); return dbVersionArray != null ? dbVersionArray[0] : null; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RedisModulesConfiguration.java b/redis-om-spring/src/main/java/com/redis/om/spring/RedisModulesConfiguration.java index cf9aa5fc..03391ab6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RedisModulesConfiguration.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RedisModulesConfiguration.java @@ -73,7 +73,7 @@ import static com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively; @Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties({RedisProperties.class, RedisOMProperties.class}) +@EnableConfigurationProperties({ RedisProperties.class, RedisOMProperties.class }) @EnableAspectJAutoProxy @ComponentScan("com.redis.om.spring.bloom") @ComponentScan("com.redis.om.spring.cuckoo") @@ -107,8 +107,8 @@ public GsonBuilder gsonBuilder(List customizers) { @Bean(name = "redisModulesClient") @Lazy RedisModulesClient redisModulesClient( // - JedisConnectionFactory jedisConnectionFactory, // - @Qualifier("omGsonBuilder") GsonBuilder builder) { + JedisConnectionFactory jedisConnectionFactory, // + @Qualifier("omGsonBuilder") GsonBuilder builder) { return new RedisModulesClient(jedisConnectionFactory, builder); } @@ -117,9 +117,9 @@ RedisModulesClient redisModulesClient( // @ConditionalOnMissingBean @Lazy RedisModulesOperations redisModulesOperations( // - RedisModulesClient rmc, // - StringRedisTemplate template, // - @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder) { + RedisModulesClient rmc, // + StringRedisTemplate template, // + @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder) { return new RedisModulesOperations<>(rmc, template, gsonBuilder); } @@ -151,7 +151,7 @@ CuckooFilterOperations redisCuckooFilterOperations(RedisModulesOperations @Bean(name = "rediSearchIndexer") public RediSearchIndexer redisearchIndexer(ApplicationContext ac, - @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder) { + @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder) { return new RediSearchIndexer(ac, gsonBuilder); } @@ -163,42 +163,40 @@ public ImageFactory imageFactory() { @Bean(name = "djlImageEmbeddingModelCriteria") public Criteria imageEmbeddingModelCriteria(RedisOMProperties properties) { - return properties.getDjl().isEnabled() ? Criteria.builder() - .setTypes(Image.class, byte[].class) // - .optEngine(properties.getDjl().getImageEmbeddingModelEngine()) // - .optModelUrls(properties.getDjl().getImageEmbeddingModelModelUrls()) // - .build() : null; + return properties.getDjl().isEnabled() ? Criteria.builder().setTypes(Image.class, byte[].class) // + .optEngine(properties.getDjl().getImageEmbeddingModelEngine()) // + .optModelUrls(properties.getDjl().getImageEmbeddingModelModelUrls()) // + .build() : null; } @Bean(name = "djlFaceDetectionTranslator") public Translator faceDetectionTranslator() { double confThresh = 0.85f; double nmsThresh = 0.45f; - double[] variance = {0.1f, 0.2f}; + double[] variance = { 0.1f, 0.2f }; int topK = 5000; - int[][] scales = {{16, 32}, {64, 128}, {256, 512}}; - int[] steps = {8, 16, 32}; + int[][] scales = { { 16, 32 }, { 64, 128 }, { 256, 512 } }; + int[] steps = { 8, 16, 32 }; return new FaceDetectionTranslator(confThresh, nmsThresh, variance, topK, scales, steps); } @Bean(name = "djlFaceDetectionModelCriteria") public Criteria faceDetectionModelCriteria( // - @Qualifier("djlFaceDetectionTranslator") Translator translator, // - RedisOMProperties properties) { - - return properties.getDjl().isEnabled() ? Criteria.builder() - .setTypes(Image.class, DetectedObjects.class) // - .optModelUrls(properties.getDjl().getFaceDetectionModelModelUrls()) // - .optModelName(properties.getDjl().getFaceDetectionModelName()) // - .optTranslator(translator) // - .optEngine(properties.getDjl().getFaceDetectionModelEngine()) // - .build() : null; + @Qualifier("djlFaceDetectionTranslator") Translator translator, // + RedisOMProperties properties) { + + return properties.getDjl().isEnabled() ? Criteria.builder().setTypes(Image.class, DetectedObjects.class) // + .optModelUrls(properties.getDjl().getFaceDetectionModelModelUrls()) // + .optModelName(properties.getDjl().getFaceDetectionModelName()) // + .optTranslator(translator) // + .optEngine(properties.getDjl().getFaceDetectionModelEngine()) // + .build() : null; } @Bean(name = "djlFaceDetectionModel") public ZooModel faceDetectionModel( - @Nullable @Qualifier("djlFaceDetectionModelCriteria") Criteria criteria, - RedisOMProperties properties) { + @Nullable @Qualifier("djlFaceDetectionModelCriteria") Criteria criteria, + RedisOMProperties properties) { try { return properties.getDjl().isEnabled() && (criteria != null) ? ModelZoo.loadModel(criteria) : null; } catch (IOException | ModelNotFoundException | MalformedModelException ex) { @@ -214,22 +212,21 @@ public Translator faceEmbeddingTranslator() { @Bean(name = "djlFaceEmbeddingModelCriteria") public Criteria faceEmbeddingModelCriteria( // - @Qualifier("djlFaceEmbeddingTranslator") Translator translator, // - RedisOMProperties properties) { + @Qualifier("djlFaceEmbeddingTranslator") Translator translator, // + RedisOMProperties properties) { return properties.getDjl().isEnabled() ? Criteria.builder() // - .setTypes(Image.class, float[].class) - .optModelUrls(properties.getDjl().getFaceEmbeddingModelModelUrls()) // - .optModelName(properties.getDjl().getFaceEmbeddingModelName()) // - .optTranslator(translator) // - .optEngine(properties.getDjl().getFaceEmbeddingModelEngine()) // - .build() : null; + .setTypes(Image.class, float[].class).optModelUrls(properties.getDjl().getFaceEmbeddingModelModelUrls()) // + .optModelName(properties.getDjl().getFaceEmbeddingModelName()) // + .optTranslator(translator) // + .optEngine(properties.getDjl().getFaceEmbeddingModelEngine()) // + .build() : null; } @Bean(name = "djlFaceEmbeddingModel") public ZooModel faceEmbeddingModel( - @Nullable @Qualifier("djlFaceEmbeddingModelCriteria") Criteria criteria, // - RedisOMProperties properties) { + @Nullable @Qualifier("djlFaceEmbeddingModelCriteria") Criteria criteria, // + RedisOMProperties properties) { try { return properties.getDjl().isEnabled() && (criteria != null) ? ModelZoo.loadModel(criteria) : null; } catch (Exception e) { @@ -240,8 +237,8 @@ public ZooModel faceEmbeddingModel( @Bean(name = "djlImageEmbeddingModel") public ZooModel imageModel( - @Nullable @Qualifier("djlImageEmbeddingModelCriteria") Criteria criteria, RedisOMProperties properties) - throws MalformedModelException, ModelNotFoundException, IOException { + @Nullable @Qualifier("djlImageEmbeddingModelCriteria") Criteria criteria, + RedisOMProperties properties) throws MalformedModelException, ModelNotFoundException, IOException { return properties.getDjl().isEnabled() && (criteria != null) ? ModelZoo.loadModel(criteria) : null; } @@ -253,20 +250,21 @@ public Pipeline defaultImagePipeline(RedisOMProperties properties) { pipeline.add(new CenterCrop()); } return pipeline // - .add(new Resize( // - properties.getDjl().getDefaultImagePipelineResizeWidth(), // - properties.getDjl().getDefaultImagePipelineResizeHeight() // - )) // - .add(new ToTensor()); - } else return null; + .add(new Resize( // + properties.getDjl().getDefaultImagePipelineResizeWidth(), // + properties.getDjl().getDefaultImagePipelineResizeHeight() // + )) // + .add(new ToTensor()); + } else + return null; } @Bean(name = "djlSentenceTokenizer") public HuggingFaceTokenizer sentenceTokenizer(RedisOMProperties properties) { if (properties.getDjl().isEnabled()) { Map options = Map.of( // - "maxLength", properties.getDjl().getSentenceTokenizerMaxLength(), // - "modelMaxLength", properties.getDjl().getSentenceTokenizerModelMaxLength() // + "maxLength", properties.getDjl().getSentenceTokenizerMaxLength(), // + "modelMaxLength", properties.getDjl().getSentenceTokenizerModelMaxLength() // ); try { @@ -277,74 +275,73 @@ public HuggingFaceTokenizer sentenceTokenizer(RedisOMProperties properties) { logger.warn("Error retrieving default DJL sentence tokenizer"); return null; } - } else return null; + } else + return null; } @Bean(name = "featureExtractor") public FeatureExtractor featureExtractor( - @Nullable @Qualifier("djlImageEmbeddingModel") ZooModel imageEmbeddingModel, - @Nullable @Qualifier("djlFaceEmbeddingModel") ZooModel faceEmbeddingModel, - @Nullable @Qualifier("djlImageFactory") ImageFactory imageFactory, - @Nullable @Qualifier("djlDefaultImagePipeline") Pipeline defaultImagePipeline, - @Nullable @Qualifier("djlSentenceTokenizer") HuggingFaceTokenizer sentenceTokenizer, - RedisOMProperties properties, - ApplicationContext ac) { - return properties.getDjl().isEnabled() ? new DefaultFeatureExtractor( ac, imageEmbeddingModel, faceEmbeddingModel, imageFactory, defaultImagePipeline, sentenceTokenizer) : new NoopFeatureExtractor(); + @Nullable @Qualifier("djlImageEmbeddingModel") ZooModel imageEmbeddingModel, + @Nullable @Qualifier("djlFaceEmbeddingModel") ZooModel faceEmbeddingModel, + @Nullable @Qualifier("djlImageFactory") ImageFactory imageFactory, + @Nullable @Qualifier("djlDefaultImagePipeline") Pipeline defaultImagePipeline, + @Nullable @Qualifier("djlSentenceTokenizer") HuggingFaceTokenizer sentenceTokenizer, RedisOMProperties properties, + ApplicationContext ac) { + return properties.getDjl().isEnabled() ? + new DefaultFeatureExtractor(ac, imageEmbeddingModel, faceEmbeddingModel, imageFactory, defaultImagePipeline, + sentenceTokenizer) : + new NoopFeatureExtractor(); } @Bean(name = "redisJSONKeyValueAdapter") RedisJSONKeyValueAdapter getRedisJSONKeyValueAdapter( // - RedisOperations redisOps, // - RedisModulesOperations redisModulesOperations, // - RedisMappingContext mappingContext, // - RediSearchIndexer indexer, // - @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, // - RedisOMProperties properties, // - @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor - ) { - return new RedisJSONKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, gsonBuilder, featureExtractor, properties); + RedisOperations redisOps, // + RedisModulesOperations redisModulesOperations, // + RedisMappingContext mappingContext, // + RediSearchIndexer indexer, // + @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, // + RedisOMProperties properties, // + @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor) { + return new RedisJSONKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, gsonBuilder, + featureExtractor, properties); } @Bean(name = "redisJSONKeyValueTemplate") public CustomRedisKeyValueTemplate getRedisJSONKeyValueTemplate( // - RedisOperations redisOps, // - RedisModulesOperations redisModulesOperations, // - RedisMappingContext mappingContext, // - RediSearchIndexer indexer, // - @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, // - RedisOMProperties properties, // - @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor - ) { + RedisOperations redisOps, // + RedisModulesOperations redisModulesOperations, // + RedisMappingContext mappingContext, // + RediSearchIndexer indexer, // + @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, // + RedisOMProperties properties, // + @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor) { return new CustomRedisKeyValueTemplate( - new RedisJSONKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, gsonBuilder, featureExtractor, properties), - mappingContext); + new RedisJSONKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, gsonBuilder, + featureExtractor, properties), mappingContext); } @Bean(name = "redisCustomKeyValueTemplate") public CustomRedisKeyValueTemplate getKeyValueTemplate( // - RedisOperations redisOps, // - RedisModulesOperations redisModulesOperations, // - RedisMappingContext mappingContext, // - RediSearchIndexer indexer, // - RedisOMProperties properties, // - @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor - ) { + RedisOperations redisOps, // + RedisModulesOperations redisModulesOperations, // + RedisMappingContext mappingContext, // + RediSearchIndexer indexer, // + RedisOMProperties properties, // + @Nullable @Qualifier("featureExtractor") FeatureExtractor featureExtractor) { return new CustomRedisKeyValueTemplate( - new RedisEnhancedKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, featureExtractor, properties), // - mappingContext); + new RedisEnhancedKeyValueAdapter(redisOps, redisModulesOperations, mappingContext, indexer, featureExtractor, + properties), // + mappingContext); } @Bean(name = "streamingQueryBuilder") - EntityStream streamingQueryBuilder( - RedisModulesOperations redisModulesOperations, - @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, - RediSearchIndexer indexer - ) { + EntityStream streamingQueryBuilder(RedisModulesOperations redisModulesOperations, + @Qualifier("omGsonBuilder") GsonBuilder gsonBuilder, RediSearchIndexer indexer) { return new EntityStreamImpl(redisModulesOperations, gsonBuilder, indexer); } @Bean(name = "redisOMCacheManager") - public CacheManager getCacheManager(){ + public CacheManager getCacheManager() { return new ConcurrentMapCacheManager(); } @@ -362,8 +359,8 @@ public void ensureIndexesAreCreated(ContextRefreshedEvent cre) { @EventListener(ContextRefreshedEvent.class) public void processBloom(ContextRefreshedEvent cre) { ApplicationContext ac = cre.getApplicationContext(); - @SuppressWarnings("unchecked") - RedisModulesOperations rmo = (RedisModulesOperations) ac.getBean("redisModulesOperations"); + @SuppressWarnings("unchecked") RedisModulesOperations rmo = (RedisModulesOperations) ac.getBean( + "redisModulesOperations"); Set beanDefs = getBeanDefinitionsFor(ac, Document.class, RedisHash.class); @@ -374,8 +371,9 @@ public void processBloom(ContextRefreshedEvent cre) { if (field.isAnnotationPresent(Bloom.class)) { Bloom bloom = field.getAnnotation(Bloom.class); BloomOperations ops = rmo.opsForBloom(); - String filterName = !ObjectUtils.isEmpty(bloom.name()) ? bloom.name() - : String.format("bf:%s:%s", cl.getSimpleName(), field.getName()); + String filterName = !ObjectUtils.isEmpty(bloom.name()) ? + bloom.name() : + String.format("bf:%s:%s", cl.getSimpleName(), field.getName()); ops.createFilter(filterName, bloom.capacity(), bloom.errorRate()); } } @@ -388,8 +386,8 @@ public void processBloom(ContextRefreshedEvent cre) { @EventListener(ContextRefreshedEvent.class) public void processCuckoo(ContextRefreshedEvent cre) { ApplicationContext ac = cre.getApplicationContext(); - @SuppressWarnings("unchecked") - RedisModulesOperations rmo = (RedisModulesOperations) ac.getBean("redisModulesOperations"); + @SuppressWarnings("unchecked") RedisModulesOperations rmo = (RedisModulesOperations) ac.getBean( + "redisModulesOperations"); Set beanDefs = getBeanDefinitionsFor(ac, Document.class, RedisHash.class); @@ -400,12 +398,11 @@ public void processCuckoo(ContextRefreshedEvent cre) { if (field.isAnnotationPresent(Cuckoo.class)) { Cuckoo cuckoo = field.getAnnotation(Cuckoo.class); CuckooFilterOperations ops = rmo.opsForCuckoFilter(); - String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? cuckoo.name() - : String.format("cf:%s:%s", cl.getSimpleName(), field.getName()); - CFReserveParams params = CFReserveParams.reserveParams() - .bucketSize(cuckoo.bucketSize()) - .expansion(cuckoo.expansion()) - .maxIterations(cuckoo.maxIterations()); + String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? + cuckoo.name() : + String.format("cf:%s:%s", cl.getSimpleName(), field.getName()); + CFReserveParams params = CFReserveParams.reserveParams().bucketSize(cuckoo.bucketSize()) + .expansion(cuckoo.expansion()).maxIterations(cuckoo.maxIterations()); ops.createFilter(filterName, cuckoo.capacity(), params); } } @@ -420,7 +417,7 @@ public void registerReferenceSerializer(ContextRefreshedEvent cre) { logger.info("Registering Reference Serializers......"); ApplicationContext ac = cre.getApplicationContext(); - GsonBuilder gsonBuilder = (GsonBuilder)ac.getBean("omGsonBuilder"); + GsonBuilder gsonBuilder = (GsonBuilder) ac.getBean("omGsonBuilder"); GsonReferenceSerializerRegistrar registrar = new GsonReferenceSerializerRegistrar(gsonBuilder, ac); registrar.registerReferencesFor(Document.class); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RedisOMProperties.java b/redis-om-spring/src/main/java/com/redis/om/spring/RedisOMProperties.java index 7673b21f..3e866af8 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RedisOMProperties.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RedisOMProperties.java @@ -7,228 +7,230 @@ import java.util.List; @ConfigurationProperties( - prefix = "redis.om.spring", ignoreInvalidFields = true + prefix = "redis.om.spring", ignoreInvalidFields = true ) public class RedisOMProperties { - public static final int MAX_SEARCH_RESULTS = 10000; - // repository properties - private final Repository repository = new Repository(); - private final References references = new References(); - - public Repository getRepository() { - return repository; - } - public References getReferences() { return references; } - - public static class Repository { - private final Query query = new Query(); - - public Query getQuery() { - return query; - } - - public static class Query { - private int limit = MAX_SEARCH_RESULTS; - - public int getLimit() { - return limit; - } - - public void setLimit(int limit) { - this.limit = limit; - } - } - } - - public static class References { - private String cacheName = "roms-reference-cache"; - private List cachedReferenceClasses = new ArrayList<>(); - - public String getCacheName() { - return cacheName; - } - - public void setCacheName(String cacheName) { - this.cacheName = cacheName; - } - - public List getCachedReferenceClasses() { - return cachedReferenceClasses; - } - - public void setCachedReferenceClasses(List cachedReferenceClasses) { - this.cachedReferenceClasses = cachedReferenceClasses; - } - } - - // DJL properties - public static class Djl { - private static final String DEFAULT_ENGINE = "PyTorch"; - private boolean enabled = false; - // image embedding settings - @NotNull - private String imageEmbeddingModelEngine = DEFAULT_ENGINE; - @NotNull - private String imageEmbeddingModelModelUrls = "djl://ai.djl.pytorch/resnet18_embedding"; - private int defaultImagePipelineResizeWidth = 224; - private int defaultImagePipelineResizeHeight = 224; - private boolean defaultImagePipelineCenterCrop = true; - - // sentence tokenizer settings - @NotNull - private String sentenceTokenizerMaxLength = "768"; - @NotNull - private String sentenceTokenizerModelMaxLength = "768"; - @NotNull - private String sentenceTokenizerModel = "sentence-transformers/all-mpnet-base-v2"; - - // face detection - @NotNull - private String faceDetectionModelEngine = DEFAULT_ENGINE; - @NotNull - private String faceDetectionModelName = "retinaface"; - @NotNull - private String faceDetectionModelModelUrls = "https://resources.djl.ai/test-models/pytorch/retinaface.zip"; - - // face embeddings - @NotNull - private String faceEmbeddingModelEngine = DEFAULT_ENGINE; - @NotNull - private String faceEmbeddingModelName = "face_feature"; - @NotNull - private String faceEmbeddingModelModelUrls = "https://resources.djl.ai/test-models/pytorch/face_feature.zip"; - - public Djl() { - } - - public boolean isEnabled() { - return this.enabled; - } - - public @NotNull String getImageEmbeddingModelEngine() { - return this.imageEmbeddingModelEngine; - } - - public @NotNull String getImageEmbeddingModelModelUrls() { - return this.imageEmbeddingModelModelUrls; - } - - public int getDefaultImagePipelineResizeWidth() { - return this.defaultImagePipelineResizeWidth; - } - - public int getDefaultImagePipelineResizeHeight() { - return this.defaultImagePipelineResizeHeight; - } - - public boolean isDefaultImagePipelineCenterCrop() { - return this.defaultImagePipelineCenterCrop; - } - - public @NotNull String getSentenceTokenizerMaxLength() { - return this.sentenceTokenizerMaxLength; - } - - public @NotNull String getSentenceTokenizerModelMaxLength() { - return this.sentenceTokenizerModelMaxLength; - } - - public @NotNull String getSentenceTokenizerModel() { - return this.sentenceTokenizerModel; - } - - public @NotNull String getFaceDetectionModelEngine() { - return this.faceDetectionModelEngine; - } - - public @NotNull String getFaceDetectionModelName() { - return this.faceDetectionModelName; - } - - public @NotNull String getFaceDetectionModelModelUrls() { - return this.faceDetectionModelModelUrls; - } - - public @NotNull String getFaceEmbeddingModelEngine() { - return this.faceEmbeddingModelEngine; - } - - public @NotNull String getFaceEmbeddingModelName() { - return this.faceEmbeddingModelName; - } - - public @NotNull String getFaceEmbeddingModelModelUrls() { - return this.faceEmbeddingModelModelUrls; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public void setImageEmbeddingModelEngine(@NotNull String imageEmbeddingModelEngine) { - this.imageEmbeddingModelEngine = imageEmbeddingModelEngine; - } - - public void setImageEmbeddingModelModelUrls(@NotNull String imageEmbeddingModelModelUrls) { - this.imageEmbeddingModelModelUrls = imageEmbeddingModelModelUrls; - } + public static final int MAX_SEARCH_RESULTS = 10000; + // repository properties + private final Repository repository = new Repository(); + private final References references = new References(); + private final Djl djl = new Djl(); - public void setDefaultImagePipelineResizeWidth(int defaultImagePipelineResizeWidth) { - this.defaultImagePipelineResizeWidth = defaultImagePipelineResizeWidth; - } + public Repository getRepository() { + return repository; + } - public void setDefaultImagePipelineResizeHeight(int defaultImagePipelineResizeHeight) { - this.defaultImagePipelineResizeHeight = defaultImagePipelineResizeHeight; - } + public References getReferences() { + return references; + } - public void setDefaultImagePipelineCenterCrop(boolean defaultImagePipelineCenterCrop) { - this.defaultImagePipelineCenterCrop = defaultImagePipelineCenterCrop; - } + public Djl getDjl() { + return djl; + } - public void setSentenceTokenizerMaxLength(@NotNull String sentenceTokenizerMaxLength) { - this.sentenceTokenizerMaxLength = sentenceTokenizerMaxLength; - } + public static class Repository { + private final Query query = new Query(); - public void setSentenceTokenizerModelMaxLength(@NotNull String sentenceTokenizerModelMaxLength) { - this.sentenceTokenizerModelMaxLength = sentenceTokenizerModelMaxLength; - } + public Query getQuery() { + return query; + } - public void setSentenceTokenizerModel(@NotNull String sentenceTokenizerModel) { - this.sentenceTokenizerModel = sentenceTokenizerModel; - } + public static class Query { + private int limit = MAX_SEARCH_RESULTS; - public void setFaceDetectionModelEngine(@NotNull String faceDetectionModelEngine) { - this.faceDetectionModelEngine = faceDetectionModelEngine; - } + public int getLimit() { + return limit; + } - public void setFaceDetectionModelName(@NotNull String faceDetectionModelName) { - this.faceDetectionModelName = faceDetectionModelName; - } + public void setLimit(int limit) { + this.limit = limit; + } + } + } - public void setFaceDetectionModelModelUrls(@NotNull String faceDetectionModelModelUrls) { - this.faceDetectionModelModelUrls = faceDetectionModelModelUrls; - } + public static class References { + private String cacheName = "roms-reference-cache"; + private List cachedReferenceClasses = new ArrayList<>(); - public void setFaceEmbeddingModelEngine(@NotNull String faceEmbeddingModelEngine) { - this.faceEmbeddingModelEngine = faceEmbeddingModelEngine; - } + public String getCacheName() { + return cacheName; + } - public void setFaceEmbeddingModelName(@NotNull String faceEmbeddingModelName) { - this.faceEmbeddingModelName = faceEmbeddingModelName; - } + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } - public void setFaceEmbeddingModelModelUrls(@NotNull String faceEmbeddingModelModelUrls) { - this.faceEmbeddingModelModelUrls = faceEmbeddingModelModelUrls; - } + public List getCachedReferenceClasses() { + return cachedReferenceClasses; + } - public String toString() { - return "RedisOMSpringProperties.Djl(enabled=" + this.isEnabled() + ", imageEmbeddingModelEngine=" + this.getImageEmbeddingModelEngine() + ", imageEmbeddingModelModelUrls=" + this.getImageEmbeddingModelModelUrls() + ", defaultImagePipelineResizeWidth=" + this.getDefaultImagePipelineResizeWidth() + ", defaultImagePipelineResizeHeight=" + this.getDefaultImagePipelineResizeHeight() + ", defaultImagePipelineCenterCrop=" + this.isDefaultImagePipelineCenterCrop() + ", sentenceTokenizerMaxLength=" + this.getSentenceTokenizerMaxLength() + ", sentenceTokenizerModelMaxLength=" + this.getSentenceTokenizerModelMaxLength() + ", sentenceTokenizerModel=" + this.getSentenceTokenizerModel() + ", faceDetectionModelEngine=" + this.getFaceDetectionModelEngine() + ", faceDetectionModelName=" + this.getFaceDetectionModelName() + ", faceDetectionModelModelUrls=" + this.getFaceDetectionModelModelUrls() + ", faceEmbeddingModelEngine=" + this.getFaceEmbeddingModelEngine() + ", faceEmbeddingModelName=" + this.getFaceEmbeddingModelName() + ", faceEmbeddingModelModelUrls=" + this.getFaceEmbeddingModelModelUrls() + ")"; - } + public void setCachedReferenceClasses(List cachedReferenceClasses) { + this.cachedReferenceClasses = cachedReferenceClasses; + } + } + + // DJL properties + public static class Djl { + private static final String DEFAULT_ENGINE = "PyTorch"; + private boolean enabled = false; + // image embedding settings + @NotNull + private String imageEmbeddingModelEngine = DEFAULT_ENGINE; + @NotNull + private String imageEmbeddingModelModelUrls = "djl://ai.djl.pytorch/resnet18_embedding"; + private int defaultImagePipelineResizeWidth = 224; + private int defaultImagePipelineResizeHeight = 224; + private boolean defaultImagePipelineCenterCrop = true; + + // sentence tokenizer settings + @NotNull + private String sentenceTokenizerMaxLength = "768"; + @NotNull + private String sentenceTokenizerModelMaxLength = "768"; + @NotNull + private String sentenceTokenizerModel = "sentence-transformers/all-mpnet-base-v2"; + + // face detection + @NotNull + private String faceDetectionModelEngine = DEFAULT_ENGINE; + @NotNull + private String faceDetectionModelName = "retinaface"; + @NotNull + private String faceDetectionModelModelUrls = "https://resources.djl.ai/test-models/pytorch/retinaface.zip"; + + // face embeddings + @NotNull + private String faceEmbeddingModelEngine = DEFAULT_ENGINE; + @NotNull + private String faceEmbeddingModelName = "face_feature"; + @NotNull + private String faceEmbeddingModelModelUrls = "https://resources.djl.ai/test-models/pytorch/face_feature.zip"; + + public Djl() { + } + + public boolean isEnabled() { + return this.enabled; } - private final Djl djl = new Djl(); + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public @NotNull String getImageEmbeddingModelEngine() { + return this.imageEmbeddingModelEngine; + } + + public void setImageEmbeddingModelEngine(@NotNull String imageEmbeddingModelEngine) { + this.imageEmbeddingModelEngine = imageEmbeddingModelEngine; + } + + public @NotNull String getImageEmbeddingModelModelUrls() { + return this.imageEmbeddingModelModelUrls; + } + + public void setImageEmbeddingModelModelUrls(@NotNull String imageEmbeddingModelModelUrls) { + this.imageEmbeddingModelModelUrls = imageEmbeddingModelModelUrls; + } + + public int getDefaultImagePipelineResizeWidth() { + return this.defaultImagePipelineResizeWidth; + } + + public void setDefaultImagePipelineResizeWidth(int defaultImagePipelineResizeWidth) { + this.defaultImagePipelineResizeWidth = defaultImagePipelineResizeWidth; + } + + public int getDefaultImagePipelineResizeHeight() { + return this.defaultImagePipelineResizeHeight; + } + + public void setDefaultImagePipelineResizeHeight(int defaultImagePipelineResizeHeight) { + this.defaultImagePipelineResizeHeight = defaultImagePipelineResizeHeight; + } + + public boolean isDefaultImagePipelineCenterCrop() { + return this.defaultImagePipelineCenterCrop; + } + + public void setDefaultImagePipelineCenterCrop(boolean defaultImagePipelineCenterCrop) { + this.defaultImagePipelineCenterCrop = defaultImagePipelineCenterCrop; + } + + public @NotNull String getSentenceTokenizerMaxLength() { + return this.sentenceTokenizerMaxLength; + } + + public void setSentenceTokenizerMaxLength(@NotNull String sentenceTokenizerMaxLength) { + this.sentenceTokenizerMaxLength = sentenceTokenizerMaxLength; + } + + public @NotNull String getSentenceTokenizerModelMaxLength() { + return this.sentenceTokenizerModelMaxLength; + } + + public void setSentenceTokenizerModelMaxLength(@NotNull String sentenceTokenizerModelMaxLength) { + this.sentenceTokenizerModelMaxLength = sentenceTokenizerModelMaxLength; + } + + public @NotNull String getSentenceTokenizerModel() { + return this.sentenceTokenizerModel; + } + + public void setSentenceTokenizerModel(@NotNull String sentenceTokenizerModel) { + this.sentenceTokenizerModel = sentenceTokenizerModel; + } + + public @NotNull String getFaceDetectionModelEngine() { + return this.faceDetectionModelEngine; + } + + public void setFaceDetectionModelEngine(@NotNull String faceDetectionModelEngine) { + this.faceDetectionModelEngine = faceDetectionModelEngine; + } + + public @NotNull String getFaceDetectionModelName() { + return this.faceDetectionModelName; + } + + public void setFaceDetectionModelName(@NotNull String faceDetectionModelName) { + this.faceDetectionModelName = faceDetectionModelName; + } + + public @NotNull String getFaceDetectionModelModelUrls() { + return this.faceDetectionModelModelUrls; + } + + public void setFaceDetectionModelModelUrls(@NotNull String faceDetectionModelModelUrls) { + this.faceDetectionModelModelUrls = faceDetectionModelModelUrls; + } + + public @NotNull String getFaceEmbeddingModelEngine() { + return this.faceEmbeddingModelEngine; + } + + public void setFaceEmbeddingModelEngine(@NotNull String faceEmbeddingModelEngine) { + this.faceEmbeddingModelEngine = faceEmbeddingModelEngine; + } + + public @NotNull String getFaceEmbeddingModelName() { + return this.faceEmbeddingModelName; + } + + public void setFaceEmbeddingModelName(@NotNull String faceEmbeddingModelName) { + this.faceEmbeddingModelName = faceEmbeddingModelName; + } + + public @NotNull String getFaceEmbeddingModelModelUrls() { + return this.faceEmbeddingModelModelUrls; + } + + public void setFaceEmbeddingModelModelUrls(@NotNull String faceEmbeddingModelModelUrls) { + this.faceEmbeddingModelModelUrls = faceEmbeddingModelModelUrls; + } - public Djl getDjl() { - return djl; + public String toString() { + return "RedisOMSpringProperties.Djl(enabled=" + this.isEnabled() + ", imageEmbeddingModelEngine=" + this.getImageEmbeddingModelEngine() + ", imageEmbeddingModelModelUrls=" + this.getImageEmbeddingModelModelUrls() + ", defaultImagePipelineResizeWidth=" + this.getDefaultImagePipelineResizeWidth() + ", defaultImagePipelineResizeHeight=" + this.getDefaultImagePipelineResizeHeight() + ", defaultImagePipelineCenterCrop=" + this.isDefaultImagePipelineCenterCrop() + ", sentenceTokenizerMaxLength=" + this.getSentenceTokenizerMaxLength() + ", sentenceTokenizerModelMaxLength=" + this.getSentenceTokenizerModelMaxLength() + ", sentenceTokenizerModel=" + this.getSentenceTokenizerModel() + ", faceDetectionModelEngine=" + this.getFaceDetectionModelEngine() + ", faceDetectionModelName=" + this.getFaceDetectionModelName() + ", faceDetectionModelModelUrls=" + this.getFaceDetectionModelModelUrls() + ", faceEmbeddingModelEngine=" + this.getFaceEmbeddingModelEngine() + ", faceEmbeddingModelName=" + this.getFaceEmbeddingModelName() + ", faceEmbeddingModelModelUrls=" + this.getFaceEmbeddingModelModelUrls() + ")"; } + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/RedisRepositoriesExcludeFilter.java b/redis-om-spring/src/main/java/com/redis/om/spring/RedisRepositoriesExcludeFilter.java index 004a48f8..fe0461e8 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/RedisRepositoriesExcludeFilter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/RedisRepositoriesExcludeFilter.java @@ -10,7 +10,7 @@ public class RedisRepositoriesExcludeFilter implements AutoConfigurationImportFilter { private static final Set SHOULD_SKIP = new HashSet<>( - List.of("org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration")); + List.of("org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration")); @Override public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/SentinelConfig.java b/redis-om-spring/src/main/java/com/redis/om/spring/SentinelConfig.java index 455d159e..6422e05f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/SentinelConfig.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/SentinelConfig.java @@ -24,8 +24,7 @@ public JedisConnectionFactory jedisConnectionFactory(Environment env) { Set sentinelNodes = commaDelimitedListToSet(nodes); Set redisNodes = sentinelNodes.stream().map(RedisNode::fromString).collect(Collectors.toSet()); - RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() - .master(master); + RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration().master(master); sentinelConfig.setSentinels(redisNodes); final JedisPoolConfig poolConfig = new JedisPoolConfig(); @@ -38,9 +37,7 @@ public JedisConnectionFactory jedisConnectionFactory(Environment env) { final int timeout = 10000; final JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder() - .connectTimeout(Duration.ofMillis(timeout)) - .readTimeout(Duration.ofMillis(timeout)) - .usePooling() + .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout)).usePooling() .poolConfig(poolConfig).build(); return new JedisConnectionFactory(sentinelConfig, jedisClientConfiguration); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/VectorType.java b/redis-om-spring/src/main/java/com/redis/om/spring/VectorType.java index efa68da2..13c88fba 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/VectorType.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/VectorType.java @@ -1,5 +1,6 @@ package com.redis.om.spring; public enum VectorType { - FLOAT32, FLOAT64 + FLOAT32, + FLOAT64 } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Aggregation.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Aggregation.java index dae8e6f7..2fcff6d3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Aggregation.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Aggregation.java @@ -7,15 +7,24 @@ @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) public @interface Aggregation { String value() default "*"; + boolean verbatim() default false; + Load[] load() default {}; + long timeout() default Long.MIN_VALUE; + Apply[] apply() default {}; + int limit() default Integer.MIN_VALUE; + int offset() default Integer.MIN_VALUE; + String[] filter() default {}; GroupBy[] groupBy() default {}; + SortBy[] sortBy() default {}; + int sortByMax() default Integer.MIN_VALUE; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Apply.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Apply.java index 7a83f3fb..1c442909 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Apply.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Apply.java @@ -9,5 +9,6 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Apply { String expression() default ""; + String alias() default ""; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/AutoCompletePayload.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/AutoCompletePayload.java index 0790afec..ee621362 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/AutoCompletePayload.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/AutoCompletePayload.java @@ -7,5 +7,6 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface AutoCompletePayload { String value() default ""; + String[] fields() default {}; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Bloom.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Bloom.java index ac492ea8..796ccc51 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Bloom.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Bloom.java @@ -7,6 +7,8 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface Bloom { String name() default ""; + double errorRate(); + int capacity(); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Cuckoo.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Cuckoo.java index 2e78b38a..74e6e361 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Cuckoo.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Cuckoo.java @@ -7,8 +7,12 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface Cuckoo { String name() default ""; + int capacity(); + int bucketSize() default 2; + int maxIterations() default 20; + int expansion() default 1; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Document.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Document.java index 35bad1f3..6774909b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Document.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Document.java @@ -14,17 +14,22 @@ @KeySpace public @interface Document { - @AliasFor(annotation = KeySpace.class, attribute = "value") - String value() default ""; + @AliasFor(annotation = KeySpace.class, attribute = "value") String value() default ""; + String indexName() default ""; - + boolean async() default false; + String[] prefixes() default {}; + String filter() default ""; + String languageField() default ""; + SearchLanguage language() default SearchLanguage.ENGLISH; - double score() default 1.0; - + + double score() default 1.0; + /** * Time before expire in seconds. * diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EmbeddingType.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EmbeddingType.java index bfb496cb..2ae240e4 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EmbeddingType.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EmbeddingType.java @@ -1,5 +1,8 @@ package com.redis.om.spring.annotations; public enum EmbeddingType { - IMAGE, SENTENCE, WORD, FACE + IMAGE, + SENTENCE, + WORD, + FACE } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisDocumentRepositories.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisDocumentRepositories.java index e41f7302..9fe638f6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisDocumentRepositories.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisDocumentRepositories.java @@ -35,29 +35,31 @@ * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: * {@code @EnableRedisRepositories("org.my.pkg")} instead of * {@code @EnableRedisRepositories(basePackages="org.my.pkg")}. + * * @return basePackages */ - @AliasFor("basePackages") - String[] value() default {}; + @AliasFor("basePackages") String[] value() default {}; /** * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. + * * @return basePackages as a String */ - @AliasFor("value") - String[] basePackages() default {}; + @AliasFor("value") String[] basePackages() default {}; /** * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in * each package that serves no purpose other than being referenced by this attribute. + * * @return array of base Package Classes */ Class[] basePackageClasses() default {}; /** * Specifies which types are not eligible for component scanning. + * * @return array of components to exclude */ Filter[] excludeFilters() default {}; @@ -66,6 +68,7 @@ * Specifies which types are eligible for component scanning. Further narrows * the set of candidate components from everything in {@link #basePackages()} to * everything in the base packages that matches the given filter or filters. + * * @return array of components to include */ Filter[] includeFilters() default {}; @@ -119,6 +122,7 @@ /** * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the * repositories infrastructure. + * * @return whether to consider nested repositories */ boolean considerNestedRepositories() default false; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisEnhancedRepositories.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisEnhancedRepositories.java index fe0f2e8e..828f8ddf 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisEnhancedRepositories.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/EnableRedisEnhancedRepositories.java @@ -35,29 +35,31 @@ * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: * {@code @EnableRedisRepositories("org.my.pkg")} instead of * {@code @EnableRedisRepositories(basePackages="org.my.pkg")}. + * * @return basePackages */ - @AliasFor("basePackages") - String[] value() default {}; + @AliasFor("basePackages") String[] value() default {}; /** * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. + * * @return basePackages as a String */ - @AliasFor("value") - String[] basePackages() default {}; + @AliasFor("value") String[] basePackages() default {}; /** * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in * each package that serves no purpose other than being referenced by this attribute. + * * @return array of base Package Classes */ Class[] basePackageClasses() default {}; /** * Specifies which types are not eligible for component scanning. + * * @return array of components to exclude */ Filter[] excludeFilters() default {}; @@ -65,6 +67,7 @@ /** * Specifies which types are eligible for component scanning. Narrows the set of candidate components from * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters. + * * @return array of components to include */ Filter[] includeFilters() default {}; @@ -113,11 +116,12 @@ * * @return key value operations template name */ - String keyValueTemplateRef() default "redisCustomKeyValueTemplate"; + String keyValueTemplateRef() default "redisCustomKeyValueTemplate"; /** * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the * repositories infrastructure. + * * @return whether to consider nested repositories */ boolean considerNestedRepositories() default false; @@ -150,7 +154,7 @@ * @since 1.8 */ EnableKeyspaceEvents enableKeyspaceEvents() default EnableKeyspaceEvents.OFF; - + /** * Configure the name of the {@link org.springframework.data.redis.listener.RedisMessageListenerContainer} bean to be * used for keyspace event subscriptions. Defaults to use an anonymous managed instance by diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GeoIndexed.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GeoIndexed.java index 1f22f587..1a106e05 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GeoIndexed.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GeoIndexed.java @@ -7,6 +7,8 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface GeoIndexed { String fieldName() default ""; + String alias() default ""; + boolean noindex() default false; } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GroupBy.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GroupBy.java index 61de24ba..49732c6a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GroupBy.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/GroupBy.java @@ -9,5 +9,6 @@ @Retention(RetentionPolicy.RUNTIME) public @interface GroupBy { String[] properties() default {}; + Reducer[] reduce() default {}; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Load.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Load.java index 7f72c3a0..792f1b3d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Load.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Load.java @@ -9,5 +9,6 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Load { String property() default ""; + String alias() default ""; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/NumericIndexed.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/NumericIndexed.java index fe657a1c..1267a7eb 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/NumericIndexed.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/NumericIndexed.java @@ -7,7 +7,10 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface NumericIndexed { String fieldName() default ""; + String alias() default ""; + boolean sortable() default false; + boolean noindex() default false; } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Query.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Query.java index e9ebd5be..e48de6d4 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Query.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Query.java @@ -7,9 +7,14 @@ @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) public @interface Query { String value() default "*"; + String[] returnFields() default {}; + int offset() default Integer.MIN_VALUE; + int limit() default Integer.MIN_VALUE; + String sortBy() default ""; + boolean sortAscending() default true; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Reducer.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Reducer.java index eb067f85..da9b4a4b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Reducer.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Reducer.java @@ -9,6 +9,8 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Reducer { ReducerFunction func(); + String[] args() default {}; + String alias() default ""; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/SortBy.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/SortBy.java index 4128ea12..8d6994ac 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/SortBy.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/SortBy.java @@ -11,5 +11,6 @@ @Retention(RetentionPolicy.RUNTIME) public @interface SortBy { String field(); + Direction direction() default Direction.ASC; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TagIndexed.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TagIndexed.java index bb178b65..27c03d72 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TagIndexed.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TagIndexed.java @@ -7,7 +7,10 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface TagIndexed { String fieldName() default ""; + String alias() default ""; + boolean noindex() default false; + String separator() default "|"; } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TextIndexed.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TextIndexed.java index af0e757e..dddef83f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TextIndexed.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/TextIndexed.java @@ -7,10 +7,16 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface TextIndexed { String fieldName() default ""; + String alias() default ""; + boolean sortable() default false; + boolean noindex() default false; + double weight() default 1.0; + boolean nostem() default false; + String phonetic() default ""; } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Vectorize.java b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Vectorize.java index 1a4a8692..7ce6dde9 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Vectorize.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/annotations/Vectorize.java @@ -7,5 +7,6 @@ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) public @interface Vectorize { String destination(); + EmbeddingType embeddingType() default EmbeddingType.SENTENCE; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/audit/EntityAuditor.java b/redis-om-spring/src/main/java/com/redis/om/spring/audit/EntityAuditor.java index 265f1d44..f3247871 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/audit/EntityAuditor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/audit/EntityAuditor.java @@ -21,9 +21,9 @@ public EntityAuditor(RedisOperations redisOperations) { } public void processEntity(byte[] redisKey, Object item) { - boolean isNew = (boolean) redisOperations - .execute((RedisCallback) connection -> !connection.keyCommands().exists(redisKey)); - processEntity(item, isNew); + boolean isNew = (boolean) redisOperations.execute( + (RedisCallback) connection -> !connection.keyCommands().exists(redisKey)); + processEntity(item, isNew); } public void processEntity(String redisKey, Object item) { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/autocomplete/AutoCompleteAspect.java b/redis-om-spring/src/main/java/com/redis/om/spring/autocomplete/AutoCompleteAspect.java index 53e625e1..e059136c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/autocomplete/AutoCompleteAspect.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/autocomplete/AutoCompleteAspect.java @@ -30,11 +30,8 @@ @Component public class AutoCompleteAspect implements Ordered { private static final Log logger = LogFactory.getLog(AutoCompleteAspect.class); - - private final Gson gson; - final StringRedisTemplate template; - + private final Gson gson; private final RedisModulesOperations rmo; public AutoCompleteAspect(RedisModulesOperations rmo, Gson gson, StringRedisTemplate template) { @@ -117,11 +114,13 @@ public void deleteAllSuggestionsFromEntities(JoinPoint jp, List entities for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(AutoComplete.class)) { AutoComplete suggestible = field.getAnnotation(AutoComplete.class); - String key = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); + String key = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); - String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format(Suggestion.PAYLOAD_KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); + String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format(Suggestion.PAYLOAD_KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); @@ -129,8 +128,8 @@ public void deleteAllSuggestionsFromEntities(JoinPoint jp, List entities String suggestion = pd.getReadMethod().invoke(entity).toString(); ops.deleteSuggestion(key, suggestion); template.opsForHash().delete(payLoadKey, suggestion); - } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException - | InvocationTargetException e) { + } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException | + InvocationTargetException e) { logger.error("Error while deleting suggestions...", e); } } @@ -177,45 +176,48 @@ public int getOrder() { } private void processSuggestionsForEntity(Object entity) { - final List entityClassFields = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass()); + final List entityClassFields = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively( + entity.getClass()); for (Field field : entityClassFields) { if (field.isAnnotationPresent(AutoComplete.class)) { String suggestion = ""; Map payload = null; AutoComplete suggestible = field.getAnnotation(AutoComplete.class); - String key = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); + String key = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); SearchOperations ops = rmo.opsForSearch(key); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); suggestion = pd.getReadMethod().invoke(entity).toString(); - } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException - | InvocationTargetException e) { + } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException | + InvocationTargetException e) { logger.error("Error while processing suggestions...", e); } for (Field field2 : entityClassFields) { if (field2.isAnnotationPresent(AutoCompletePayload.class)) { AutoCompletePayload suggestiblePayload = field2.getAnnotation(AutoCompletePayload.class); - boolean inPayload = (!suggestiblePayload.value().isBlank() - && suggestiblePayload.value().equalsIgnoreCase(field.getName())) - || (Arrays.asList(suggestiblePayload.fields()).contains(field.getName())); + boolean inPayload = (!suggestiblePayload.value().isBlank() && suggestiblePayload.value() + .equalsIgnoreCase(field.getName())) || (Arrays.asList(suggestiblePayload.fields()) + .contains(field.getName())); if (inPayload) { try { payload = payload == null ? new HashMap<>() : payload; PropertyDescriptor pd = new PropertyDescriptor(field2.getName(), entity.getClass()); payload.put(field2.getName(), pd.getReadMethod().invoke(entity)); - } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException - | InvocationTargetException e) { + } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException | + InvocationTargetException e) { logger.error("Error while processing suggestions...", e); } } } } if (payload != null && !payload.isEmpty()) { - String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format(Suggestion.PAYLOAD_KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); + String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format(Suggestion.PAYLOAD_KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); template.opsForHash().put(payLoadKey, suggestion, gson.toJson(payload)); } @@ -228,8 +230,9 @@ private void deleteSuggestionsForEntity(Object entity) { for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(AutoComplete.class)) { AutoComplete suggestible = field.getAnnotation(AutoComplete.class); - String key = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); + String key = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format(Suggestion.KEY_FORMAT_STRING, entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); SearchOperations ops = rmo.opsForSearch(key); @@ -238,11 +241,12 @@ private void deleteSuggestionsForEntity(Object entity) { ops.deleteSuggestion(key, suggestion); - String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? suggestible.name() - : String.format("sugg:payload:%s:%s", entity.getClass().getSimpleName(), field.getName()); + String payLoadKey = !ObjectUtils.isEmpty(suggestible.name()) ? + suggestible.name() : + String.format("sugg:payload:%s:%s", entity.getClass().getSimpleName(), field.getName()); template.opsForHash().delete(payLoadKey, suggestion); - } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException - | InvocationTargetException e) { + } catch (IllegalArgumentException | IntrospectionException | IllegalAccessException | + InvocationTargetException e) { logger.error("Error while deleting suggestions...", e); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/bloom/BloomAspect.java b/redis-om-spring/src/main/java/com/redis/om/spring/bloom/BloomAspect.java index acf84e42..c7db5867 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/bloom/BloomAspect.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/bloom/BloomAspect.java @@ -21,32 +21,38 @@ @Aspect @Component public class BloomAspect implements Ordered { - private final BloomOperations ops; private static final Log logger = LogFactory.getLog(BloomAspect.class); + private final BloomOperations ops; public BloomAspect(BloomOperations ops) { this.ops = ops; } @Pointcut("execution(public * org.springframework.data.repository.CrudRepository+.save(..))") - public void inCrudRepositorySave() {} + public void inCrudRepositorySave() { + } @Pointcut("execution(public * com.redis.om.spring.repository.RedisDocumentRepository+.save(..))") - public void inRedisDocumentRepositorySave() {} + public void inRedisDocumentRepositorySave() { + } @Pointcut("inCrudRepositorySave() || inRedisDocumentRepositorySave()") - private void inSaveOperation() {} + private void inSaveOperation() { + } @AfterReturning("inSaveOperation() && args(entity,..)") public void addToBloom(JoinPoint jp, Object entity) { for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(Bloom.class)) { Bloom bloom = field.getAnnotation(Bloom.class); - String filterName = !ObjectUtils.isEmpty(bloom.name()) ? bloom.name() : String.format("bf:%s:%s", entity.getClass().getSimpleName(), field.getName()); + String filterName = !ObjectUtils.isEmpty(bloom.name()) ? + bloom.name() : + String.format("bf:%s:%s", entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); ops.add(filterName, pd.getReadMethod().invoke(entity).toString()); - } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | InvocationTargetException e) { + } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | + InvocationTargetException e) { logger.error(String.format("Could not add value to Bloom filter %s", filterName), e); } } @@ -54,13 +60,16 @@ public void addToBloom(JoinPoint jp, Object entity) { } @Pointcut("execution(public * org.springframework.data.repository.CrudRepository+.saveAll(..))") - public void inCrudRepositorySaveAll() {} + public void inCrudRepositorySaveAll() { + } @Pointcut("execution(public * com.redis.om.spring.repository.RedisDocumentRepository+.saveAll(..))") - public void inRedisDocumentRepositorySaveAll() {} + public void inRedisDocumentRepositorySaveAll() { + } @Pointcut("inCrudRepositorySaveAll() || inRedisDocumentRepositorySaveAll()") - private void inSaveAllOperation() {} + private void inSaveAllOperation() { + } @AfterReturning("inSaveAllOperation() && args(entities,..)") public void addAllToBloom(JoinPoint jp, List entities) { @@ -68,11 +77,14 @@ public void addAllToBloom(JoinPoint jp, List entities) { for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(Bloom.class)) { Bloom bloom = field.getAnnotation(Bloom.class); - String filterName = !ObjectUtils.isEmpty(bloom.name()) ? bloom.name() : String.format("bf:%s:%s", entity.getClass().getSimpleName(), field.getName()); + String filterName = !ObjectUtils.isEmpty(bloom.name()) ? + bloom.name() : + String.format("bf:%s:%s", entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); ops.add(filterName, pd.getReadMethod().invoke(entity).toString()); - } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | InvocationTargetException e) { + } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | + InvocationTargetException e) { logger.error(String.format("Could not add values to Bloom filter %s", filterName), e); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/client/RedisModulesClient.java b/redis-om-spring/src/main/java/com/redis/om/spring/client/RedisModulesClient.java index 17c6014f..b5575d10 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/client/RedisModulesClient.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/client/RedisModulesClient.java @@ -25,6 +25,7 @@ public class RedisModulesClient { private static final Log logger = LogFactory.getLog(RedisModulesClient.class); private final GsonBuilder builder; private final UnifiedJedis unifiedJedis; + private final JedisConnectionFactory jedisConnectionFactory; public RedisModulesClient(JedisConnectionFactory jedisConnectionFactory, GsonBuilder builder) { this.jedisConnectionFactory = jedisConnectionFactory; @@ -70,17 +71,15 @@ private UnifiedJedis getUnifiedJedis() { // var masterNode = sentinelConfiguration.getMaster(); var master = masterNode != null ? masterNode.getName() : "mymaster"; - var sentinels = sentinelConfiguration.getSentinels().stream() - .map(RedisModulesClient::apply).collect(Collectors.toSet()); + var sentinels = sentinelConfiguration.getSentinels().stream().map(RedisModulesClient::apply) + .collect(Collectors.toSet()); var password = sentinelConfiguration.getPassword(); var sentinelPassword = sentinelConfiguration.getSentinelPassword(); var username = sentinelConfiguration.getUsername(); - var masterClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), - username, - password, jedisConnectionFactory.getClientConfiguration()); - var sentinelClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), - username, - sentinelPassword, jedisConnectionFactory.getClientConfiguration()); + var masterClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), username, password, + jedisConnectionFactory.getClientConfiguration()); + var sentinelClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), username, sentinelPassword, + jedisConnectionFactory.getClientConfiguration()); logger.info("Modules Client connecting in Sentinel mode, master: " + master); return new JedisSentineled(master, masterClientConfig, sentinels, sentinelClientConfig); @@ -94,9 +93,7 @@ private UnifiedJedis getUnifiedJedis() { var standaloneConfig = jedisConnectionFactory.getStandaloneConfiguration(); var username = standaloneConfig != null ? standaloneConfig.getUsername() : null; var password = standaloneConfig != null ? standaloneConfig.getPassword() : null; - var jedisClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), - username, - password, cc); + var jedisClientConfig = createClientConfig(jedisConnectionFactory.getDatabase(), username, password, cc); logger.info("Modules Client connecting with standalone pool"); @@ -113,7 +110,7 @@ public Optional getJedis() { return Optional.empty(); } } - + public Optional getJedisCluster() { Object nativeConnection = jedisConnectionFactory.getConnection().getNativeConnection(); if (nativeConnection instanceof JedisCluster jedisCluster) { @@ -127,9 +124,8 @@ public GsonBuilder gsonBuilder() { return builder; } - private final JedisConnectionFactory jedisConnectionFactory; - - private JedisClientConfig createClientConfig(int database, @Nullable String username, RedisPassword password, JedisClientConfiguration clientConfiguration) { + private JedisClientConfig createClientConfig(int database, @Nullable String username, RedisPassword password, + JedisClientConfiguration clientConfiguration) { DefaultJedisClientConfig.Builder jedisConfigBuilder = DefaultJedisClientConfig.builder(); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/BooleanToBytesConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/BooleanToBytesConverter.java index 5f655bd8..7d9eec33 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/BooleanToBytesConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/BooleanToBytesConverter.java @@ -9,13 +9,13 @@ @Component @WritingConverter public class BooleanToBytesConverter implements Converter { + private final byte[] trueAsBytes = fromString("true"); + private final byte[] falseAsBytes = fromString("false"); + byte[] fromString(String source) { return source.getBytes(StandardCharsets.UTF_8); } - private final byte[] trueAsBytes = fromString("true"); - private final byte[] falseAsBytes = fromString("false"); - @Override public byte[] convert(Boolean source) { return Boolean.TRUE.equals(source) ? trueAsBytes : falseAsBytes; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/BytesToOffsetDateTimeConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/BytesToOffsetDateTimeConverter.java index 82a6d3f8..76b61365 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/BytesToOffsetDateTimeConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/BytesToOffsetDateTimeConverter.java @@ -15,6 +15,7 @@ public class BytesToOffsetDateTimeConverter implements Converter listKeyComparator = Comparator.nullsLast(NaturalOrderingKeyComparator.INSTANCE); - + private final ProjectionFactory projectionFactory; private @Nullable ReferenceResolver referenceResolver; private CustomConversions customConversions; - private final ProjectionFactory projectionFactory; public MappingRedisOMConverter() { this(null); @@ -75,7 +74,7 @@ public MappingRedisOMConverter(RedisMappingContext context) { * @param referenceResolver can be not be {@literal null}. */ public MappingRedisOMConverter(@Nullable RedisMappingContext mappingContext, - @Nullable ReferenceResolver referenceResolver) { + @Nullable ReferenceResolver referenceResolver) { this(mappingContext, referenceResolver, null); } @@ -88,20 +87,29 @@ public MappingRedisOMConverter(@Nullable RedisMappingContext mappingContext, * @param typeMapper can be {@literal null}. */ public MappingRedisOMConverter(@Nullable RedisMappingContext mappingContext, - @Nullable ReferenceResolver referenceResolver, @Nullable RedisTypeMapper typeMapper) { + @Nullable ReferenceResolver referenceResolver, @Nullable RedisTypeMapper typeMapper) { this.mappingContext = mappingContext != null ? mappingContext : new RedisMappingContext(); this.entityInstantiators = new EntityInstantiators(); this.conversionService = new DefaultConversionService(); this.customConversions = new RedisOMCustomConversions(); - this.typeMapper = typeMapper != null ? typeMapper - : new DefaultRedisTypeMapper(DefaultRedisTypeMapper.DEFAULT_TYPE_KEY, this.mappingContext); + this.typeMapper = typeMapper != null ? + typeMapper : + new DefaultRedisTypeMapper(DefaultRedisTypeMapper.DEFAULT_TYPE_KEY, this.mappingContext); this.projectionFactory = new SpelAwareProxyProjectionFactory(); this.referenceResolver = referenceResolver; afterPropertiesSet(); } + private static boolean isByteArray(RedisPersistentProperty property) { + return !property.getType().equals(byte[].class); + } + + private static boolean isByteArray(TypeInformation type) { + return type.getType().equals(byte[].class); + } + /* (non-Javadoc) * * @see org.springframework.data.convert.EntityReader#read(java.lang.Class, @@ -116,8 +124,8 @@ public R read(Class type, RedisData source) { } // if (type.isInterface()) { -// return (R) projectionFactory.createProjection(type, result); -// } + // return (R) projectionFactory.createProjection(type, result); + // } return readInternal(type, "", type, source); } @@ -155,7 +163,8 @@ private R doReadInternal(Class entityClass, String path, Class type, R } if (conversionService.canConvert(byte[].class, readType.getType())) { - return (R) conversionService.convert(source.getBucket().get(StringUtils.hasText(path) ? path : "_raw"), readType.getType()); + return (R) conversionService.convert(source.getBucket().get(StringUtils.hasText(path) ? path : "_raw"), + readType.getType()); } RedisPersistentEntity entity = mappingContext.getRequiredPersistentEntity(readType); @@ -208,9 +217,10 @@ private R doReadInternal(Class entityClass, String path, Class type, R return (R) instance; } + @Nullable protected Object readProperty(Class entityClass, String path, RedisData source, - RedisPersistentProperty persistentProperty) { + RedisPersistentProperty persistentProperty) { String currentPath = !path.isEmpty() ? path + "." + persistentProperty.getName() : persistentProperty.getName(); @@ -226,29 +236,29 @@ protected Object readProperty(Class entityClass, String path, RedisData sourc if (conversionService.canConvert(byte[].class, mapValueType)) { return readMapOfSimpleTypes(currentPath, typeInformation.getType(), - typeInformation.getRequiredComponentType().getType(), mapValueType, source); + typeInformation.getRequiredComponentType().getType(), mapValueType, source); } return readMapOfComplexTypes(entityClass, currentPath, typeInformation.getType(), - typeInformation.getRequiredComponentType().getType(), mapValueType, source); + typeInformation.getRequiredComponentType().getType(), mapValueType, source); } if (typeInformation.isCollectionLike()) { if (!isByteArray(typeInformation)) { return readCollectionOrArray(entityClass, currentPath, typeInformation.getType(), - typeInformation.getRequiredComponentType().getType(), source.getBucket()); + typeInformation.getRequiredComponentType().getType(), source.getBucket()); } if (!source.getBucket().hasValue(currentPath) && isByteArray(typeInformation)) { return readCollectionOrArray(entityClass, currentPath, typeInformation.getType(), - typeInformation.getRequiredComponentType().getType(), source.getBucket()); + typeInformation.getRequiredComponentType().getType(), source.getBucket()); } } - if (persistentProperty.isEntity() - && !conversionService.canConvert(byte[].class, typeInformation.getRequiredActualType().getType())) { + if (persistentProperty.isEntity() && !conversionService.canConvert(byte[].class, + typeInformation.getRequiredActualType().getType())) { Bucket bucket = source.getBucket().extract(currentPath + "."); @@ -281,19 +291,20 @@ protected Object readProperty(Class entityClass, String path, RedisData sourc } private void readAssociation(String path, RedisData source, RedisPersistentEntity entity, - PersistentPropertyAccessor accessor) { + PersistentPropertyAccessor accessor) { entity.doWithAssociations((AssociationHandler) association -> { - String currentPath = !path.isEmpty() ? path + "." + association.getInverse().getName() - : association.getInverse().getName(); + String currentPath = !path.isEmpty() ? + path + "." + association.getInverse().getName() : + association.getInverse().getName(); if (association.getInverse().isCollectionLike()) { Bucket bucket = source.getBucket().extract(currentPath + ".["); Collection target = CollectionFactory.createCollection(association.getInverse().getType(), - association.getInverse().getComponentType(), bucket.size()); + association.getInverse().getComponentType(), bucket.size()); for (Entry entry : bucket.entrySet()) { @@ -305,7 +316,7 @@ private void readAssociation(String path, RedisData source, RedisPersistentEntit KeyspaceIdentifier identifier = KeyspaceIdentifier.of(referenceKey); Map rawHash = referenceResolver.resolveReference(identifier.getId(), - identifier.getKeyspace()); + identifier.getKeyspace()); if (!CollectionUtils.isEmpty(rawHash)) { target.add(read(association.getInverse().getActualType(), new RedisData(rawHash))); @@ -327,11 +338,11 @@ private void readAssociation(String path, RedisData source, RedisPersistentEntit KeyspaceIdentifier identifier = KeyspaceIdentifier.of(referenceKey); Map rawHash = referenceResolver.resolveReference(identifier.getId(), - identifier.getKeyspace()); + identifier.getKeyspace()); if (!CollectionUtils.isEmpty(rawHash)) { accessor.setProperty(association.getInverse(), - read(association.getInverse().getActualType(), new RedisData(rawHash))); + read(association.getInverse().getActualType(), new RedisData(rawHash))); } } } @@ -343,9 +354,10 @@ private void readAssociation(String path, RedisData source, RedisPersistentEntit * @see org.springframework.data.convert.EntityWriter#write(java.lang.Object, * java.lang.Object) */ @Override - @SuppressWarnings({ "rawtypes", "ConstantValue" }) + @SuppressWarnings({ "ConstantValue" }) public void write(Object source, RedisData sink) { - if (source == null) return; + if (source == null) + return; if (source instanceof PartialUpdate pu) { writePartialUpdate(pu, sink); @@ -372,7 +384,7 @@ private void writeEntity(RedisPersistentEntity entity, Object source, RedisDa if (entity.getTypeInformation().isCollectionLike()) { writeCollection(entity.getType(), entity.getKeySpace(), "", (List) source, - entity.getTypeInformation().getRequiredComponentType(), sink); + entity.getTypeInformation().getRequiredComponentType(), sink); } else { writeInternal(entity.getKeySpace(), "", source, entity.getTypeInformation(), sink); } @@ -428,7 +440,7 @@ protected void writePartialUpdate(PartialUpdate update, RedisData sink) { * @param path */ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate pUpdate, RedisData sink, - RedisPersistentEntity entity, String path) { + RedisPersistentEntity entity, String path) { RedisPersistentProperty targetProperty = getTargetPropertyOrNullForPath(path, update.getTarget()); @@ -436,10 +448,13 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate targetProperty = getTargetPropertyOrNullForPath(path.replaceAll("\\.\\[.*]", ""), update.getTarget()); - TypeInformation ti = targetProperty == null ? TypeInformation.OBJECT - : (targetProperty.isMap() ? (targetProperty.getTypeInformation().getMapValueType() != null - ? targetProperty.getTypeInformation().getRequiredMapValueType() - : TypeInformation.OBJECT) : targetProperty.getTypeInformation().getActualType()); + TypeInformation ti = targetProperty == null ? + TypeInformation.OBJECT : + (targetProperty.isMap() ? + (targetProperty.getTypeInformation().getMapValueType() != null ? + targetProperty.getTypeInformation().getRequiredMapValueType() : + TypeInformation.OBJECT) : + targetProperty.getTypeInformation().getActualType()); writeInternal(entity.getKeySpace(), pUpdate.getPropertyPath(), pUpdate.getValue(), ti, sink); return; @@ -449,8 +464,9 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate if (targetProperty.isCollectionLike()) { - RedisPersistentEntity ref = mappingContext.getPersistentEntity(targetProperty.getRequiredAssociation() - .getInverse().getTypeInformation().getRequiredComponentType().getRequiredActualType()); + RedisPersistentEntity ref = mappingContext.getPersistentEntity( + targetProperty.getRequiredAssociation().getInverse().getTypeInformation().getRequiredComponentType() + .getRequiredActualType()); int i = 0; for (Object o : (Collection) pUpdate.getValue()) { @@ -463,8 +479,8 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate } } else { - RedisPersistentEntity ref = mappingContext - .getRequiredPersistentEntity(targetProperty.getRequiredAssociation().getInverse().getTypeInformation()); + RedisPersistentEntity ref = mappingContext.getRequiredPersistentEntity( + targetProperty.getRequiredAssociation().getInverse().getTypeInformation()); Object refId = ref.getPropertyAccessor(pUpdate.getValue()).getProperty(ref.getRequiredIdProperty()); if (refId != null) { @@ -473,10 +489,11 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate } } else if (targetProperty.isCollectionLike() && isByteArray(targetProperty)) { - Collection collection = pUpdate.getValue() instanceof Collection ? (Collection) pUpdate.getValue() - : Collections.singleton(pUpdate.getValue()); + Collection collection = pUpdate.getValue() instanceof Collection ? + (Collection) pUpdate.getValue() : + Collections.singleton(pUpdate.getValue()); writeCollection(entity.getType(), entity.getKeySpace(), pUpdate.getPropertyPath(), collection, - targetProperty.getTypeInformation().getRequiredActualType(), sink); + targetProperty.getTypeInformation().getRequiredActualType(), sink); } else if (targetProperty.isMap()) { Map map = new HashMap<>(); @@ -487,16 +504,16 @@ private void writePartialPropertyUpdate(PartialUpdate update, PropertyUpdate map.put(((Entry) pUpdate.getValue()).getKey(), ((Entry) pUpdate.getValue()).getValue()); } else { throw new MappingException( - String.format("Cannot set update value for map property '%s' to '%s'. Please use a Map or Map.Entry.", - pUpdate.getPropertyPath(), pUpdate.getValue())); + String.format("Cannot set update value for map property '%s' to '%s'. Please use a Map or Map.Entry.", + pUpdate.getPropertyPath(), pUpdate.getValue())); } writeMap(entity.getType(), entity.getKeySpace(), pUpdate.getPropertyPath(), targetProperty.getMapValueType(), map, - sink); + sink); } else { writeInternal(entity.getKeySpace(), pUpdate.getPropertyPath(), pUpdate.getValue(), - targetProperty.getTypeInformation(), sink); + targetProperty.getTypeInformation(), sink); } } @@ -505,8 +522,8 @@ RedisPersistentProperty getTargetPropertyOrNullForPath(String path, Class typ try { - PersistentPropertyPath persistentPropertyPath = mappingContext - .getPersistentPropertyPath(path, type); + PersistentPropertyPath persistentPropertyPath = mappingContext.getPersistentPropertyPath( + path, type); return persistentPropertyPath.getLeafProperty(); } catch (Exception e) { // that's just fine @@ -523,7 +540,7 @@ RedisPersistentProperty getTargetPropertyOrNullForPath(String path, Class typ * @param sink */ private void writeInternal(@Nullable String keyspace, String path, @Nullable Object value, - TypeInformation typeHint, RedisData sink) { + TypeInformation typeHint, RedisData sink) { if (value == null) { return; @@ -533,14 +550,14 @@ private void writeInternal(@Nullable String keyspace, String path, @Nullable Obj Optional> targetType = customConversions.getCustomWriteTarget(value.getClass()); - if (!StringUtils.hasText(path) && targetType.isPresent() - && ClassUtils.isAssignable(byte[].class, targetType.get())) { + if (!StringUtils.hasText(path) && targetType.isPresent() && ClassUtils.isAssignable(byte[].class, + targetType.get())) { sink.getBucket().put(StringUtils.hasText(path) ? path : "_raw", conversionService.convert(value, byte[].class)); } else { if (!ClassUtils.isAssignable(typeHint.getType(), value.getClass())) { throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), path, typeHint.getType())); + String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), path, typeHint.getType())); } writeToBucket(path, value, sink, typeHint.getType()); } @@ -576,23 +593,23 @@ private void writeInternal(@Nullable String keyspace, String path, @Nullable Obj if (propertyValue != null) { writeMap(entity.getType(), keyspace, propertyStringPath, persistentProperty.getMapValueType(), - (Map) propertyValue, sink); + (Map) propertyValue, sink); } } else if (persistentProperty.isCollectionLike() && isByteArray(persistentProperty)) { if (propertyValue == null) { writeCollection(entity.getType(), keyspace, propertyStringPath, null, - persistentProperty.getTypeInformation().getRequiredComponentType(), sink); + persistentProperty.getTypeInformation().getRequiredComponentType(), sink); } else { if (Iterable.class.isAssignableFrom(propertyValue.getClass())) { writeCollection(entity.getType(), keyspace, propertyStringPath, (Iterable) propertyValue, - persistentProperty.getTypeInformation().getRequiredComponentType(), sink); + persistentProperty.getTypeInformation().getRequiredComponentType(), sink); } else if (propertyValue.getClass().isArray()) { writeCollection(entity.getType(), keyspace, propertyStringPath, CollectionUtils.arrayToList(propertyValue), - persistentProperty.getTypeInformation().getRequiredComponentType(), sink); + persistentProperty.getTypeInformation().getRequiredComponentType(), sink); } else { throw new RuntimeException("Don't know how to handle " + propertyValue.getClass() + " type collection"); @@ -603,7 +620,7 @@ private void writeInternal(@Nullable String keyspace, String path, @Nullable Obj if (propertyValue != null) { writeInternal(keyspace, propertyStringPath, propertyValue, - persistentProperty.getTypeInformation().getRequiredActualType(), sink); + persistentProperty.getTypeInformation().getRequiredActualType(), sink); } } else { @@ -634,7 +651,7 @@ private void writeAssociation(String path, RedisPersistentEntity entity, @Nul if (association.getInverse().isCollectionLike()) { RedisPersistentEntity ref = mappingContext.getRequiredPersistentEntity( - association.getInverse().getTypeInformation().getRequiredComponentType().getRequiredActualType()); + association.getInverse().getTypeInformation().getRequiredComponentType().getRequiredActualType()); String keyspace = ref.getKeySpace(); String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName(); @@ -651,8 +668,8 @@ private void writeAssociation(String path, RedisPersistentEntity entity, @Nul } else { - RedisPersistentEntity ref = mappingContext - .getRequiredPersistentEntity(association.getInverse().getTypeInformation()); + RedisPersistentEntity ref = mappingContext.getRequiredPersistentEntity( + association.getInverse().getTypeInformation()); String keyspace = ref.getKeySpace(); if (keyspace != null) { @@ -676,7 +693,7 @@ private void writeAssociation(String path, RedisPersistentEntity entity, @Nul * @param sink */ private void writeCollection(Class entityClass, @Nullable String keyspace, String path, - @Nullable Iterable values, TypeInformation typeHint, RedisData sink) { + @Nullable Iterable values, TypeInformation typeHint, RedisData sink) { if (values == null) { return; @@ -701,12 +718,11 @@ private void writeCollection(Class entityClass, @Nullable String keyspace, St // it's ok, move on! } - if ((field != null) && (collectionElementType != null) && (indexed != null || tagIndexed != null) - && CharSequence.class.isAssignableFrom(collectionElementType)) { - @SuppressWarnings("null") - String separator = indexed != null ? indexed.separator() : tagIndexed.separator(); + if ((field != null) && (collectionElementType != null) && (indexed != null || tagIndexed != null) && CharSequence.class.isAssignableFrom( + collectionElementType)) { + @SuppressWarnings("null") String separator = indexed != null ? indexed.separator() : tagIndexed.separator(); String value = StreamSupport.stream(values.spliterator(), false).map(Object::toString).map(QueryUtils::escape) - .collect(Collectors.joining(separator)); + .collect(Collectors.joining(separator)); writeInternal(keyspace, path, value, typeHint, sink); } else { int i = 0; @@ -720,7 +736,7 @@ private void writeCollection(Class entityClass, @Nullable String keyspace, St if (!ClassUtils.isAssignable(typeHint.getType(), value.getClass())) { throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), currentPath, typeHint.getType())); + String.format(INVALID_TYPE_ASSIGNMENT, value.getClass(), currentPath, typeHint.getType())); } if (customConversions.hasCustomWriteTarget(value.getClass())) { @@ -748,8 +764,8 @@ private void writeToBucket(String path, @Nullable Object value, RedisData sink, Optional> targetType = customConversions.getCustomWriteTarget(value.getClass()); - if (!propertyType.isPrimitive() && targetType.filter(it -> ClassUtils.isAssignable(Map.class, it)).isEmpty() - && customConversions.isSimpleType(value.getClass()) && value.getClass() != propertyType) { + if (!propertyType.isPrimitive() && targetType.filter(it -> ClassUtils.isAssignable(Map.class, it)) + .isEmpty() && customConversions.isSimpleType(value.getClass()) && value.getClass() != propertyType) { typeMapper.writeType(value.getClass(), sink.getBucket().getPropertyPath(path)); } @@ -757,21 +773,21 @@ private void writeToBucket(String path, @Nullable Object value, RedisData sink, Map map = (Map) conversionService.convert(value, targetType.get()); for (Map.Entry entry : map.entrySet()) { - sink.getBucket().put(path + (StringUtils.hasText(path) ? "." : "") + entry.getKey(), - toBytes(entry.getValue())); + sink.getBucket() + .put(path + (StringUtils.hasText(path) ? "." : "") + entry.getKey(), toBytes(entry.getValue())); } } else if (targetType.filter(it -> ClassUtils.isAssignable(byte[].class, it)).isPresent()) { sink.getBucket().put(path, toBytes(value)); } else { throw new IllegalArgumentException( - String.format("Cannot convert value '%s' of type %s to bytes.", value, value.getClass())); + String.format("Cannot convert value '%s' of type %s to bytes.", value, value.getClass())); } } } @Nullable private Object readCollectionOrArray(Class entityClass, String path, Class collectionType, Class valueType, - Bucket bucket) { + Bucket bucket) { Field field = null; Class collectionElementType = null; Indexed indexed = null; @@ -779,7 +795,8 @@ private Object readCollectionOrArray(Class entityClass, String path, Class try { field = ReflectionUtils.findField(entityClass, path); if (field != null) { - Optional> maybeCollectionElementType = com.redis.om.spring.util.ObjectUtils.getCollectionElementClass(field); + Optional> maybeCollectionElementType = com.redis.om.spring.util.ObjectUtils.getCollectionElementClass( + field); collectionElementType = maybeCollectionElementType.orElse(null); if (field.isAnnotationPresent(Indexed.class)) { indexed = field.getAnnotation(Indexed.class); @@ -794,13 +811,12 @@ private Object readCollectionOrArray(Class entityClass, String path, Class Collection target; boolean isArray = collectionType.isArray(); - if ((field != null) && (indexed != null || tagIndexed != null) - && (collectionElementType != null && CharSequence.class.isAssignableFrom(collectionElementType))) { - @SuppressWarnings("null") - String separator = indexed != null ? indexed.separator() : tagIndexed.separator(); + if ((field != null) && (indexed != null || tagIndexed != null) && (collectionElementType != null && CharSequence.class.isAssignableFrom( + collectionElementType))) { + @SuppressWarnings("null") String separator = indexed != null ? indexed.separator() : tagIndexed.separator(); Bucket elementData = bucket.extract(path); TypeInformation typeInformation = typeMapper.readType(elementData.getPropertyPath(path), - TypeInformation.of(valueType)); + TypeInformation.of(valueType)); Class collectionTypeToUse = isArray ? ArrayList.class : collectionType; Class typeToUse = typeInformation.getType(); String collectionAsString; @@ -812,8 +828,8 @@ private Object readCollectionOrArray(Class entityClass, String path, Class if (collectionAsString == null) { collectionAsString = ""; } - @SuppressWarnings("Annotator") List values = Arrays.stream(collectionAsString.split("\\" + separator)).map(QueryUtils::unescape) - .toList(); + @SuppressWarnings("Annotator") List values = Arrays.stream(collectionAsString.split("\\" + separator)) + .map(QueryUtils::unescape).toList(); target = CollectionFactory.createCollection(collectionTypeToUse, valueType, values.size()); target.addAll(values); } else { @@ -832,7 +848,7 @@ private Object readCollectionOrArray(Class entityClass, String path, Class Bucket elementData = bucket.extract(key); TypeInformation typeInformation = typeMapper.readType(elementData.getPropertyPath(key), - TypeInformation.of(valueType)); + TypeInformation.of(valueType)); Class typeToUse = typeInformation.getType(); if (conversionService.canConvert(byte[].class, typeToUse)) { @@ -854,7 +870,7 @@ private Object readCollectionOrArray(Class entityClass, String path, Class * @param sink */ private void writeMap(Class entityClass, @Nullable String keyspace, String path, Class mapValueType, - Map source, RedisData sink) { + Map source, RedisData sink) { if (CollectionUtils.isEmpty(source)) { return; @@ -870,14 +886,13 @@ private void writeMap(Class entityClass, @Nullable String keyspace, String pa if (!ClassUtils.isAssignable(mapValueType, entry.getValue().getClass())) { throw new MappingException( - String.format(INVALID_TYPE_ASSIGNMENT, entry.getValue().getClass(), currentPath, mapValueType)); + String.format(INVALID_TYPE_ASSIGNMENT, entry.getValue().getClass(), currentPath, mapValueType)); } if (customConversions.hasCustomWriteTarget(entry.getValue().getClass())) { writeToBucket(currentPath, entry.getValue(), sink, mapValueType); } else { - writeInternal(keyspace, currentPath, entry.getValue(), TypeInformation.of(mapValueType), - sink); + writeInternal(keyspace, currentPath, entry.getValue(), TypeInformation.of(mapValueType), sink); } } } @@ -901,7 +916,7 @@ private String mapMapKey(Object key) { */ @Nullable private Map readMapOfSimpleTypes(String path, Class mapType, Class keyType, Class valueType, - RedisData source) { + RedisData source) { Bucket partial = source.getBucket().extract(path + ".["); @@ -931,7 +946,7 @@ private String mapMapKey(Object key) { */ @Nullable private Map readMapOfComplexTypes(Class entityClass, String path, Class mapType, Class keyType, - Class valueType, RedisData source) { + Class valueType, RedisData source) { Set keys = source.getBucket().extractAllKeysFor(path); @@ -944,7 +959,7 @@ private String mapMapKey(Object key) { Object mapKey = extractMapKeyForPath(path, key, keyType); TypeInformation typeInformation = typeMapper.readType(source.getBucket().getPropertyPath(key), - TypeInformation.of(valueType)); + TypeInformation.of(valueType)); Object o = readInternal(entityClass, key, typeInformation.getType(), new RedisData(partial)); target.put(mapKey, o); @@ -962,7 +977,7 @@ private Object extractMapKeyForPath(String path, String key, Class targetType Matcher matcher = pattern.matcher(key); if (!matcher.find()) { throw new IllegalArgumentException( - String.format("Cannot extract map value for key '%s' in path '%s'.", key, path)); + String.format("Cannot extract map value for key '%s' in path '%s'.", key, path)); } Object mapKey = matcher.group(2); @@ -977,7 +992,7 @@ private Object extractMapKeyForPath(String path, String key, Class targetType private Class getTypeHint(String path, Bucket bucket, Class fallback) { TypeInformation typeInformation = typeMapper.readType(bucket.getPropertyPath(path), - TypeInformation.of(fallback)); + TypeInformation.of(fallback)); return typeInformation.getType(); } @@ -1002,9 +1017,9 @@ public byte[] toBytes(Object source) { * Convert given binary representation to desired target type using the * underlying {@link ConversionService}. * - * @param expected type of the source object - * @param source the source object - * @param type the class to cast the object to + * @param expected type of the source object + * @param source the source object + * @param type the class to cast the object to * @return the target object * @throws ConverterNotFoundException if a specific converter cannot be found */ @@ -1102,47 +1117,6 @@ private void initializeConverters() { customConversions.registerConvertersIn(conversionService); } - private static boolean isByteArray(RedisPersistentProperty property) { - return !property.getType().equals(byte[].class); - } - - private static boolean isByteArray(TypeInformation type) { - return type.getType().equals(byte[].class); - } - - /** - * @author Christoph Strobl - * @author Mark Paluch - */ - private class ConverterAwareParameterValueProvider implements PropertyValueProvider { - - private final String path; - private final RedisData source; - private final ConversionService conversionService; - private final Class entityClass; - - ConverterAwareParameterValueProvider(Class entityClass, String path, RedisData source, - ConversionService conversionService) { - this.entityClass = entityClass; - this.path = path; - this.source = source; - this.conversionService = conversionService; - } - - @Override - @SuppressWarnings("unchecked") - public T getPropertyValue(RedisPersistentProperty property) { - - Object value = readProperty(entityClass, path, source, property); - - if (value == null || ClassUtils.isAssignableValue(property.getType(), value)) { - return (T) value; - } - - return (T) conversionService.convert(value, property.getType()); - } - } - private enum NaturalOrderingKeyComparator implements Comparator { INSTANCE; @@ -1341,8 +1315,8 @@ public boolean isPhantomKey() { */ public static class BinaryKeyspaceIdentifier { - protected static final byte[] PHANTOM = KeyspaceIdentifier.PHANTOM.getBytes(); public static final byte DELIMITER = ':'; + protected static final byte[] PHANTOM = KeyspaceIdentifier.PHANTOM.getBytes(); protected static final byte[] PHANTOM_SUFFIX = ByteUtils.concat(new byte[] { DELIMITER }, PHANTOM); private final byte[] keyspace; @@ -1430,4 +1404,37 @@ public boolean isPhantomKey() { return this.phantomKey; } } + + /** + * @author Christoph Strobl + * @author Mark Paluch + */ + private class ConverterAwareParameterValueProvider implements PropertyValueProvider { + + private final String path; + private final RedisData source; + private final ConversionService conversionService; + private final Class entityClass; + + ConverterAwareParameterValueProvider(Class entityClass, String path, RedisData source, + ConversionService conversionService) { + this.entityClass = entityClass; + this.path = path; + this.source = source; + this.conversionService = conversionService; + } + + @Override + @SuppressWarnings("unchecked") + public T getPropertyValue(RedisPersistentProperty property) { + + Object value = readProperty(entityClass, path, source, property); + + if (value == null || ClassUtils.isAssignableValue(property.getType(), value)) { + return (T) value; + } + + return (T) conversionService.convert(value, property.getType()); + } + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/OffsetDateTimeToStringConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/OffsetDateTimeToStringConverter.java index 5546fd4d..00fe1d85 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/OffsetDateTimeToStringConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/OffsetDateTimeToStringConverter.java @@ -11,10 +11,10 @@ @Component @WritingConverter public class OffsetDateTimeToStringConverter implements Converter { - @Override - public String convert(OffsetDateTime source) { - Instant instant = source.atZoneSameInstant(ZoneId.systemDefault()).toInstant(); - long unixTime = instant.getEpochSecond(); - return Long.toString(unixTime); - } + @Override + public String convert(OffsetDateTime source) { + Instant instant = source.atZoneSameInstant(ZoneId.systemDefault()).toInstant(); + long unixTime = instant.getEpochSecond(); + return Long.toString(unixTime); + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/PointToBytesConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/PointToBytesConverter.java index 33389e20..e379635e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/PointToBytesConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/PointToBytesConverter.java @@ -9,11 +9,11 @@ @Component @WritingConverter -public class PointToBytesConverter implements Converter { +public class PointToBytesConverter implements Converter { byte[] fromString(String source) { return source.getBytes(StandardCharsets.UTF_8); } - + @Override public byte[] convert(Point source) { return fromString(source.getX() + "," + source.getY()); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/RedisOMCustomConversions.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/RedisOMCustomConversions.java index d8c585ff..13728a6a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/RedisOMCustomConversions.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/RedisOMCustomConversions.java @@ -8,7 +8,7 @@ public class RedisOMCustomConversions extends RedisCustomConversions { private static final List omConverters = new ArrayList<>(); - + static { // Ulid omConverters.add(new UlidToBytesConverter()); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/convert/UlidToBytesConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/convert/UlidToBytesConverter.java index 131c98f7..5a570421 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/convert/UlidToBytesConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/convert/UlidToBytesConverter.java @@ -13,7 +13,7 @@ public class UlidToBytesConverter implements Converter { byte[] fromString(String source) { return source.getBytes(StandardCharsets.UTF_8); } - + @Override public byte[] convert(Ulid source) { return fromString(source.toString()); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/cuckoo/CuckooAspect.java b/redis-om-spring/src/main/java/com/redis/om/spring/cuckoo/CuckooAspect.java index 3529c11e..8548ad18 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/cuckoo/CuckooAspect.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/cuckoo/CuckooAspect.java @@ -21,32 +21,38 @@ @Aspect @Component public class CuckooAspect implements Ordered { - private final CuckooFilterOperations ops; private static final Log logger = LogFactory.getLog(CuckooAspect.class); + private final CuckooFilterOperations ops; public CuckooAspect(CuckooFilterOperations ops) { this.ops = ops; } @Pointcut("execution(public * org.springframework.data.repository.CrudRepository+.save(..))") - public void inCrudRepositorySave() {} + public void inCrudRepositorySave() { + } @Pointcut("execution(public * com.redis.om.spring.repository.RedisDocumentRepository+.save(..))") - public void inRedisDocumentRepositorySave() {} + public void inRedisDocumentRepositorySave() { + } @Pointcut("inCrudRepositorySave() || inRedisDocumentRepositorySave()") - private void inSaveOperation() {} + private void inSaveOperation() { + } @AfterReturning("inSaveOperation() && args(entity,..)") public void addToCuckoo(JoinPoint jp, Object entity) { for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(Cuckoo.class)) { Cuckoo cuckoo = field.getAnnotation(Cuckoo.class); - String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? cuckoo.name() : String.format("cf:%s:%s", entity.getClass().getSimpleName(), field.getName()); + String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? + cuckoo.name() : + String.format("cf:%s:%s", entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); ops.add(filterName, pd.getReadMethod().invoke(entity).toString()); - } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | InvocationTargetException e) { + } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | + InvocationTargetException e) { logger.error(String.format("Could not add value to Cuckoo filter %s", filterName), e); } } @@ -54,13 +60,16 @@ public void addToCuckoo(JoinPoint jp, Object entity) { } @Pointcut("execution(public * org.springframework.data.repository.CrudRepository+.saveAll(..))") - public void inCrudRepositorySaveAll() {} + public void inCrudRepositorySaveAll() { + } @Pointcut("execution(public * com.redis.om.spring.repository.RedisDocumentRepository+.saveAll(..))") - public void inRedisDocumentRepositorySaveAll() {} + public void inRedisDocumentRepositorySaveAll() { + } @Pointcut("inCrudRepositorySaveAll() || inRedisDocumentRepositorySaveAll()") - private void inSaveAllOperation() {} + private void inSaveAllOperation() { + } @AfterReturning("inSaveAllOperation() && args(entities,..)") public void addAllToCuckoo(JoinPoint jp, List entities) { @@ -68,11 +77,14 @@ public void addAllToCuckoo(JoinPoint jp, List entities) { for (Field field : com.redis.om.spring.util.ObjectUtils.getDeclaredFieldsTransitively(entity.getClass())) { if (field.isAnnotationPresent(Cuckoo.class)) { Cuckoo cuckoo = field.getAnnotation(Cuckoo.class); - String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? cuckoo.name() : String.format("cf:%s:%s", entity.getClass().getSimpleName(), field.getName()); + String filterName = !ObjectUtils.isEmpty(cuckoo.name()) ? + cuckoo.name() : + String.format("cf:%s:%s", entity.getClass().getSimpleName(), field.getName()); try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); ops.add(filterName, pd.getReadMethod().invoke(entity).toString()); - } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | InvocationTargetException e) { + } catch (IllegalArgumentException | IllegalAccessException | IntrospectionException | + InvocationTargetException e) { logger.error(String.format("Could not add values to Bloom filter %s", filterName), e); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/id/OsTools.java b/redis-om-spring/src/main/java/com/redis/om/spring/id/OsTools.java index 3ab60647..a6e16582 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/id/OsTools.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/id/OsTools.java @@ -4,14 +4,15 @@ import java.util.List; public class OsTools { - private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name").toLowerCase(); + private static final String OPERATING_SYSTEM_NAME = System.getProperty("os.name").toLowerCase(); - private static final List SECURE_RANDOM_ALGORITHMS_LINUX_OSX_SOLARIS = Arrays.asList("NativePRNGBlocking", - "NativePRNGNonBlocking", "NativePRNG", "SHA1PRNG"); - private static final List SECURE_RANDOM_ALGORITHMS_WINDOWS = Arrays.asList("SHA1PRNG", "Windows-PRNG"); + private static final List SECURE_RANDOM_ALGORITHMS_LINUX_OSX_SOLARIS = Arrays.asList("NativePRNGBlocking", + "NativePRNGNonBlocking", "NativePRNG", "SHA1PRNG"); + private static final List SECURE_RANDOM_ALGORITHMS_WINDOWS = Arrays.asList("SHA1PRNG", "Windows-PRNG"); - static List secureRandomAlgorithmNames() { - return OPERATING_SYSTEM_NAME.contains("win") ? SECURE_RANDOM_ALGORITHMS_WINDOWS - : SECURE_RANDOM_ALGORITHMS_LINUX_OSX_SOLARIS; - } + static List secureRandomAlgorithmNames() { + return OPERATING_SYSTEM_NAME.contains("win") ? + SECURE_RANDOM_ALGORITHMS_WINDOWS : + SECURE_RANDOM_ALGORITHMS_LINUX_OSX_SOLARIS; + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/id/SecureRandom.java b/redis-om-spring/src/main/java/com/redis/om/spring/id/SecureRandom.java index 21990268..be7bf3d0 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/id/SecureRandom.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/id/SecureRandom.java @@ -7,22 +7,23 @@ import java.util.concurrent.atomic.AtomicReference; public class SecureRandom { - private static final AtomicReference secureRandom = new AtomicReference<>(null); + private static final AtomicReference secureRandom = new AtomicReference<>(null); - public static java.security.SecureRandom getSecureRandom() { - return secureRandom.updateAndGet(sr -> sr != null ? sr : createSecureRandom()); - } - - private static java.security.SecureRandom createSecureRandom() { - for (String algorithm : OsTools.secureRandomAlgorithmNames()) { - try { - return java.security.SecureRandom.getInstance(algorithm); - } catch (NoSuchAlgorithmException e) { - // ignore and try the next algorithm. - } - } + public static java.security.SecureRandom getSecureRandom() { + return secureRandom.updateAndGet(sr -> sr != null ? sr : createSecureRandom()); + } - throw new InvalidDataAccessApiUsageException("Could not create SecureRandom instance for any of the specified algorithms: " - + StringUtils.collectionToCommaDelimitedString(OsTools.secureRandomAlgorithmNames())); + private static java.security.SecureRandom createSecureRandom() { + for (String algorithm : OsTools.secureRandomAlgorithmNames()) { + try { + return java.security.SecureRandom.getInstance(algorithm); + } catch (NoSuchAlgorithmException e) { + // ignore and try the next algorithm. + } } + + throw new InvalidDataAccessApiUsageException( + "Could not create SecureRandom instance for any of the specified algorithms: " + StringUtils.collectionToCommaDelimitedString( + OsTools.secureRandomAlgorithmNames())); + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/id/ULIDIdentifierGenerator.java b/redis-om-spring/src/main/java/com/redis/om/spring/id/ULIDIdentifierGenerator.java index 046939d1..dc0bb953 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/id/ULIDIdentifierGenerator.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/id/ULIDIdentifierGenerator.java @@ -27,8 +27,8 @@ public T generateIdentifierOfType(TypeInformation identifierType) { } throw new InvalidDataAccessApiUsageException( - String.format("Identifier cannot be generated for %s. Supported types are: ULID, String, Integer, and Long.", - identifierType.getType().getName())); + String.format("Identifier cannot be generated for %s. Supported types are: ULID, String, Integer, and Long.", + identifierType.getType().getName())); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/IllegalJavaBeanException.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/IllegalJavaBeanException.java index 504e69d9..3a898f54 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/IllegalJavaBeanException.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/IllegalJavaBeanException.java @@ -4,12 +4,13 @@ public class IllegalJavaBeanException extends RuntimeException { - @Serial private static final long serialVersionUID = 92362727623423324L; + @Serial + private static final long serialVersionUID = 92362727623423324L; public IllegalJavaBeanException(final Class clazz, final String fieldName) { super(String.format( - "The field '%s.%s' could not be matched to any getter. Please update your %s class to reflect standard JavaBean notation.", - clazz.getName(), fieldName, clazz.getName())); + "The field '%s.%s' could not be matched to any getter. Please update your %s class to reflect standard JavaBean notation.", + clazz.getName(), fieldName, clazz.getName())); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelField.java index 4f7b4c86..8747397a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelField.java @@ -8,13 +8,13 @@ import java.util.Comparator; import java.util.function.Function; -public class MetamodelField implements Comparator, Function { +public class MetamodelField implements Comparator, Function { protected final SearchFieldAccessor searchFieldAccessor; protected final boolean indexed; protected final String alias; protected Class targetClass; - + public MetamodelField(SearchFieldAccessor searchFieldAccessor, boolean indexed) { this.searchFieldAccessor = searchFieldAccessor; this.indexed = indexed; @@ -34,7 +34,7 @@ public MetamodelField(String alias, Class targetClass) { this.alias = alias; this.targetClass = targetClass; } - + public SearchFieldAccessor getSearchFieldAccessor() { return searchFieldAccessor; } @@ -48,7 +48,7 @@ public int compare(E o1, E o2) { public T apply(E t) { return null; } - + public boolean isIndexed() { return indexed; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelGenerator.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelGenerator.java index 70375de3..8a67689e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelGenerator.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelGenerator.java @@ -40,782 +40,744 @@ import static org.apache.commons.lang3.ObjectUtils.isEmpty; -@SupportedAnnotationTypes(value = { "com.redis.om.spring.annotations.Document", - "org.springframework.data.redis.core.RedisHash" }) +@SupportedAnnotationTypes( + value = { "com.redis.om.spring.annotations.Document", "org.springframework.data.redis.core.RedisHash" } +) @SupportedSourceVersion(SourceVersion.RELEASE_17) @AutoService(Processor.class) public final class MetamodelGenerator extends AbstractProcessor { - static final String GET_PREFIX = "get"; - static final String IS_PREFIX = "is"; - - private ProcessingEnvironment processingEnvironment; - private Messager messager; - - private TypeElement objectTypeElement; - private final Map depthMap = new HashMap<>(); - - public MetamodelGenerator() { + static final String GET_PREFIX = "get"; + static final String IS_PREFIX = "is"; + private static final Set DISALLOWED_ACCESS_LEVELS = Stream.of("PROTECTED", "PRIVATE", "NONE") + .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); + private final Map depthMap = new HashMap<>(); + private ProcessingEnvironment processingEnvironment; + private Messager messager; + private TypeElement objectTypeElement; + + public MetamodelGenerator() { + } + + private static TypeSpec getTypeSpecForMetamodelClass(String genEntityName, List interceptors, + List fields, List nestedFieldsConstants, CodeBlock staticBlock) { + return TypeSpec.classBuilder(genEntityName) // + .addModifiers(Modifier.PUBLIC, Modifier.FINAL) // + .addFields(fields.stream().map(ObjectGraphFieldSpec::fieldSpec).toList()) // + .addFields(nestedFieldsConstants) // + .addStaticBlock(staticBlock) // + .addFields(interceptors) // + .build(); + } + + @Override + public synchronized void init(ProcessingEnvironment env) { + super.init(env); + + this.processingEnvironment = env; + processingEnvironment.getElementUtils(); + processingEnvironment.getTypeUtils(); + + messager = processingEnvironment.getMessager(); + messager.printMessage(Diagnostic.Kind.NOTE, "🍃 Redis OM Spring Entity Metamodel Generator"); + + this.objectTypeElement = processingEnvironment.getElementUtils().getTypeElement("java.lang.Object"); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + + if (annotations.isEmpty() || roundEnv.processingOver()) { + // Allow other processors to run + return false; } - @Override - public synchronized void init(ProcessingEnvironment env) { - super.init(env); - - this.processingEnvironment = env; - processingEnvironment.getElementUtils(); - processingEnvironment.getTypeUtils(); - - messager = processingEnvironment.getMessager(); - messager.printMessage(Diagnostic.Kind.NOTE, "🍃 Redis OM Spring Entity Metamodel Generator"); - - this.objectTypeElement = processingEnvironment.getElementUtils().getTypeElement("java.lang.Object"); + Set documentEntities = roundEnv.getElementsAnnotatedWith(Document.class); + Set hashEntities = roundEnv.getElementsAnnotatedWith(RedisHash.class); + Set metamodelCandidates = Stream.of(documentEntities, hashEntities) // + .flatMap(Collection::stream).collect(Collectors.toSet()); + + metamodelCandidates.stream().filter(ae -> ae.getKind() == ElementKind.CLASS).forEach(ae -> { + try { + generateMetaModelClass(ae); + } catch (IOException ioe) { + messager.printMessage(Diagnostic.Kind.ERROR, + "Cannot generate metamodel class for " + ae.getClass().getName() + " because " + ioe.getMessage()); + } + }); + + return true; + } + + void generateMetaModelClass(final Element annotatedElement) throws IOException { + String qualifiedGenEntityName = annotatedElement.asType().toString() + "$"; + final String entityName = ObjectUtils.shortName(annotatedElement.asType().toString()); + final String genEntityName = entityName + "$"; + TypeName entity = TypeName.get(annotatedElement.asType()); + + messager.printMessage(Diagnostic.Kind.NOTE, "Generating Entity Metamodel: " + qualifiedGenEntityName); + + Map enclosedFields = getInstanceFields(annotatedElement); + + final PackageElement packageElement = processingEnvironment.getElementUtils().getPackageOf(annotatedElement); + String packageName; + if (packageElement.isUnnamed()) { + messager.printMessage(Diagnostic.Kind.WARNING, "Class " + entityName + " has an unnamed package."); + packageName = ""; + } else { + packageName = packageElement.getQualifiedName().toString(); } - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { + List interceptors = new ArrayList<>(); + List fields = new ArrayList<>(); + List initCodeBlocks = new ArrayList<>(); + List nestedFieldsConstants = new ArrayList<>(); - if (annotations.isEmpty() || roundEnv.processingOver()) { - // Allow other processors to run - return false; - } + enclosedFields.forEach((field, getter) -> { + List> fieldMetamodels = processFieldMetamodel(entity, + entityName, List.of(field)); + extractFieldMetamodels(entity, interceptors, fields, initCodeBlocks, fieldMetamodels); + }); - Set documentEntities = roundEnv.getElementsAnnotatedWith(Document.class); - Set hashEntities = roundEnv.getElementsAnnotatedWith(RedisHash.class); - Set metamodelCandidates = Stream.of(documentEntities, hashEntities) // - .flatMap(Collection::stream).collect(Collectors.toSet()); + Pair keyAccessor = generateUnboundMetamodelField(entity, "_KEY", "__key", String.class); + interceptors.add(keyAccessor.getFirst()); + initCodeBlocks.add(keyAccessor.getSecond()); - metamodelCandidates.stream().filter(ae -> ae.getKind() == ElementKind.CLASS).forEach(ae -> { - try { - generateMetaModelClass(ae); - } catch (IOException ioe) { - messager.printMessage(Diagnostic.Kind.ERROR, "Cannot generate metamodel class for " - + ae.getClass().getName() + " because " + ioe.getMessage()); - } - }); + Pair thisAccessor = generateThisMetamodelField(entity); + interceptors.add(thisAccessor.getFirst()); + initCodeBlocks.add(thisAccessor.getSecond()); - return true; - } + CodeBlock.Builder blockBuilder = CodeBlock.builder(); - void generateMetaModelClass(final Element annotatedElement) throws IOException { - String qualifiedGenEntityName = annotatedElement.asType().toString() + "$"; - final String entityName = ObjectUtils.shortName(annotatedElement.asType().toString()); - final String genEntityName = entityName + "$"; - TypeName entity = TypeName.get(annotatedElement.asType()); + boolean hasFields = !fields.isEmpty(); + if (hasFields) + blockBuilder.beginControlFlow("try"); + addStatement(entity, fields, initCodeBlocks, blockBuilder); - messager.printMessage(Diagnostic.Kind.NOTE, - "Generating Entity Metamodel: " + qualifiedGenEntityName); - - Map enclosedFields = getInstanceFields(annotatedElement); - - final PackageElement packageElement = processingEnvironment.getElementUtils().getPackageOf(annotatedElement); - String packageName; - if (packageElement.isUnnamed()) { - messager.printMessage(Diagnostic.Kind.WARNING, "Class " + entityName + " has an unnamed package."); - packageName = ""; - } else { - packageName = packageElement.getQualifiedName().toString(); - } - - List interceptors = new ArrayList<>(); - List fields = new ArrayList<>(); - List initCodeBlocks = new ArrayList<>(); - List nestedFieldsConstants = new ArrayList<>(); + if (hasFields) { + blockBuilder.nextControlFlow("catch($T | $T e)", NoSuchFieldException.class, SecurityException.class); + blockBuilder.addStatement("System.err.println(e.getMessage())"); + blockBuilder.endControlFlow(); + } - enclosedFields.forEach((field, getter) -> { - List> fieldMetamodels = processFieldMetamodel(entity, - entityName, List.of(field)); - extractFieldMetamodels(entity, interceptors, fields, initCodeBlocks, fieldMetamodels); - }); + CodeBlock staticBlock = blockBuilder.build(); - Pair keyAccessor = generateUnboundMetamodelField(entity, "_KEY", "__key", String.class); - interceptors.add(keyAccessor.getFirst()); - initCodeBlocks.add(keyAccessor.getSecond()); + TypeSpec metaClass = getTypeSpecForMetamodelClass(genEntityName, interceptors, fields, nestedFieldsConstants, + staticBlock); - Pair thisAccessor = generateThisMetamodelField(entity); - interceptors.add(thisAccessor.getFirst()); - initCodeBlocks.add(thisAccessor.getSecond()); + JavaFile javaFile = JavaFile // + .builder(packageName, metaClass) // + .build(); - CodeBlock.Builder blockBuilder = CodeBlock.builder(); + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(qualifiedGenEntityName); + Writer writer = builderFile.openWriter(); + javaFile.writeTo(writer); - boolean hasFields = !fields.isEmpty(); - if (hasFields) - blockBuilder.beginControlFlow("try"); - addStatement(entity, fields, initCodeBlocks, blockBuilder); + writer.close(); + } - if (hasFields) { - blockBuilder.nextControlFlow("catch($T | $T e)", NoSuchFieldException.class, SecurityException.class); - blockBuilder.addStatement("System.err.println(e.getMessage())"); - blockBuilder.endControlFlow(); + private void addStatement(TypeName entity, List fields, List initCodeBlocks, + Builder blockBuilder) { + for (ObjectGraphFieldSpec ogfs : fields) { + StringBuilder sb = new StringBuilder("$T.class"); + for (int i = 0; i < ogfs.chain().size(); i++) { + Element element = ogfs.chain().get(i); + if (i != 0) { + sb.append(".getType()"); } - - CodeBlock staticBlock = blockBuilder.build(); - - TypeSpec metaClass = getTypeSpecForMetamodelClass(genEntityName, interceptors, fields, - nestedFieldsConstants, staticBlock); - - JavaFile javaFile = JavaFile // - .builder(packageName, metaClass) // - .build(); - - JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(qualifiedGenEntityName); - Writer writer = builderFile.openWriter(); - javaFile.writeTo(writer); - - writer.close(); + String formattedString = String.format( + "com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(%s, \"%s\")", sb, element.getSimpleName()); + sb.setLength(0); // clear the builder + sb.append(formattedString); + } + FieldSpec fieldSpec = ogfs.fieldSpec(); + blockBuilder.addStatement("$L = " + sb, fieldSpec.name, entity); } - private static TypeSpec getTypeSpecForMetamodelClass(String genEntityName, List interceptors, - List fields, List nestedFieldsConstants, - CodeBlock staticBlock) { - return TypeSpec.classBuilder(genEntityName) // - .addModifiers(Modifier.PUBLIC, Modifier.FINAL) // - .addFields(fields.stream().map(ObjectGraphFieldSpec::fieldSpec).toList()) // - .addFields(nestedFieldsConstants) // - .addStaticBlock(staticBlock) // - .addFields(interceptors) // - .build(); + for (CodeBlock initCodeBlock : initCodeBlocks) { + blockBuilder.add(initCodeBlock); + } + } + + private List> processFieldMetamodel(TypeName entity, + String entityName, List chain) { + return processFieldMetamodel(entity, entityName, chain, null); + } + + private List> processFieldMetamodel(TypeName entity, + String entityName, List chain, String collectionPrefix) { + List> fieldMetamodelSpec = new ArrayList<>(); + + Element field = chain.get(chain.size() - 1); + + var indexed = field.getAnnotation(Indexed.class); + var searchable = field.getAnnotation(Searchable.class); + var textIndexed = field.getAnnotation(TextIndexed.class); + var tagIndexed = field.getAnnotation(TagIndexed.class); + var numericIndexed = field.getAnnotation(NumericIndexed.class); + var geoIndexed = field.getAnnotation(GeoIndexed.class); + var vectorIndexed = field.getAnnotation(VectorIndexed.class); + + var id = field.getAnnotation(Id.class); + var reference = field.getAnnotation(Reference.class); + + boolean fieldIsIndexed = (searchable != null) || (indexed != null) || (textIndexed != null) || (tagIndexed != null) || (numericIndexed != null) || (geoIndexed != null) || (vectorIndexed != null) || (id != null); + + String chainedFieldName = chain.stream().map(Element::getSimpleName).collect(Collectors.joining("_")); + messager.printMessage(Diagnostic.Kind.NOTE, "Processing " + chainedFieldName); + TypeName entityField = TypeName.get(field.asType()); + + TypeMirror fieldType = field.asType(); + String fullTypeClassName = fieldType.toString(); + String cls = ObjectUtils.getTargetClassName(fullTypeClassName); + + if (field.asType().getKind().isPrimitive()) { + Class primitive = ClassUtils.resolvePrimitiveClassName(cls); + if (primitive == null) + return Collections.emptyList(); + Class primitiveWrapper = ClassUtils.resolvePrimitiveIfNecessary(primitive); + entityField = TypeName.get(primitiveWrapper); + fullTypeClassName = entityField.toString(); + cls = ObjectUtils.getTargetClassName(fullTypeClassName); } - private void addStatement(TypeName entity, List fields, - List initCodeBlocks, Builder blockBuilder) { - for (ObjectGraphFieldSpec ogfs : fields) { - StringBuilder sb = new StringBuilder("$T.class"); - for (int i = 0; i < ogfs.chain().size(); i++) { - Element element = ogfs.chain().get(i); - if (i != 0) { - sb.append(".getType()"); - } - String formattedString = String.format( - "com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(%s, \"%s\")", sb, - element.getSimpleName()); - sb.setLength(0); // clear the builder - sb.append(formattedString); - } - FieldSpec fieldSpec = ogfs.fieldSpec(); - blockBuilder.addStatement("$L = " + sb, fieldSpec.name, entity); + Class targetInterceptor = null; + Class targetCls = null; + + String searchSchemaAlias = null; + + if (indexed != null && reference != null) { + // + // @Reference: Field is a reference to another entity + // + targetInterceptor = ReferenceField.class; + searchSchemaAlias = indexed.alias(); + } else if (searchable != null || textIndexed != null) { + // + // @Searchable/@TextIndexed: Field is a full-text field + // + targetInterceptor = TextField.class; + searchSchemaAlias = (searchable != null) ? searchable.alias() : textIndexed.alias(); + } else if (fieldIsIndexed) { + // + // + // + try { + targetCls = ClassUtils.forName(cls, MetamodelGenerator.class.getClassLoader()); + } catch (ClassNotFoundException cnfe) { + messager.printMessage(Diagnostic.Kind.WARNING, + "Processing class " + entityName + " could not resolve " + cls + " while checking for nested @Indexed"); + fieldMetamodelSpec.addAll(processNestedIndexableFields(entity, chain)); + } + + if (tagIndexed != null) { + targetInterceptor = TextTagField.class; + searchSchemaAlias = tagIndexed.alias(); + } else if (numericIndexed != null) { + targetInterceptor = NumericField.class; + searchSchemaAlias = numericIndexed.alias(); + } else if (geoIndexed != null) { + targetInterceptor = GeoField.class; + searchSchemaAlias = geoIndexed.alias(); + } else if (vectorIndexed != null) { + targetInterceptor = VectorField.class; + searchSchemaAlias = vectorIndexed.alias(); + } else if (indexed != null && indexed.schemaFieldType() != SchemaFieldType.AUTODETECT) { + searchSchemaAlias = indexed.alias(); + // here we do the non autodetect annotated fields + switch (indexed.schemaFieldType()) { + case TAG -> targetInterceptor = TextTagField.class; + case NUMERIC -> targetInterceptor = NumericField.class; + case GEO -> targetInterceptor = GeoField.class; + case VECTOR -> targetInterceptor = VectorField.class; + default -> { + } // NOOP } - - for (CodeBlock initCodeBlock : initCodeBlocks) { - blockBuilder.add(initCodeBlock); + } else if (indexed != null && targetCls == null && isEnum(processingEnv, fieldType)) { + targetInterceptor = TextTagField.class; + searchSchemaAlias = indexed.alias(); + } else if (targetCls != null) { + // + // Any Character class -> Tag Search Field + // + if (CharSequence.class.isAssignableFrom(targetCls) || (targetCls == Ulid.class)) { + targetInterceptor = TextTagField.class; } - } - - private List> processFieldMetamodel(TypeName entity, - String entityName, List chain) { - return processFieldMetamodel(entity, entityName, chain, null); - } - - private List> processFieldMetamodel(TypeName entity, - String entityName, List chain, String collectionPrefix) { - List> fieldMetamodelSpec = new ArrayList<>(); - - Element field = chain.get(chain.size() - 1); - - var indexed = field.getAnnotation(Indexed.class); - var searchable = field.getAnnotation(Searchable.class); - var textIndexed = field.getAnnotation(TextIndexed.class); - var tagIndexed = field.getAnnotation(TagIndexed.class); - var numericIndexed = field.getAnnotation(NumericIndexed.class); - var geoIndexed = field.getAnnotation(GeoIndexed.class); - var vectorIndexed = field.getAnnotation(VectorIndexed.class); - - var id = field.getAnnotation(Id.class); - var reference = field.getAnnotation(Reference.class); - - boolean fieldIsIndexed = (searchable != null) - || (indexed != null) - || (textIndexed != null) - || (tagIndexed != null) - || (numericIndexed != null) - || (geoIndexed != null) - || (vectorIndexed != null) - || (id != null); - - String chainedFieldName = chain.stream().map(Element::getSimpleName).collect(Collectors.joining("_")); - messager.printMessage(Diagnostic.Kind.NOTE, "Processing " + chainedFieldName); - TypeName entityField = TypeName.get(field.asType()); - - TypeMirror fieldType = field.asType(); - String fullTypeClassName = fieldType.toString(); - String cls = ObjectUtils.getTargetClassName(fullTypeClassName); - - if (field.asType().getKind().isPrimitive()) { - Class primitive = ClassUtils.resolvePrimitiveClassName(cls); - if (primitive == null) - return Collections.emptyList(); - Class primitiveWrapper = ClassUtils.resolvePrimitiveIfNecessary(primitive); - entityField = TypeName.get(primitiveWrapper); - fullTypeClassName = entityField.toString(); - cls = ObjectUtils.getTargetClassName(fullTypeClassName); + // + // Any Numeric class -> Numeric Search Field + // + else if (Number.class.isAssignableFrom(targetCls)) { + targetInterceptor = NumericField.class; } - - Class targetInterceptor = null; - Class targetCls = null; - - String searchSchemaAlias = null; - - if (indexed != null && reference != null) { - // - // @Reference: Field is a reference to another entity - // - targetInterceptor = ReferenceField.class; - searchSchemaAlias = indexed.alias(); - } else if (searchable != null || textIndexed != null) { - // - // @Searchable/@TextIndexed: Field is a full-text field - // - targetInterceptor = TextField.class; - searchSchemaAlias = (searchable != null) ? searchable.alias() : textIndexed.alias(); - } else if (fieldIsIndexed) { - // - // - // + // + // Any Date/Time Types + // + else if ((targetCls == LocalDateTime.class) || (targetCls == LocalDate.class) // + || (targetCls == Date.class) || (targetCls == Instant.class) || (targetCls == OffsetDateTime.class)) { + targetInterceptor = DateField.class; + } + // + // Set / List + // + else if (Set.class.isAssignableFrom(targetCls) || List.class.isAssignableFrom(targetCls)) { + String collectionElementName = ObjectUtils.getCollectionTargetClassName(fullTypeClassName); + targetInterceptor = TagField.class; + try { + ClassUtils.forName(collectionElementName, MetamodelGenerator.class.getClassLoader()); + } catch (ClassNotFoundException cnfe) { + Triple collectionFieldMetamodel = null; try { - targetCls = ClassUtils.forName(cls, MetamodelGenerator.class.getClassLoader()); - } catch (ClassNotFoundException cnfe) { - messager.printMessage(Diagnostic.Kind.WARNING, - "Processing class " + entityName + " could not resolve " + cls - + " while checking for nested @Indexed"); - fieldMetamodelSpec.addAll(processNestedIndexableFields(entity, chain)); + collectionFieldMetamodel = generateCollectionFieldMetamodel(entity, chain, chainedFieldName, + collectionElementName); + } catch (IOException e) { + messager.printMessage(Diagnostic.Kind.WARNING, + "Processing class " + entityName + " could create collection field metamodel element for " + collectionElementName); } - - if (tagIndexed != null) { - targetInterceptor = TextTagField.class; - searchSchemaAlias = tagIndexed.alias(); - } else if (numericIndexed != null) { - targetInterceptor = NumericField.class; - searchSchemaAlias = numericIndexed.alias(); - } else if (geoIndexed != null) { - targetInterceptor = GeoField.class; - searchSchemaAlias = geoIndexed.alias(); - } else if (vectorIndexed != null) { - targetInterceptor = VectorField.class; - searchSchemaAlias = vectorIndexed.alias(); - } else if (indexed != null && indexed.schemaFieldType() != SchemaFieldType.AUTODETECT) { - searchSchemaAlias = indexed.alias(); - // here we do the non autodetect annotated fields - switch (indexed.schemaFieldType()) { - case TAG -> targetInterceptor = TextTagField.class; - case NUMERIC -> targetInterceptor = NumericField.class; - case GEO -> targetInterceptor = GeoField.class; - case VECTOR -> targetInterceptor = VectorField.class; - } - } else if (indexed != null && targetCls == null && isEnum(processingEnv, fieldType)) { - targetInterceptor = TextTagField.class; - searchSchemaAlias = indexed.alias(); - } else if (targetCls != null) { - // - // Any Character class -> Tag Search Field - // - if (CharSequence.class.isAssignableFrom(targetCls) || (targetCls == Ulid.class)) { - targetInterceptor = TextTagField.class; - } - // - // Any Numeric class -> Numeric Search Field - // - else if (Number.class.isAssignableFrom(targetCls)) { - targetInterceptor = NumericField.class; - } - // - // Any Date/Time Types - // - else if ((targetCls == LocalDateTime.class) || (targetCls == LocalDate.class) // - || (targetCls == Date.class) || (targetCls == Instant.class) || (targetCls == OffsetDateTime.class)) { - targetInterceptor = DateField.class; - } - // - // Set / List - // - else if (Set.class.isAssignableFrom(targetCls) || List.class.isAssignableFrom(targetCls)) { - String collectionElementName = ObjectUtils.getCollectionTargetClassName(fullTypeClassName); - targetInterceptor = TagField.class; - try { - ClassUtils.forName(collectionElementName, MetamodelGenerator.class.getClassLoader()); - } catch (ClassNotFoundException cnfe) { - Triple collectionFieldMetamodel = null; - try { - collectionFieldMetamodel = generateCollectionFieldMetamodel(entity, chain, chainedFieldName, - collectionElementName); - } catch (IOException e) { - messager.printMessage(Diagnostic.Kind.WARNING, - "Processing class " + entityName - + " could create collection field metamodel element for " - + collectionElementName); - } - if (collectionFieldMetamodel != null) { - fieldMetamodelSpec.add(collectionFieldMetamodel); - targetInterceptor = null; - } - } - } - // - // Point - // - else if (targetCls == Point.class) { - targetInterceptor = GeoField.class; - } - // - // Boolean - // - else if (targetCls == Boolean.class) { - targetInterceptor = BooleanField.class; - } - } - if (indexed != null) { - searchSchemaAlias = indexed.alias(); - } - } else { - var metamodel = field.getAnnotation(Metamodel.class); - try { - targetCls = ClassUtils.forName(cls, MetamodelGenerator.class.getClassLoader()); - - // - // Any Character class - // - if (CharSequence.class.isAssignableFrom(targetCls) || (targetCls == Ulid.class)) { - targetInterceptor = NonIndexedTextField.class; - } - // - // Non-indexed Boolean - // - else if (targetCls == Boolean.class) { - targetInterceptor = NonIndexedBooleanField.class; - } - // - // Numeric class AND Any Date/Time Types - // - else if (Number.class.isAssignableFrom(targetCls) || (targetCls == LocalDateTime.class) - || (targetCls == LocalDate.class) || (targetCls == Date.class) - || (targetCls == Instant.class) || (targetCls == OffsetDateTime.class)) { - targetInterceptor = NonIndexedNumericField.class; - } - // - // Set / List - // - else if (Set.class.isAssignableFrom(targetCls) || List.class.isAssignableFrom(targetCls)) { - targetInterceptor = NonIndexedTagField.class; - } - // - // Point - // - else if (targetCls == Point.class) { - targetInterceptor = NonIndexedGeoField.class; - } - } catch (ClassNotFoundException cnfe) { - if (metamodel != null) { - messager.printMessage(Kind.NOTE, - "Processing class " + entityName + ", generating nested class " + cls - + " metamodel (@Metamodel)"); - fieldMetamodelSpec.addAll(processNestedIndexableFields(entity, chain)); - } + if (collectionFieldMetamodel != null) { + fieldMetamodelSpec.add(collectionFieldMetamodel); + targetInterceptor = null; } + } } - - if (targetInterceptor != null) { - fieldMetamodelSpec.add(generateFieldMetamodel(entity, chain, chainedFieldName, entityField, - targetInterceptor, fieldIsIndexed, collectionPrefix, searchSchemaAlias)); + // + // Point + // + else if (targetCls == Point.class) { + targetInterceptor = GeoField.class; + } + // + // Boolean + // + else if (targetCls == Boolean.class) { + targetInterceptor = BooleanField.class; + } + } + if (indexed != null) { + searchSchemaAlias = indexed.alias(); + } + } else { + var metamodel = field.getAnnotation(Metamodel.class); + try { + targetCls = ClassUtils.forName(cls, MetamodelGenerator.class.getClassLoader()); + + // + // Any Character class + // + if (CharSequence.class.isAssignableFrom(targetCls) || (targetCls == Ulid.class)) { + targetInterceptor = NonIndexedTextField.class; + } + // + // Non-indexed Boolean + // + else if (targetCls == Boolean.class) { + targetInterceptor = NonIndexedBooleanField.class; + } + // + // Numeric class AND Any Date/Time Types + // + else if (Number.class.isAssignableFrom( + targetCls) || (targetCls == LocalDateTime.class) || (targetCls == LocalDate.class) || (targetCls == Date.class) || (targetCls == Instant.class) || (targetCls == OffsetDateTime.class)) { + targetInterceptor = NonIndexedNumericField.class; } - return fieldMetamodelSpec; + // + // Set / List + // + else if (Set.class.isAssignableFrom(targetCls) || List.class.isAssignableFrom(targetCls)) { + targetInterceptor = NonIndexedTagField.class; + } + // + // Point + // + else if (targetCls == Point.class) { + targetInterceptor = NonIndexedGeoField.class; + } + } catch (ClassNotFoundException cnfe) { + if (metamodel != null) { + messager.printMessage(Kind.NOTE, + "Processing class " + entityName + ", generating nested class " + cls + " metamodel (@Metamodel)"); + fieldMetamodelSpec.addAll(processNestedIndexableFields(entity, chain)); + } + } } - private Triple generateCollectionFieldMetamodel( // - TypeName parentEntity, // - List chain, // - String chainedFieldName, // - String collectionElementName // - ) throws IOException { - Element entity1 = chain.get(chain.size() - 1).getEnclosingElement(); - String qualifiedGenEntityName = parentEntity.toString() + "_" + chainedFieldName + "$"; - final String genEntityName = qualifiedGenEntityName.substring(qualifiedGenEntityName.lastIndexOf('.') + 1); - final String entityName = collectionElementName; - TypeName entity = ClassName.bestGuess(entityName); - Map enclosedFields = getInstanceFields(entity); - - final PackageElement packageElement = processingEnvironment.getElementUtils().getPackageOf(entity1); - String packageName; - if (packageElement.isUnnamed()) { - messager.printMessage(Diagnostic.Kind.WARNING, - "Class " + entity1.getSimpleName() + " has an unnamed package."); - packageName = ""; - } else { - packageName = packageElement.getQualifiedName().toString(); - } + if (targetInterceptor != null) { + fieldMetamodelSpec.add( + generateFieldMetamodel(entity, chain, chainedFieldName, entityField, targetInterceptor, fieldIsIndexed, + collectionPrefix, searchSchemaAlias)); + } + return fieldMetamodelSpec; + } + + private Triple generateCollectionFieldMetamodel( // + TypeName parentEntity, // + List chain, // + String chainedFieldName, // + String collectionElementName // + ) throws IOException { + Element entity1 = chain.get(chain.size() - 1).getEnclosingElement(); + String qualifiedGenEntityName = parentEntity.toString() + "_" + chainedFieldName + "$"; + final String genEntityName = qualifiedGenEntityName.substring(qualifiedGenEntityName.lastIndexOf('.') + 1); + final String entityName = collectionElementName; + TypeName entity = ClassName.bestGuess(entityName); + Map enclosedFields = getInstanceFields(entity); + + final PackageElement packageElement = processingEnvironment.getElementUtils().getPackageOf(entity1); + String packageName; + if (packageElement.isUnnamed()) { + messager.printMessage(Diagnostic.Kind.WARNING, "Class " + entity1.getSimpleName() + " has an unnamed package."); + packageName = ""; + } else { + packageName = packageElement.getQualifiedName().toString(); + } - List interceptors = new ArrayList<>(); - List fields = new ArrayList<>(); - List initCodeBlocks = new ArrayList<>(); - List nestedFieldsConstants = new ArrayList<>(); + List interceptors = new ArrayList<>(); + List fields = new ArrayList<>(); + List initCodeBlocks = new ArrayList<>(); + List nestedFieldsConstants = new ArrayList<>(); - enclosedFields.forEach((field, getter) -> { - List> fieldMetamodels = processFieldMetamodel(entity, - entityName, List.of(field), chainedFieldName); - extractFieldMetamodels(entity, interceptors, fields, initCodeBlocks, fieldMetamodels); - }); + enclosedFields.forEach((field, getter) -> { + List> fieldMetamodels = processFieldMetamodel(entity, + entityName, List.of(field), chainedFieldName); + extractFieldMetamodels(entity, interceptors, fields, initCodeBlocks, fieldMetamodels); + }); - CodeBlock.Builder blockBuilder = CodeBlock.builder(); + CodeBlock.Builder blockBuilder = CodeBlock.builder(); - blockBuilder.beginControlFlow("try"); - addStatement(entity, fields, initCodeBlocks, blockBuilder); + blockBuilder.beginControlFlow("try"); + addStatement(entity, fields, initCodeBlocks, blockBuilder); - blockBuilder.nextControlFlow("catch($T | $T e)", NoSuchFieldException.class, SecurityException.class); - blockBuilder.addStatement("System.err.println(e.getMessage())"); - blockBuilder.endControlFlow(); + blockBuilder.nextControlFlow("catch($T | $T e)", NoSuchFieldException.class, SecurityException.class); + blockBuilder.addStatement("System.err.println(e.getMessage())"); + blockBuilder.endControlFlow(); - TypeSpec metaClass = getTypeSpecForFieldMetamodel(genEntityName, interceptors, fields, - nestedFieldsConstants, blockBuilder); + TypeSpec metaClass = getTypeSpecForFieldMetamodel(genEntityName, interceptors, fields, nestedFieldsConstants, + blockBuilder); - JavaFile javaFile = JavaFile // - .builder(packageName, metaClass) // - .build(); + JavaFile javaFile = JavaFile // + .builder(packageName, metaClass) // + .build(); - JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(qualifiedGenEntityName); - Writer writer = builderFile.openWriter(); - javaFile.writeTo(writer); + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(qualifiedGenEntityName); + Writer writer = builderFile.openWriter(); + javaFile.writeTo(writer); - writer.close(); + writer.close(); - TypeName generatedTypeName = ClassName.bestGuess(qualifiedGenEntityName); + TypeName generatedTypeName = ClassName.bestGuess(qualifiedGenEntityName); - return generateFieldMetamodel(chain, chainedFieldName, generatedTypeName); - } + return generateFieldMetamodel(chain, chainedFieldName, generatedTypeName); + } - private void extractFieldMetamodels(TypeName entity, List interceptors, - List fields, List initCodeBlocks, - List> fieldMetamodels) { - for (Triple fieldMetamodel : fieldMetamodels) { - FieldSpec fieldSpec = fieldMetamodel.getSecond(); - fields.add(fieldMetamodel.getFirst()); - interceptors.add(fieldMetamodel.getSecond()); - initCodeBlocks.add(fieldMetamodel.getThird()); - - // Add _SCORE field to Vector - if (fieldSpec.type.toString().startsWith(VectorField.class.getName())) { - String fieldName = fieldMetamodel.getFirst().fieldSpec().name; - Pair vectorFieldScore = generateUnboundMetamodelField(entity, - "_" + fieldSpec.name + "_SCORE", "__" + fieldName + "_score", Double.class); - interceptors.add(vectorFieldScore.getFirst()); - initCodeBlocks.add(vectorFieldScore.getSecond()); - } - } - } + private void extractFieldMetamodels(TypeName entity, List interceptors, List fields, + List initCodeBlocks, List> fieldMetamodels) { + for (Triple fieldMetamodel : fieldMetamodels) { + FieldSpec fieldSpec = fieldMetamodel.getSecond(); + fields.add(fieldMetamodel.getFirst()); + interceptors.add(fieldMetamodel.getSecond()); + initCodeBlocks.add(fieldMetamodel.getThird()); - private TypeSpec getTypeSpecForFieldMetamodel(String genEntityName, List interceptors, - List fields, List nestedFieldsConstants, - Builder blockBuilder) { - CodeBlock staticBlock = blockBuilder.build(); - - return TypeSpec.classBuilder(genEntityName) // - .superclass(CollectionField.class) // - .addMethod(MethodSpec.constructorBuilder() - .addModifiers(Modifier.PUBLIC) - .addParameter(SearchFieldAccessor.class, "searchFieldAccessor") - .addParameter(boolean.class, "indexed") - .addStatement("super(searchFieldAccessor, indexed)") - .build()) - .addModifiers(Modifier.PUBLIC, Modifier.FINAL) // - .addFields(fields.stream().map(ObjectGraphFieldSpec::fieldSpec).toList()) // - .addFields(nestedFieldsConstants) // - .addStaticBlock(staticBlock) // - .addFields(interceptors) // - .build(); + // Add _SCORE field to Vector + if (fieldSpec.type.toString().startsWith(VectorField.class.getName())) { + String fieldName = fieldMetamodel.getFirst().fieldSpec().name; + Pair vectorFieldScore = generateUnboundMetamodelField(entity, + "_" + fieldSpec.name + "_SCORE", "__" + fieldName + "_score", Double.class); + interceptors.add(vectorFieldScore.getFirst()); + initCodeBlocks.add(vectorFieldScore.getSecond()); + } } - - private List> processNestedIndexableFields(TypeName entity, - List chain) { - Element fieldElement = chain.get(chain.size() - 1); - TypeMirror typeMirror = fieldElement.asType(); - DeclaredType asDeclaredType = (DeclaredType) typeMirror; - Element entityField = asDeclaredType.asElement(); - - Indexed annotation = fieldElement.getAnnotation(Indexed.class); - if(entity.toString().equals(entityField.toString()) && annotation != null) { - Integer integer = depthMap.get(entity.toString()); - if (integer == null) { - depthMap.put(entity.toString(), 1); - } else { - if (++integer > annotation.depth()) { - return new ArrayList<>(); - } - depthMap.put(entity.toString(), integer); - } + } + + private TypeSpec getTypeSpecForFieldMetamodel(String genEntityName, List interceptors, + List fields, List nestedFieldsConstants, Builder blockBuilder) { + CodeBlock staticBlock = blockBuilder.build(); + + return TypeSpec.classBuilder(genEntityName) // + .superclass(CollectionField.class) // + .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC) + .addParameter(SearchFieldAccessor.class, "searchFieldAccessor").addParameter(boolean.class, "indexed") + .addStatement("super(searchFieldAccessor, indexed)").build()).addModifiers(Modifier.PUBLIC, Modifier.FINAL) // + .addFields(fields.stream().map(ObjectGraphFieldSpec::fieldSpec).toList()) // + .addFields(nestedFieldsConstants) // + .addStaticBlock(staticBlock) // + .addFields(interceptors) // + .build(); + } + + private List> processNestedIndexableFields(TypeName entity, + List chain) { + Element fieldElement = chain.get(chain.size() - 1); + TypeMirror typeMirror = fieldElement.asType(); + DeclaredType asDeclaredType = (DeclaredType) typeMirror; + Element entityField = asDeclaredType.asElement(); + + Indexed annotation = fieldElement.getAnnotation(Indexed.class); + if (entity.toString().equals(entityField.toString()) && annotation != null) { + Integer integer = depthMap.get(entity.toString()); + if (integer == null) { + depthMap.put(entity.toString(), 1); + } else { + if (++integer > annotation.depth()) { + return new ArrayList<>(); } + depthMap.put(entity.toString(), integer); + } + } - List> fieldMetamodels = new ArrayList<>(); - - messager.printMessage(Diagnostic.Kind.NOTE, - "Processing constants for " + fieldElement + " of type " + entityField); - - final String entityFieldName = fieldElement.toString(); - messager.printMessage(Diagnostic.Kind.NOTE, "entityFieldName => " + entityFieldName); - - Map enclosedFields = getInstanceFields(entityField); + List> fieldMetamodels = new ArrayList<>(); - messager.printMessage(Diagnostic.Kind.NOTE, "Enclosed subfield size() ==> " + enclosedFields.size()); + messager.printMessage(Diagnostic.Kind.NOTE, "Processing constants for " + fieldElement + " of type " + entityField); - enclosedFields.forEach((field, getter) -> { - boolean fieldIsIndexed = (field.getAnnotation(Indexed.class) != null) - || (field.getAnnotation(Searchable.class) != null); - boolean generateMetamodel = field.getAnnotation(Metamodel.class) != null; + final String entityFieldName = fieldElement.toString(); + messager.printMessage(Diagnostic.Kind.NOTE, "entityFieldName => " + entityFieldName); - if (fieldIsIndexed || generateMetamodel) { - List newChain = new ArrayList<>(chain); - newChain.add(field); - fieldMetamodels.addAll(processFieldMetamodel(entity, entityFieldName, newChain)); - } - }); + Map enclosedFields = getInstanceFields(entityField); - return fieldMetamodels; - } + messager.printMessage(Diagnostic.Kind.NOTE, "Enclosed subfield size() ==> " + enclosedFields.size()); - private Map getInstanceFields(Element element) { - if (objectTypeElement.equals(element)) { - return Collections.emptyMap(); - } + enclosedFields.forEach((field, getter) -> { + boolean fieldIsIndexed = (field.getAnnotation(Indexed.class) != null) || (field.getAnnotation( + Searchable.class) != null); + boolean generateMetamodel = field.getAnnotation(Metamodel.class) != null; - final Map getters = element.getEnclosedElements().stream() - .filter(ee -> ee.getKind() == ElementKind.METHOD) - // Only consider methods with no parameters - .filter(ee -> ee.getEnclosedElements().stream() - .noneMatch(eee -> eee.getKind() == ElementKind.PARAMETER)) - // Todo: Filter out methods that returns void or Void - .collect(Collectors.toMap(e -> e.getSimpleName().toString(), Function.identity())); - - final Set isGetters = getters.values().stream() - // todo: Filter out methods only returning boolean or Boolean - .map(Element::getSimpleName).map(Object::toString).filter(n -> n.startsWith(IS_PREFIX)) - .map(n -> n.substring(2)) - .map(ObjectUtils::toLowercaseFirstCharacter).collect(Collectors.toSet()); - - // Retrieve all declared non-final instance fields of the annotated class - Map results = element.getEnclosedElements().stream() - .filter(ee -> ee.getKind().isField() && !ee.getModifiers().contains(Modifier.STATIC) // Ignore static - // fields - && !ee.getModifiers().contains(Modifier.FINAL)) // Ignore final fields - .collect(Collectors.toMap(Function.identity(), - ee -> findGetter(ee, getters, isGetters, element.toString(), - lombokGetterAvailable(element, ee)))); - - Types types = processingEnvironment.getTypeUtils(); - List superTypes = types.directSupertypes(element.asType()); - superTypes.stream() - .map(types::asElement) - .filter(superElement -> superElement.getKind().isClass()) - .findFirst() - .ifPresent(superElement -> results.putAll(getInstanceFields(superElement))); - - return results; - } + if (fieldIsIndexed || generateMetamodel) { + List newChain = new ArrayList<>(chain); + newChain.add(field); + fieldMetamodels.addAll(processFieldMetamodel(entity, entityFieldName, newChain)); + } + }); - private Map getInstanceFields(TypeName entity) { - Element element = getElementFromTypeName(entity); - return getInstanceFields(element); - } + return fieldMetamodels; + } - private Element getElementFromTypeName(TypeName typeName) { - if (typeName instanceof ParameterizedTypeName parameterizedTypeName) { - return getElementFromTypeName(parameterizedTypeName.rawType); - } else if (typeName instanceof ClassName className) { - return processingEnvironment.getElementUtils().getTypeElement(className.reflectionName()); - } else { - throw new IllegalArgumentException("Unknown type name: " + typeName); - } + private Map getInstanceFields(Element element) { + if (objectTypeElement.equals(element)) { + return Collections.emptyMap(); } - private static final Set DISALLOWED_ACCESS_LEVELS = Stream.of("PROTECTED", "PRIVATE", "NONE") - .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); - - private boolean lombokGetterAvailable(Element classElement, Element fieldElement) { - final boolean globalEnable = isLombokAnnotated(classElement, "Data") - || isLombokAnnotated(classElement, "Getter"); - final boolean localEnable = isLombokAnnotated(fieldElement, "Getter"); - final boolean disallowedAccessLevel = DISALLOWED_ACCESS_LEVELS - .contains(getterAccessLevel(fieldElement).orElse("No access level defined")); - return !disallowedAccessLevel && (globalEnable || localEnable); + final Map getters = element.getEnclosedElements().stream() + .filter(ee -> ee.getKind() == ElementKind.METHOD) + // Only consider methods with no parameters + .filter(ee -> ee.getEnclosedElements().stream().noneMatch(eee -> eee.getKind() == ElementKind.PARAMETER)) + // Todo: Filter out methods that returns void or Void + .collect(Collectors.toMap(e -> e.getSimpleName().toString(), Function.identity())); + + final Set isGetters = getters.values().stream() + // todo: Filter out methods only returning boolean or Boolean + .map(Element::getSimpleName).map(Object::toString).filter(n -> n.startsWith(IS_PREFIX)).map(n -> n.substring(2)) + .map(ObjectUtils::toLowercaseFirstCharacter).collect(Collectors.toSet()); + + // Retrieve all declared non-final instance fields of the annotated class + Map results = element.getEnclosedElements().stream() + .filter(ee -> ee.getKind().isField() && !ee.getModifiers().contains(Modifier.STATIC) // Ignore static + // fields + && !ee.getModifiers().contains(Modifier.FINAL)) // Ignore final fields + .collect(Collectors.toMap(Function.identity(), + ee -> findGetter(ee, getters, isGetters, element.toString(), lombokGetterAvailable(element, ee)))); + + Types types = processingEnvironment.getTypeUtils(); + List superTypes = types.directSupertypes(element.asType()); + superTypes.stream().map(types::asElement).filter(superElement -> superElement.getKind().isClass()).findFirst() + .ifPresent(superElement -> results.putAll(getInstanceFields(superElement))); + + return results; + } + + private Map getInstanceFields(TypeName entity) { + Element element = getElementFromTypeName(entity); + return getInstanceFields(element); + } + + private Element getElementFromTypeName(TypeName typeName) { + if (typeName instanceof ParameterizedTypeName parameterizedTypeName) { + return getElementFromTypeName(parameterizedTypeName.rawType); + } else if (typeName instanceof ClassName className) { + return processingEnvironment.getElementUtils().getTypeElement(className.reflectionName()); + } else { + throw new IllegalArgumentException("Unknown type name: " + typeName); } - - private boolean isLombokAnnotated(final Element annotatedElement, final String lombokSimpleClassName) { - try { - final String className = "lombok." + lombokSimpleClassName; - @SuppressWarnings("unchecked") - final java.lang.Class clazz = (java.lang.Class) java.lang.Class - .forName(className); - return annotatedElement.getAnnotation(clazz) != null; - } catch (ClassNotFoundException ignored) { - // ignore - } - return false; + } + + private boolean lombokGetterAvailable(Element classElement, Element fieldElement) { + final boolean globalEnable = isLombokAnnotated(classElement, "Data") || isLombokAnnotated(classElement, "Getter"); + final boolean localEnable = isLombokAnnotated(fieldElement, "Getter"); + final boolean disallowedAccessLevel = DISALLOWED_ACCESS_LEVELS.contains( + getterAccessLevel(fieldElement).orElse("No access level defined")); + return !disallowedAccessLevel && (globalEnable || localEnable); + } + + private boolean isLombokAnnotated(final Element annotatedElement, final String lombokSimpleClassName) { + try { + final String className = "lombok." + lombokSimpleClassName; + @SuppressWarnings( + "unchecked" + ) final java.lang.Class clazz = (java.lang.Class) java.lang.Class.forName( + className); + return annotatedElement.getAnnotation(clazz) != null; + } catch (ClassNotFoundException ignored) { + // ignore } + return false; + } - private Optional getterAccessLevel(final Element fieldElement) { + private Optional getterAccessLevel(final Element fieldElement) { - final List mirrors = fieldElement.getAnnotationMirrors(); + final List mirrors = fieldElement.getAnnotationMirrors(); - Map map = mirrors.stream() - .filter(am -> "lombok.Getter".equals(am.getAnnotationType().toString())).findFirst() - .map(AnnotationMirror::getElementValues).orElse(Collections.emptyMap()); + Map map = mirrors.stream() + .filter(am -> "lombok.Getter".equals(am.getAnnotationType().toString())).findFirst() + .map(AnnotationMirror::getElementValues).orElse(Collections.emptyMap()); - return map.values().stream() // - .map(AnnotationValue::toString) - .map(v -> v.substring(v.lastIndexOf('.') + 1)) // Format as simple name - .filter(this::isAccessLevel).findFirst(); - } + return map.values().stream() // + .map(AnnotationValue::toString).map(v -> v.substring(v.lastIndexOf('.') + 1)) // Format as simple name + .filter(this::isAccessLevel).findFirst(); + } - private boolean isAccessLevel(String s) { - Set validAccessLevels = Stream.of("PACKAGE", "NONE", "PRIVATE", "MODULE", "PROTECTED", "PUBLIC") - .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); - return validAccessLevels.contains(s); - } + private boolean isAccessLevel(String s) { + Set validAccessLevels = Stream.of("PACKAGE", "NONE", "PRIVATE", "MODULE", "PROTECTED", "PUBLIC") + .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); + return validAccessLevels.contains(s); + } - private String findGetter(final Element field, final Map getters, final Set isGetters, - final String entityName, boolean lombokGetterAvailable) { + private String findGetter(final Element field, final Map getters, final Set isGetters, + final String entityName, boolean lombokGetterAvailable) { - final String fieldName = field.getSimpleName().toString(); - final String getterPrefix = isGetters.contains(fieldName) ? IS_PREFIX : GET_PREFIX; + final String fieldName = field.getSimpleName().toString(); + final String getterPrefix = isGetters.contains(fieldName) ? IS_PREFIX : GET_PREFIX; - final String standardJavaName = ObjectUtils.javaNameFromExternal(fieldName); + final String standardJavaName = ObjectUtils.javaNameFromExternal(fieldName); - final String standardGetterName = getterPrefix + standardJavaName; + final String standardGetterName = getterPrefix + standardJavaName; - final Element standardGetter = getters.get(standardGetterName); + final Element standardGetter = getters.get(standardGetterName); - if (standardGetter != null || lombokGetterAvailable) { - // We got lucky because the user elected to conform - // to the standard JavaBean notation. - return entityName + "::" + standardGetterName; - } + if (standardGetter != null || lombokGetterAvailable) { + // We got lucky because the user elected to conform + // to the standard JavaBean notation. + return entityName + "::" + standardGetterName; + } - final String lambdaName = ObjectUtils.toLowercaseFirstCharacter(entityName); + final String lambdaName = ObjectUtils.toLowercaseFirstCharacter(entityName); - if (!field.getModifiers().contains(Modifier.PROTECTED) && !field.getModifiers().contains(Modifier.PRIVATE)) { - // We can use a lambda. Great escape hatch! - return lambdaName + " -> " + lambdaName + "." + fieldName; - } + if (!field.getModifiers().contains(Modifier.PROTECTED) && !field.getModifiers().contains(Modifier.PRIVATE)) { + // We can use a lambda. Great escape hatch! + return lambdaName + " -> " + lambdaName + "." + fieldName; + } - // default to thrower - messager.printMessage(Diagnostic.Kind.ERROR, "Class " + entityName + " is not a proper JavaBean because " - + field.getSimpleName().toString() + " has no standard getter."); - return lambdaName + " -> {throw new " + IllegalJavaBeanException.class.getSimpleName() + "(" + entityName - + ".class, \"" + fieldName + "\");}"; + // default to thrower + messager.printMessage(Diagnostic.Kind.ERROR, + "Class " + entityName + " is not a proper JavaBean because " + field.getSimpleName() + .toString() + " has no standard getter."); + return lambdaName + " -> {throw new " + IllegalJavaBeanException.class.getSimpleName() + "(" + entityName + ".class, \"" + fieldName + "\");}"; + } + + private Triple generateFieldMetamodel( // + TypeName entity, // + List chain, // + String chainFieldName, // + TypeName entityField, // + Class interceptorClass, // + boolean fieldIsIndexed, // + String collectionPrefix, // + String searchSchemaAlias // + ) { + String fieldAccessor = ObjectUtils.staticField(chainFieldName); + + FieldSpec objectField = FieldSpec // + .builder(Field.class, chainFieldName).addModifiers(Modifier.PUBLIC, Modifier.STATIC) // + .build(); + + ObjectGraphFieldSpec ogf = new ObjectGraphFieldSpec(objectField, chain); + + TypeName interceptor = ParameterizedTypeName.get(ClassName.get(interceptorClass), entity, entityField); + + FieldSpec aField = FieldSpec // + .builder(interceptor, fieldAccessor).addModifiers(Modifier.PUBLIC, Modifier.STATIC) // + .build(); + + String alias; + if (!isEmpty(searchSchemaAlias)) { + alias = searchSchemaAlias; + } else { + alias = chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining("_")); + alias = collectionPrefix != null ? collectionPrefix + "_" + alias : alias; } - private Triple generateFieldMetamodel( // - TypeName entity, // - List chain, // - String chainFieldName, // - TypeName entityField, // - Class interceptorClass, // - boolean fieldIsIndexed, // - String collectionPrefix, // - String searchSchemaAlias // - ) { - String fieldAccessor = ObjectUtils.staticField(chainFieldName); - - FieldSpec objectField = FieldSpec // - .builder(Field.class, chainFieldName).addModifiers(Modifier.PUBLIC, Modifier.STATIC) // - .build(); - - ObjectGraphFieldSpec ogf = new ObjectGraphFieldSpec(objectField, chain); - - TypeName interceptor = ParameterizedTypeName.get(ClassName.get(interceptorClass), entity, entityField); - - FieldSpec aField = FieldSpec // - .builder(interceptor, fieldAccessor).addModifiers(Modifier.PUBLIC, Modifier.STATIC) // - .build(); - - String alias; - if (!isEmpty(searchSchemaAlias)) { - alias = searchSchemaAlias; - } else { - alias = chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining("_")); - alias = collectionPrefix != null ? collectionPrefix + "_" + alias : alias; - } + String jsonPath = chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining(".")); + jsonPath = "$." + (collectionPrefix != null ? collectionPrefix + "." + jsonPath : jsonPath); - String jsonPath = chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining(".")); - jsonPath = "$." + (collectionPrefix != null ? collectionPrefix + "." + jsonPath : jsonPath); - - CodeBlock aFieldInit = CodeBlock // - .builder() // - .addStatement( // - "$L = new $T(new $T(\"$L\", \"$L\", $L),$L)", // - fieldAccessor, // - interceptor, // - SearchFieldAccessor.class, // - alias, // - jsonPath, // - chainFieldName, // - fieldIsIndexed // - ) // - .build(); - - return Tuples.of(ogf, aField, aFieldInit); - } + CodeBlock aFieldInit = CodeBlock // + .builder() // + .addStatement( // + "$L = new $T(new $T(\"$L\", \"$L\", $L),$L)", // + fieldAccessor, // + interceptor, // + SearchFieldAccessor.class, // + alias, // + jsonPath, // + chainFieldName, // + fieldIsIndexed // + ) // + .build(); - private Triple generateFieldMetamodel( - List chain, // - String chainFieldName, // - TypeName interceptor // - ) { - String fieldAccessor = ObjectUtils.staticField(chainFieldName); + return Tuples.of(ogf, aField, aFieldInit); + } - FieldSpec objectField = FieldSpec.builder(Field.class, chainFieldName) - .addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .build(); - ObjectGraphFieldSpec ogf = new ObjectGraphFieldSpec(objectField, chain); + private Triple generateFieldMetamodel(List chain, // + String chainFieldName, // + TypeName interceptor // + ) { + String fieldAccessor = ObjectUtils.staticField(chainFieldName); - FieldSpec aField = FieldSpec.builder(interceptor, fieldAccessor).addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .build(); + FieldSpec objectField = FieldSpec.builder(Field.class, chainFieldName) + .addModifiers(Modifier.PUBLIC, Modifier.STATIC).build(); + ObjectGraphFieldSpec ogf = new ObjectGraphFieldSpec(objectField, chain); - String searchSchemaAlias = chain.stream().map(e -> e.getSimpleName().toString()) - .collect(Collectors.joining("_")); - String jsonPath = "$." + chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining(".")); + FieldSpec aField = FieldSpec.builder(interceptor, fieldAccessor).addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .build(); - CodeBlock aFieldInit = CodeBlock.builder() - .addStatement("$L = new $T(new $T(\"$L\", \"$L\", $L),$L)", fieldAccessor, interceptor, - SearchFieldAccessor.class, searchSchemaAlias, jsonPath, chainFieldName, - true) - .build(); + String searchSchemaAlias = chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining("_")); + String jsonPath = "$." + chain.stream().map(e -> e.getSimpleName().toString()).collect(Collectors.joining(".")); - return Tuples.of(ogf, aField, aFieldInit); - } + CodeBlock aFieldInit = CodeBlock.builder() + .addStatement("$L = new $T(new $T(\"$L\", \"$L\", $L),$L)", fieldAccessor, interceptor, SearchFieldAccessor.class, + searchSchemaAlias, jsonPath, chainFieldName, true).build(); - private Pair generateUnboundMetamodelField(TypeName entity, String name, String alias, - Class type) { - TypeName interceptor = ParameterizedTypeName.get(ClassName.get(MetamodelField.class), entity, - TypeName.get(type)); + return Tuples.of(ogf, aField, aFieldInit); + } - FieldSpec aField = FieldSpec.builder(interceptor, name).addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .build(); + private Pair generateUnboundMetamodelField(TypeName entity, String name, String alias, + Class type) { + TypeName interceptor = ParameterizedTypeName.get(ClassName.get(MetamodelField.class), entity, TypeName.get(type)); - CodeBlock aFieldInit = CodeBlock.builder() - .addStatement("$L = new $T(\"$L\", $T.class, $L)", name, interceptor, alias, type, true).build(); + FieldSpec aField = FieldSpec.builder(interceptor, name).addModifiers(Modifier.PUBLIC, Modifier.STATIC).build(); - return Tuples.of(aField, aFieldInit); - } + CodeBlock aFieldInit = CodeBlock.builder() + .addStatement("$L = new $T(\"$L\", $T.class, $L)", name, interceptor, alias, type, true).build(); - private Pair generateThisMetamodelField(TypeName entity) { - String name = "_THIS"; - String alias = "__this"; - TypeName interceptor = ParameterizedTypeName.get(ClassName.get(MetamodelField.class), entity, - entity); + return Tuples.of(aField, aFieldInit); + } - FieldSpec aField = FieldSpec.builder(interceptor, name).addModifiers(Modifier.PUBLIC, Modifier.STATIC) - .build(); + private Pair generateThisMetamodelField(TypeName entity) { + String name = "_THIS"; + String alias = "__this"; + TypeName interceptor = ParameterizedTypeName.get(ClassName.get(MetamodelField.class), entity, entity); - CodeBlock aFieldInit = CodeBlock.builder() - .addStatement("$L = new $T(\"$L\", $T.class, $L)", name, interceptor, alias, entity, true).build(); + FieldSpec aField = FieldSpec.builder(interceptor, name).addModifiers(Modifier.PUBLIC, Modifier.STATIC).build(); - return Tuples.of(aField, aFieldInit); - } + CodeBlock aFieldInit = CodeBlock.builder() + .addStatement("$L = new $T(\"$L\", $T.class, $L)", name, interceptor, alias, entity, true).build(); - private boolean isEnum(ProcessingEnvironment processingEnv, TypeMirror typeMirror) { - Types typeUtils = processingEnv.getTypeUtils(); + return Tuples.of(aField, aFieldInit); + } - Element element = typeUtils.asElement(typeMirror); - if (element != null) { - return element.getKind() == ElementKind.ENUM; - } else { - return false; - } + private boolean isEnum(ProcessingEnvironment processingEnv, TypeMirror typeMirror) { + Types typeUtils = processingEnv.getTypeUtils(); + + Element element = typeUtils.asElement(typeMirror); + if (element != null) { + return element.getKind() == ElementKind.ENUM; + } else { + return false; } + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelUtils.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelUtils.java index f250bcfd..ac0fbb93 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelUtils.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/MetamodelUtils.java @@ -9,7 +9,7 @@ import java.util.Optional; public class MetamodelUtils { - public static MetamodelField getMetamodelForIdField(Class entityClass) { + public static MetamodelField getMetamodelForIdField(Class entityClass) { Optional idField = ObjectUtils.getIdFieldForEntityClass(entityClass); if (idField.isPresent()) { try { @@ -24,11 +24,12 @@ public static MetamodelField getMetamodelForIdField(Class entityClass) { return null; } - public static List> getMetamodelFieldsForProperties(Class entityClass, Collection properties) { - List> result = new ArrayList<>(); + public static List> getMetamodelFieldsForProperties(Class entityClass, + Collection properties) { + List> result = new ArrayList<>(); try { Class metamodel = Class.forName(entityClass.getName() + "$"); - for (var property: properties) { + for (var property : properties) { try { result.add((MetamodelField) metamodel.getField(ObjectUtils.staticField(property)).get(null)); } catch (IllegalAccessException | NoSuchFieldException e) { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/SearchFieldAccessor.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/SearchFieldAccessor.java index bd012875..dd97b7bb 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/SearchFieldAccessor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/SearchFieldAccessor.java @@ -12,7 +12,6 @@ public class SearchFieldAccessor { private final Class targetClass; private final Class declaringClass; - public SearchFieldAccessor(String searchAlias, String jsonPath, Field... fields) { this.searchAlias = searchAlias; this.jsonPath = jsonPath; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/DateField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/DateField.java index 6162e9bf..a7bf6c29 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/DateField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/DateField.java @@ -9,33 +9,33 @@ public class DateField extends MetamodelField { public DateField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - - public EqualPredicate eq(T value) { - return new EqualPredicate<>(searchFieldAccessor,value); + + public EqualPredicate eq(T value) { + return new EqualPredicate<>(searchFieldAccessor, value); } - - public NotEqualPredicate notEq(T value) { - return new NotEqualPredicate<>(searchFieldAccessor,value); + + public NotEqualPredicate notEq(T value) { + return new NotEqualPredicate<>(searchFieldAccessor, value); } - - public GreaterThanPredicate after(T value) { - return new GreaterThanPredicate<>(searchFieldAccessor,value); + + public GreaterThanPredicate after(T value) { + return new GreaterThanPredicate<>(searchFieldAccessor, value); } - - public GreaterThanOrEqualPredicate onOrAfter(T value) { - return new GreaterThanOrEqualPredicate<>(searchFieldAccessor,value); + + public GreaterThanOrEqualPredicate onOrAfter(T value) { + return new GreaterThanOrEqualPredicate<>(searchFieldAccessor, value); } - - public LessThanPredicate before(T value) { - return new LessThanPredicate<>(searchFieldAccessor,value); + + public LessThanPredicate before(T value) { + return new LessThanPredicate<>(searchFieldAccessor, value); } - - public LessThanOrEqualPredicate onOrBefore(T value) { - return new LessThanOrEqualPredicate<>(searchFieldAccessor,value); + + public LessThanOrEqualPredicate onOrBefore(T value) { + return new LessThanOrEqualPredicate<>(searchFieldAccessor, value); } - - public BetweenPredicate between(T min, T max) { - return new BetweenPredicate<>(searchFieldAccessor,min,max); + + public BetweenPredicate between(T min, T max) { + return new BetweenPredicate<>(searchFieldAccessor, min, max); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/GeoField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/GeoField.java index f34dc42d..a7a5c7af 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/GeoField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/GeoField.java @@ -14,37 +14,37 @@ public class GeoField extends MetamodelField { public GeoField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - - public EqualPredicate eq(T value) { - return new EqualPredicate<>(searchFieldAccessor,value); + + public EqualPredicate eq(T value) { + return new EqualPredicate<>(searchFieldAccessor, value); } - - public EqualPredicate eq(String xy) { - return new EqualPredicate<>(searchFieldAccessor,xy); + + public EqualPredicate eq(String xy) { + return new EqualPredicate<>(searchFieldAccessor, xy); } - - public EqualPredicate eq(double x, double y) { + + public EqualPredicate eq(double x, double y) { return new EqualPredicate<>(searchFieldAccessor, x, y); } - - public NotEqualPredicate notEq(T value) { - return new NotEqualPredicate<>(searchFieldAccessor,value); + + public NotEqualPredicate notEq(T value) { + return new NotEqualPredicate<>(searchFieldAccessor, value); } - - public NotEqualPredicate notEq(String xy) { - return new NotEqualPredicate<>(searchFieldAccessor,xy); + + public NotEqualPredicate notEq(String xy) { + return new NotEqualPredicate<>(searchFieldAccessor, xy); } - - public NotEqualPredicate notEq(double x, double y) { + + public NotEqualPredicate notEq(double x, double y) { return new NotEqualPredicate<>(searchFieldAccessor, x, y); } - - public NearPredicate near(Point point, Distance distance) { - return new NearPredicate<>(searchFieldAccessor,point,distance); + + public NearPredicate near(Point point, Distance distance) { + return new NearPredicate<>(searchFieldAccessor, point, distance); } - - public OutsideOfPredicate outsideOf(Point point, Distance distance) { - return new OutsideOfPredicate<>(searchFieldAccessor,point,distance); + + public OutsideOfPredicate outsideOf(Point point, Distance distance) { + return new OutsideOfPredicate<>(searchFieldAccessor, point, distance); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/NumericField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/NumericField.java index 4f8c9f45..286f1190 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/NumericField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/NumericField.java @@ -13,35 +13,35 @@ public class NumericField extends MetamodelField { public NumericField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - - public EqualPredicate eq(T value) { - return new EqualPredicate<>(searchFieldAccessor,value); + + public EqualPredicate eq(T value) { + return new EqualPredicate<>(searchFieldAccessor, value); } - - public NotEqualPredicate notEq(T value) { - return new NotEqualPredicate<>(searchFieldAccessor,value); + + public NotEqualPredicate notEq(T value) { + return new NotEqualPredicate<>(searchFieldAccessor, value); } - - public GreaterThanPredicate gt(T value) { - return new GreaterThanPredicate<>(searchFieldAccessor,value); + + public GreaterThanPredicate gt(T value) { + return new GreaterThanPredicate<>(searchFieldAccessor, value); } - - public GreaterThanOrEqualPredicate ge(T value) { - return new GreaterThanOrEqualPredicate<>(searchFieldAccessor,value); + + public GreaterThanOrEqualPredicate ge(T value) { + return new GreaterThanOrEqualPredicate<>(searchFieldAccessor, value); } - - public LessThanPredicate lt(T value) { - return new LessThanPredicate<>(searchFieldAccessor,value); + + public LessThanPredicate lt(T value) { + return new LessThanPredicate<>(searchFieldAccessor, value); } - - public LessThanOrEqualPredicate le(T value) { - return new LessThanOrEqualPredicate<>(searchFieldAccessor,value); + + public LessThanOrEqualPredicate le(T value) { + return new LessThanOrEqualPredicate<>(searchFieldAccessor, value); } - - public BetweenPredicate between(T min, T max) { - return new BetweenPredicate<>(searchFieldAccessor,min,max); + + public BetweenPredicate between(T min, T max) { + return new BetweenPredicate<>(searchFieldAccessor, min, max); } - + @SuppressWarnings("unchecked") public InPredicate in(T... values) { return new InPredicate<>(searchFieldAccessor, Arrays.asList(values)); @@ -50,7 +50,7 @@ public BetweenPredicate between(T min, T max) { public Consumer incrBy(Long value) { return new NumIncrByAction<>(searchFieldAccessor, value); } - + public Consumer decrBy(Long value) { return new NumIncrByAction<>(searchFieldAccessor, -value); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/ReferenceField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/ReferenceField.java index 4981b7e9..46de1749 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/ReferenceField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/ReferenceField.java @@ -10,11 +10,11 @@ public ReferenceField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - public EqualPredicate eq(T value) { - return new EqualPredicate<>(searchFieldAccessor,value); + public EqualPredicate eq(T value) { + return new EqualPredicate<>(searchFieldAccessor, value); } - public NotEqualPredicate notEq(T value) { - return new NotEqualPredicate<>(searchFieldAccessor,value); + public NotEqualPredicate notEq(T value) { + return new NotEqualPredicate<>(searchFieldAccessor, value); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextField.java index e8c96c8f..d6fee236 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextField.java @@ -15,47 +15,48 @@ public class TextField extends MetamodelField { public TextField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - - public EqualPredicate eq(T value) { - return new EqualPredicate<>(searchFieldAccessor,value); + + public EqualPredicate eq(T value) { + return new EqualPredicate<>(searchFieldAccessor, value); } - - public NotEqualPredicate notEq(T value) { - return new NotEqualPredicate<>(searchFieldAccessor,value); + + public NotEqualPredicate notEq(T value) { + return new NotEqualPredicate<>(searchFieldAccessor, value); } - - public StartsWithPredicate startsWith(T value) { - return new StartsWithPredicate<>(searchFieldAccessor,value); + + public StartsWithPredicate startsWith(T value) { + return new StartsWithPredicate<>(searchFieldAccessor, value); } - public EndsWithPredicate endsWith(T value) { - return new EndsWithPredicate<>(searchFieldAccessor,value); + + public EndsWithPredicate endsWith(T value) { + return new EndsWithPredicate<>(searchFieldAccessor, value); } - - public LikePredicate like(T value) { - return new LikePredicate<>(searchFieldAccessor,value); + + public LikePredicate like(T value) { + return new LikePredicate<>(searchFieldAccessor, value); } - - public NotLikePredicate notLike(T value) { - return new NotLikePredicate<>(searchFieldAccessor,value); + + public NotLikePredicate notLike(T value) { + return new NotLikePredicate<>(searchFieldAccessor, value); } - - public ContainingPredicate containing(T value) { - return new ContainingPredicate<>(searchFieldAccessor,value); + + public ContainingPredicate containing(T value) { + return new ContainingPredicate<>(searchFieldAccessor, value); } - - public NotContainingPredicate notContaining(T value) { - return new NotContainingPredicate<>(searchFieldAccessor,value); + + public NotContainingPredicate notContaining(T value) { + return new NotContainingPredicate<>(searchFieldAccessor, value); } @SuppressWarnings("unchecked") public InPredicate in(T... values) { return new InPredicate<>(searchFieldAccessor, Arrays.asList(values)); } - + public Consumer append(String value) { return new StringAppendAction<>(searchFieldAccessor, value); } - + public ToLongFunction length() { return new StrLengthAction<>(searchFieldAccessor); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextTagField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextTagField.java index cc9aa759..3896dc61 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextTagField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/TextTagField.java @@ -15,12 +15,12 @@ public TextTagField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - public StartsWithPredicate startsWith(T value) { - return new StartsWithPredicate<>(searchFieldAccessor,value); + public StartsWithPredicate startsWith(T value) { + return new StartsWithPredicate<>(searchFieldAccessor, value); } - public EndsWithPredicate endsWith(T value) { - return new EndsWithPredicate<>(searchFieldAccessor,value); + public EndsWithPredicate endsWith(T value) { + return new EndsWithPredicate<>(searchFieldAccessor, value); } public Consumer append(String value) { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/VectorField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/VectorField.java index c038181a..ce9e7192 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/VectorField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/indexed/VectorField.java @@ -4,16 +4,16 @@ import com.redis.om.spring.metamodel.SearchFieldAccessor; import com.redis.om.spring.search.stream.predicates.vector.KNNPredicate; -public class VectorField extends MetamodelField { +public class VectorField extends MetamodelField { public VectorField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } - public KNNPredicate knn(int k, byte[] blobAttribute) { - return new KNNPredicate<>(searchFieldAccessor,k, blobAttribute); + public KNNPredicate knn(int k, byte[] blobAttribute) { + return new KNNPredicate<>(searchFieldAccessor, k, blobAttribute); } - public KNNPredicate knn(int k, float[] blobAttribute) { - return new KNNPredicate<>(searchFieldAccessor,k, blobAttribute); + public KNNPredicate knn(int k, float[] blobAttribute) { + return new KNNPredicate<>(searchFieldAccessor, k, blobAttribute); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedNumericField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedNumericField.java index 37dedfc8..175161f1 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedNumericField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedNumericField.java @@ -15,7 +15,7 @@ public NonIndexedNumericField(SearchFieldAccessor field, boolean indexed) { public Consumer incrBy(Long value) { return new NumIncrByAction<>(searchFieldAccessor, value); } - + public Consumer decrBy(Long value) { return new NumIncrByAction<>(searchFieldAccessor, -value); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedTextField.java b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedTextField.java index 00628180..4089653c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedTextField.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/metamodel/nonindexed/NonIndexedTextField.java @@ -10,7 +10,6 @@ public class NonIndexedTextField extends MetamodelField { - public NonIndexedTextField(SearchFieldAccessor field, boolean indexed) { super(field, indexed); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/RedisModulesOperations.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/RedisModulesOperations.java index 82d4ee94..8311ad0c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/RedisModulesOperations.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/RedisModulesOperations.java @@ -9,7 +9,8 @@ import com.redis.om.spring.ops.search.SearchOperationsImpl; import org.springframework.data.redis.core.StringRedisTemplate; -public record RedisModulesOperations(RedisModulesClient client, StringRedisTemplate template, GsonBuilder gsonBuilder) { +public record RedisModulesOperations(RedisModulesClient client, StringRedisTemplate template, + GsonBuilder gsonBuilder) { public JSONOperations opsForJSON() { return new JSONOperationsImpl<>(client, gsonBuilder); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/json/JSONOperationsImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/json/JSONOperationsImpl.java index f9cb6cfe..b804b7ae 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/json/JSONOperationsImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/json/JSONOperationsImpl.java @@ -15,9 +15,9 @@ public class JSONOperationsImpl implements JSONOperations { - private Gson gson; private final GsonBuilder builder; private final RedisModulesClient client; + private Gson gson; public JSONOperationsImpl(RedisModulesClient client, GsonBuilder builder) { this.client = client; @@ -32,11 +32,11 @@ public Long del(K key, Path2 path) { @Nullable @Override public String get(K key) { - var result = client.clientForJSON().jsonGet(key.toString()); + var result = client.clientForJSON().jsonGet(key.toString(), Path2.ROOT_PATH); if (result instanceof JSONArray jsonArray) { return !jsonArray.isEmpty() ? jsonArray.get(0).toString() : null; - } else if (result instanceof LinkedTreeMap linkedTreeMap) { - return getGson().toJson(result); + } else if (result instanceof LinkedTreeMap linkedTreeMap) { + return getGson().toJson(linkedTreeMap); } else { return result.toString(); } @@ -53,8 +53,8 @@ public T get(K key, Class clazz, Path2 path) { String asString; if (result instanceof JSONArray jsonArray) { return extractValueAsClassFromJSONArray(jsonArray, clazz); - } else if (result instanceof LinkedTreeMap linkedTreeMap) { - asString = getGson().toJson(result); + } else if (result instanceof LinkedTreeMap linkedTreeMap) { + asString = getGson().toJson(linkedTreeMap); } else { asString = result != null ? result.toString() : null; } @@ -65,34 +65,30 @@ public T get(K key, Class clazz, Path2 path) { @SafeVarargs @Override public final List mget(K... keys) { - return (keys.length > 0) ? client.clientForJSON().jsonMGet(getKeysAsString(keys)) - .stream() - .filter(Objects::nonNull) - .map(jsonArr -> jsonArr.get(0)) - .map(Object::toString) - .toList() : List.of(); + return (keys.length > 0) ? + client.clientForJSON().jsonMGet(getKeysAsString(keys)).stream().filter(Objects::nonNull) + .map(jsonArr -> jsonArr.get(0)).map(Object::toString).toList() : + List.of(); } - @SafeVarargs @Override + @SafeVarargs + @Override public final List mget(Class clazz, K... keys) { Gson g = getGson(); - return (keys.length > 0) ? client.clientForJSON().jsonMGet(getKeysAsString(keys)) - .stream() - .filter(Objects::nonNull) - .map(jsonArr -> jsonArr.get(0)) - .map(Object::toString) - .map(str -> g.fromJson(str, clazz)) - .toList() : List.of(); + return (keys.length > 0) ? + client.clientForJSON().jsonMGet(getKeysAsString(keys)).stream().filter(Objects::nonNull) + .map(jsonArr -> jsonArr.get(0)).map(Object::toString).map(str -> g.fromJson(str, clazz)).toList() : + List.of(); } - @SafeVarargs @Override + @SafeVarargs + @Override public final List mget(Path2 path, Class clazz, K... keys) { Gson g = getGson(); - return (keys.length > 0) ? client.clientForJSON().jsonMGet(path, getKeysAsString(keys)) - .stream() - .map(Object::toString) - .map(str -> g.fromJson(str, clazz)) - .toList() : List.of(); + return (keys.length > 0) ? + client.clientForJSON().jsonMGet(path, getKeysAsString(keys)).stream().map(Object::toString) + .map(str -> g.fromJson(str, clazz)).toList() : + List.of(); } @Override @@ -162,20 +158,14 @@ public List arrLen(K key, Path2 path) { @Override public List arrPop(K key, Class clazz, Path2 path, Integer index) { - return client.clientForJSON().jsonArrPop(key.toString(), path, index) - .stream() - .map(Object::toString) - .map(str -> getGson().fromJson(str, clazz)) - .toList(); + return client.clientForJSON().jsonArrPop(key.toString(), path, index).stream().map(Object::toString) + .map(str -> getGson().fromJson(str, clazz)).toList(); } @Override public List arrPop(K key, Class clazz, Path2 path) { - return client.clientForJSON().jsonArrPop(key.toString(), path) - .stream() - .map(Object::toString) - .map(str -> getGson().fromJson(str, clazz)) - .toList(); + return client.clientForJSON().jsonArrPop(key.toString(), path).stream().map(Object::toString) + .map(str -> getGson().fromJson(str, clazz)).toList(); } @Override @@ -212,7 +202,7 @@ private T extractValueAsClassFromJSONArray(JSONArray jsonArray, Class cla case "String" -> element.equals("null") ? null : (T) element; case "Integer" -> (T) Integer.valueOf(element); case "Long" -> (T) Long.valueOf(element); - case "Long[]" -> (T) jsonArray.toList().stream().map(e -> Long.valueOf(e.toString())).toArray(Long[]::new); + case "Long[]" -> (T) jsonArray.toList().stream().map(e -> Long.valueOf(e.toString())).toArray(Long[]::new); case "Double" -> (T) Double.valueOf(element); case "Boolean" -> (T) Boolean.valueOf(element); default -> getGson().fromJson(element, clazz); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/BloomOperations.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/BloomOperations.java index b89fb220..d45681ef 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/BloomOperations.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/BloomOperations.java @@ -8,17 +8,19 @@ public interface BloomOperations { /** * Reserve a bloom filter. - * @param name The key of the filter - * @param initCapacity Optimize for this many items - * @param errorRate The desired rate of false positives * - * Note that if a filter is not reserved, a new one is created when is called. + * @param name The key of the filter + * @param initCapacity Optimize for this many items + * @param errorRate The desired rate of false positives + *

+ * Note that if a filter is not reserved, a new one is created when is called. */ void createFilter(K name, long initCapacity, double errorRate); /** * Adds an item to the filter - * @param name The name of the filter + * + * @param name The name of the filter * @param value The value to add to the filter * @return true if the item was not previously in the filter. */ @@ -27,27 +29,29 @@ public interface BloomOperations { /** * add one or more items to the bloom filter, by default creating it if it does not yet exist * - * @param name The name of the filter + * @param name The name of the filter * @param options {@link BFInsertParams} - * @param items items to add to the filter + * @param items items to add to the filter * @return List of booleans, true for each successful insertion */ List insert(K name, BFInsertParams options, String... items); /** * Add one or more items to a filter - * @param name Name of the filter + * + * @param name Name of the filter * @param values values to add to the filter. * @return An array of booleans of the same length as the number of values. * Each boolean values indicates whether the corresponding element was previously in the * filter or not. A true value means the item did not previously exist, whereas a * false value means it may have previously existed. */ - List addMulti(K name, String ...values); + List addMulti(K name, String... values); /** * Check if an item exists in the filter - * @param name Name (key) of the filter + * + * @param name Name (key) of the filter * @param value Value to check for * @return true if the item may exist in the filter, false if the item does not exist in the filter */ @@ -55,14 +59,16 @@ public interface BloomOperations { /** * Check if one or more items exist in the filter - * @param name Name of the filter to check + * + * @param name Name of the filter to check * @param values values to check for * @return An array of booleans. A true value means the corresponding value may exist, false means it does not exist */ - List existsMulti(K name, String ...values); + List existsMulti(K name, String... values); /** * Get information about the filter + * * @param name the name of the filter * @return Return information */ diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperations.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperations.java index 13bd4400..290aa6f6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperations.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperations.java @@ -6,7 +6,7 @@ public interface CountMinSketchOperations { /** * CMS.INITBYDIM Initializes a Count-Min Sketch to dimensions specified by user. - * + * * @param key The name of the sketch * @param width Number of counter in each array. Reduces the error size * @param depth Number of counter-arrays. Reduces the probability for an error @@ -17,7 +17,7 @@ public interface CountMinSketchOperations { /** * CMS.INITBYPROB Initializes a Count-Min Sketch to accommodate requested * capacity. - * + * * @param key The name of the sketch. * @param error Estimate size of error. The error is a percent of total * counted items. This effects the width of the sketch. @@ -32,7 +32,7 @@ public interface CountMinSketchOperations { /** * CMS.INCRBY Increases the count of item by increment - * + * * @param key The name of the sketch * @param item The item which counter to be increased * @param increment Counter to be increased by this integer @@ -42,7 +42,7 @@ public interface CountMinSketchOperations { /** * CMS.INCRBY Increases the count of one or more item. - * + * * @param key The name of the sketch * @param itemIncrements a Map of the items to be increased and their integer * increment @@ -53,7 +53,7 @@ public interface CountMinSketchOperations { /** * CMS.QUERY Returns count for item. Multiple items can be queried with one * call. - * + * * @param key The name of the sketch * @param items The items for which to retrieve the counts * @return Count for one or more items @@ -63,7 +63,7 @@ public interface CountMinSketchOperations { /** * CMS.MERGE Merges several sketches into one sketch. All sketches must have * identical width and depth. - * + * * @param destKey The name of destination sketch. Must be initialized. * @param keys The sketches to be merged */ @@ -74,7 +74,7 @@ public interface CountMinSketchOperations { * CMS.MERGE Merges several sketches into one sketch. All sketches must have * identical width and depth. Weights can be used to multiply certain sketches. * Default weight is 1. - * + * * @param destKey The name of destination sketch. Must be initialized. * @param keysAndWeights A map of keys and weights used to multiply the sketch. */ @@ -82,7 +82,7 @@ public interface CountMinSketchOperations { /** * CMS.INFO Returns width, depth and total count of the sketch. - * + * * @param key The name of the sketch * @return A Map with width, depth and total count. */ diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperationsImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperationsImpl.java index 3cf7e9f3..15aec51c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperationsImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CountMinSketchOperationsImpl.java @@ -43,18 +43,18 @@ public List cmsQuery(K key, String... items) { @Override public void cmsMerge(K destKey, K... keys) { client.clientForCMS().cmsMerge( // - destKey.toString(), // - Arrays.stream(keys).map(Object::toString).toArray(String[]::new)); + destKey.toString(), // + Arrays.stream(keys).map(Object::toString).toArray(String[]::new)); } @Override public void cmsMerge(K destKey, Map keysAndWeights) { client.clientForCMS().cmsMerge( // - destKey.toString(), // - keysAndWeights // - .entrySet() // - .stream() // - .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue))); + destKey.toString(), // + keysAndWeights // + .entrySet() // + .stream() // + .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue))); } @Override diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CuckooFilterOperations.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CuckooFilterOperations.java index 98f3eccd..05f2b2ee 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CuckooFilterOperations.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/pds/CuckooFilterOperations.java @@ -8,18 +8,32 @@ public interface CuckooFilterOperations { void createFilter(String key, long capacity); + void createFilter(String key, long capacity, CFReserveParams reserveParams); + boolean add(String key, String item); + boolean addNx(String key, String item); + List insert(String key, String... items); + List insert(String key, CFInsertParams insertParams, String... items); + List insertNx(String key, String... items); + List insertNx(String key, CFInsertParams insertParams, String... items); + boolean exists(String key, String item); + List exists(String key, String... items); + boolean delete(String key, String item); + long count(String key, String item); + Map.Entry scanDump(String key, long iterator); + String loadChunk(String key, long iterator, byte[] data); + Map info(String key); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperations.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperations.java index 0bd9ddd4..f0744dcd 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperations.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperations.java @@ -14,31 +14,57 @@ public interface SearchOperations { String createIndex(Schema schema, IndexOptions options); + String createIndex(FTCreateParams params, List fields); + SearchResult search(Query q); + SearchResult search(Query q, FTSearchParams params); + AggregationResult aggregate(AggregationBuilder q); + String cursorDelete(long cursorId); + AggregationResult cursorRead(long cursorId, int count); + String explain(Query q); + Map getInfo(); + String dropIndex(); + String dropIndexAndDocuments(); + Long addSuggestion(String key, String suggestion); + Long addSuggestion(String key, String suggestion, double score); + List getSuggestion(String key, String prefix); + List getSuggestion(String key, String prefix, AutoCompleteOptions options); + Boolean deleteSuggestion(String key, String entry); + Long getSuggestionLength(String key); + String alterIndex(SchemaField... fields); + String setConfig(String option, String value); + Map getConfig(String option); + Map getIndexConfig(String option); + String addAlias(String name); + String updateAlias(String name); + String deleteAlias(String name); - String updateSynonym(String synonymGroupId, String ...terms); + + String updateSynonym(String synonymGroupId, String... terms); + Map> dumpSynonym(); + Set tagVals(String value); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperationsImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperationsImpl.java index 471b9f1f..5d5bbb0a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperationsImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/ops/search/SearchOperationsImpl.java @@ -97,11 +97,12 @@ public Long addSuggestion(String key, String suggestion, double score) { } @Override - public List getSuggestion(String key,String prefix) { + public List getSuggestion(String key, String prefix) { return this.getSuggestion(key, prefix, AutoCompleteOptions.get()); } - @Override public List getSuggestion(String key, String prefix, AutoCompleteOptions options) { + @Override + public List getSuggestion(String key, String prefix, AutoCompleteOptions options) { Gson gson = modulesClient.gsonBuilder().create(); if (options.isWithScore()) { @@ -109,10 +110,12 @@ public List getSuggestion(String key,String prefix) { return suggestions.stream().map(suggestion -> { if (options.isWithPayload()) { String[] keyParts = key.split(":"); - String payLoadKey = String.format("sugg:payload:%s:%s", keyParts[keyParts.length - 2], keyParts[keyParts.length - 1]); + String payLoadKey = String.format("sugg:payload:%s:%s", keyParts[keyParts.length - 2], + keyParts[keyParts.length - 1]); Object payload = template.opsForHash().get(payLoadKey, suggestion); String json = payload != null ? payload.toString() : "{}"; - Map payloadMap = gson.fromJson(json, new TypeToken>() {}.getType()); + Map payloadMap = gson.fromJson(json, new TypeToken>() { + }.getType()); return new Suggestion(suggestion.getElement(), suggestion.getScore(), payloadMap); } else { return new Suggestion(suggestion.getElement(), suggestion.getScore()); @@ -123,10 +126,12 @@ public List getSuggestion(String key,String prefix) { return suggestions.stream().map(suggestion -> { if (options.isWithPayload()) { String[] keyParts = key.split(":"); - String payLoadKey = String.format("sugg:payload:%s:%s", keyParts[keyParts.length - 2], keyParts[keyParts.length - 1]); + String payLoadKey = String.format("sugg:payload:%s:%s", keyParts[keyParts.length - 2], + keyParts[keyParts.length - 1]); Object payload = template.opsForHash().get(payLoadKey, suggestion); String json = payload != null ? payload.toString() : "{}"; - Map payloadMap = gson.fromJson(json, new TypeToken>() {}.getType()); + Map payloadMap = gson.fromJson(json, new TypeToken>() { + }.getType()); return new Suggestion(suggestion, payloadMap); } else { return new Suggestion(suggestion); @@ -156,7 +161,7 @@ public String setConfig(String option, String value) { } @Override - public Map getConfig(String option) { + public Map getConfig(String option) { return search.ftConfigGet(option); } @@ -195,6 +200,4 @@ public Set tagVals(String field) { return search.ftTagVals(index.toString(), field); } - - } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisEnhancedRepositoriesRegistrar.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisEnhancedRepositoriesRegistrar.java index b02c8640..d88158e2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisEnhancedRepositoriesRegistrar.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisEnhancedRepositoriesRegistrar.java @@ -7,7 +7,7 @@ import java.lang.annotation.Annotation; -public class RedisEnhancedRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport { +public class RedisEnhancedRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport { /* * (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getAnnotation() diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoriesRegistrar.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoriesRegistrar.java index 7f8b2c50..03b956ce 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoriesRegistrar.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoriesRegistrar.java @@ -9,7 +9,7 @@ public class RedisJSONRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport { /* (non-Javadoc) - * + * * @see org.springframework.data.repository.config. * RepositoryBeanDefinitionRegistrarSupport#getAnnotation() */ @Override @@ -18,7 +18,7 @@ protected Class getAnnotation() { } /* (non-Javadoc) - * + * * @see org.springframework.data.repository.config. * RepositoryBeanDefinitionRegistrarSupport#getExtension() */ @Override diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoryConfigurationExtension.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoryConfigurationExtension.java index 7a78524a..995978be 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoryConfigurationExtension.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/configuration/RedisJSONRepositoryConfigurationExtension.java @@ -14,7 +14,7 @@ public class RedisJSONRepositoryConfigurationExtension extends RedisRepositoryConfigurationExtension { private static final String REDIS_ADAPTER_BEAN_NAME = "redisJSONKeyValueAdapter"; - + /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension#getModuleName() @@ -23,7 +23,7 @@ public class RedisJSONRepositoryConfigurationExtension extends RedisRepositoryCo public String getModuleName() { return "RedisJSON"; } - + /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension#getModulePrefix() @@ -32,7 +32,7 @@ public String getModuleName() { protected String getModulePrefix() { return "rejson"; } - + /* * (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getIdentifyingTypes() @@ -41,21 +41,21 @@ protected String getModulePrefix() { protected Collection> getIdentifyingTypes() { return Collections.singleton(RedisDocumentRepository.class); } - + /* * (non-Javadoc) * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension#getDefaultKeyValueTemplateBeanDefinition(org.springframework.data.repository.config.RepositoryConfigurationSource) */ @Override protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition( - RepositoryConfigurationSource configurationSource) { + RepositoryConfigurationSource configurationSource) { return BeanDefinitionBuilder.rootBeanDefinition(CustomRedisKeyValueTemplate.class) // - .addConstructorArgReference(REDIS_ADAPTER_BEAN_NAME) // - .addConstructorArgReference(MAPPING_CONTEXT_BEAN_NAME) // - .getBeanDefinition(); + .addConstructorArgReference(REDIS_ADAPTER_BEAN_NAME) // + .addConstructorArgReference(MAPPING_CONTEXT_BEAN_NAME) // + .getBeanDefinition(); } - + /* * (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getIdentifyingAnnotations() diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/QueryUtils.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/QueryUtils.java index ae6becd5..758230b3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/QueryUtils.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/QueryUtils.java @@ -5,12 +5,15 @@ public class QueryUtils { public static final Set TAG_ESCAPE_CHARS = Set.of( // - ',', '.', '<', '>', '{', '}', '[', // - ']', '"', '\'', ':', ';', '!', '@', // - '#', '$', '%', '^', '&', '*', '(', // - ')', '-', '+', '=', '~', '|', '/' // + ',', '.', '<', '>', '{', '}', '[', // + ']', '"', '\'', ':', ';', '!', '@', // + '#', '$', '%', '^', '&', '*', '(', // + ')', '-', '+', '=', '~', '|', '/' // ); - + + private QueryUtils() { + } + public static String escape(String text) { return escape(text, false); } @@ -31,23 +34,21 @@ public static String escape(String text, boolean querying) { return sb.toString(); } - + public static String unescape(String text) { return text.replace("\\", ""); } - + @SuppressWarnings("unchecked") public static T escape(T maybeText) { return CharSequence.class.isAssignableFrom(maybeText.getClass()) ? (T) escape(maybeText.toString()) : maybeText; } - + public static String searchIndexFieldAliasFor(Field field, String prefix) { String alias = field.getName(); if (prefix != null && !prefix.isBlank()) { alias = prefix.replace(".", "_") + "_" + alias; - } + } return alias; } - - private QueryUtils() {} } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQuery.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQuery.java index aab1556d..9a214b62 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQuery.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQuery.java @@ -54,57 +54,49 @@ public class RediSearchQuery implements RepositoryQuery { private final QueryMethod queryMethod; private final String searchIndex; private final RedisOMProperties redisOMProperties; - - private RediSearchQueryType type; - private String value; - - // query fields - private String[] returnFields; - private Integer offset; - private Integer limit; - private String sortBy; - private Boolean sortAscending; private final boolean hasLanguageParameter; - // aggregation fields private final List> aggregationLoad = new ArrayList<>(); private final List> aggregationApply = new ArrayList<>(); - private String[] aggregationFilter; private final List aggregationGroups = new ArrayList<>(); private final List aggregationSortedFields = new ArrayList<>(); - private Integer aggregationSortByMax; - private Long aggregationTimeout; - private Boolean aggregationVerbatim; - private final List>> queryOrParts = new ArrayList<>(); - // for non @Param annotated dynamic names private final List paramNames = new ArrayList<>(); private final Class domainType; - private final RedisModulesOperations modulesOperations; - private final boolean isANDQuery; - private final BloomQueryExecutor bloomQueryExecutor; private final CuckooQueryExecutor cuckooQueryExecutor; private final AutoCompleteQueryExecutor autoCompleteQueryExecutor; private final GsonBuilder gsonBuilder; private final RediSearchIndexer indexer; + private RediSearchQueryType type; + private String value; + // query fields + private String[] returnFields; + private Integer offset; + private Integer limit; + private String sortBy; + private Boolean sortAscending; + private String[] aggregationFilter; + private Integer aggregationSortByMax; + private Long aggregationTimeout; + private Boolean aggregationVerbatim; private Gson gson; private boolean isNullParamQuery; @SuppressWarnings("unchecked") public RediSearchQuery(// - QueryMethod queryMethod, // - RepositoryMetadata metadata, // - RediSearchIndexer indexer, // - QueryMethodEvaluationContextProvider evaluationContextProvider, // - KeyValueOperations keyValueOperations, // - RedisModulesOperations rmo, // - Class> queryCreator, // - GsonBuilder gsonBuilder, // - RedisOMProperties redisOMProperties // + QueryMethod queryMethod, // + RepositoryMetadata metadata, // + RediSearchIndexer indexer, // + QueryMethodEvaluationContextProvider evaluationContextProvider, // + KeyValueOperations keyValueOperations, // + RedisModulesOperations rmo, // + Class> queryCreator, // + GsonBuilder gsonBuilder, // + RedisOMProperties redisOMProperties // ) { logger.info(String.format("Creating %s query method", queryMethod.getName())); @@ -122,19 +114,20 @@ public RediSearchQuery(// autoCompleteQueryExecutor = new AutoCompleteQueryExecutor(this, modulesOperations); Class repoClass = metadata.getRepositoryInterface(); - @SuppressWarnings("rawtypes") - Class[] params = queryMethod.getParameters().stream().map(Parameter::getType).toArray(Class[]::new); + @SuppressWarnings("rawtypes") Class[] params = queryMethod.getParameters().stream().map(Parameter::getType) + .toArray(Class[]::new); hasLanguageParameter = Arrays.stream(params).anyMatch(c -> c.isAssignableFrom(SearchLanguage.class)); isANDQuery = QueryClause.hasContainingAllClause(queryMethod.getName()); - String methodName = isANDQuery ? QueryClause.getPostProcessMethodName(queryMethod.getName()) - : queryMethod.getName(); + String methodName = isANDQuery ? + QueryClause.getPostProcessMethodName(queryMethod.getName()) : + queryMethod.getName(); try { java.lang.reflect.Method method = repoClass.getMethod(queryMethod.getName(), params); if (method.isAnnotationPresent(com.redis.om.spring.annotations.Query.class)) { - com.redis.om.spring.annotations.Query queryAnnotation = method - .getAnnotation(com.redis.om.spring.annotations.Query.class); + com.redis.om.spring.annotations.Query queryAnnotation = method.getAnnotation( + com.redis.om.spring.annotations.Query.class); this.type = RediSearchQueryType.QUERY; this.value = queryAnnotation.value(); this.returnFields = queryAnnotation.returnFields(); @@ -147,9 +140,9 @@ public RediSearchQuery(// this.type = RediSearchQueryType.AGGREGATION; this.value = aggregation.value(); Arrays.stream(aggregation.load()) - .forEach(load -> aggregationLoad.add(new SimpleEntry<>(load.property(), load.alias()))); + .forEach(load -> aggregationLoad.add(new SimpleEntry<>(load.property(), load.alias()))); Arrays.stream(aggregation.apply()) - .forEach(apply -> aggregationApply.add(new SimpleEntry<>(apply.alias(), apply.expression()))); + .forEach(apply -> aggregationApply.add(new SimpleEntry<>(apply.alias(), apply.expression()))); this.aggregationFilter = aggregation.filter(); this.aggregationTimeout = aggregation.timeout() > Long.MIN_VALUE ? aggregation.timeout() : null; this.aggregationVerbatim = aggregation.verbatim() ? true : null; @@ -201,9 +194,9 @@ public RediSearchQuery(// aggregationGroups.add(group); }); Arrays.stream(aggregation.sortBy()).forEach(sb -> { - SortedField sortedField = sb.direction().isAscending() ? SortedField.asc(sb.field()) - : SortedField.desc( - sb.field()); + SortedField sortedField = sb.direction().isAscending() ? + SortedField.asc(sb.field()) : + SortedField.desc(sb.field()); aggregationSortedFields.add(sortedField); }); @@ -234,13 +227,16 @@ public RediSearchQuery(// this.isNullParamQuery = !nullParamNames.isEmpty() || !notNullParamNames.isEmpty(); - this.type = queryMethod.getName().matches("(?:remove|delete).*") ? RediSearchQueryType.DELETE : RediSearchQueryType.QUERY; + this.type = queryMethod.getName().matches("(?:remove|delete).*") ? + RediSearchQueryType.DELETE : + RediSearchQueryType.QUERY; this.returnFields = new String[] {}; processPartTree(pt, nullParamNames, notNullParamNames); } } catch (NoSuchMethodException | SecurityException e) { - logger.debug(String.format("Could not resolved query method %s(%s): %s", queryMethod.getName(), - Arrays.toString(params), e.getMessage())); + logger.debug( + String.format("Could not resolved query method %s(%s): %s", queryMethod.getName(), Arrays.toString(params), + e.getMessage())); } } @@ -277,7 +273,7 @@ private List> extractQueryFields(Class type, Part p } private List> extractQueryFields(Class type, Part part, List path, - int level) { + int level) { List> qf = new ArrayList<>(); String property = path.get(level).getSegment(); String key = part.getProperty().toDotPath().replace(".", "_"); @@ -320,8 +316,8 @@ private List> extractQueryFields(Class type, Part p // // Any Numeric class -> Numeric Search Field // - else if (Number.class.isAssignableFrom(fieldType) || (fieldType == LocalDateTime.class) - || (field.getType() == LocalDate.class) || (field.getType() == Date.class)) { + else if (Number.class.isAssignableFrom( + fieldType) || (fieldType == LocalDateTime.class) || (field.getType() == LocalDate.class) || (field.getType() == Date.class)) { qf.add(Pair.of(actualKey, QueryClause.get(FieldType.NUMERIC, part.getType()))); } // @@ -391,7 +387,7 @@ public Object execute(Object[] parameters) { } else if (type == RediSearchQueryType.AUTOCOMPLETE) { Optional maybeAutoCompleteDictionaryKey = autoCompleteQueryExecutor.getAutoCompleteDictionaryKey(); return maybeAutoCompleteDictionaryKey.map(s -> autoCompleteQueryExecutor.executeAutoCompleteQuery(parameters, s)) - .orElse(null); + .orElse(null); } else { return null; } @@ -415,14 +411,12 @@ private Object executeQuery(Object[] parameters) { boolean isProjecting = returnedType.isProjecting() && returnedType.getReturnedType() != SearchResult.class; boolean isOpenProjecting = Arrays.stream(returnedType.getReturnedType().getMethods()) - .anyMatch(m -> m.isAnnotationPresent(Value.class)); + .anyMatch(m -> m.isAnnotationPresent(Value.class)); boolean canPerformQueryOptimization = isProjecting && !isOpenProjecting; if (canPerformQueryOptimization) { - query.returnFields(returnedType.getInputProperties() - .stream() - .map(inputProperty -> new FieldName( "$." + inputProperty, inputProperty)) - .toArray(FieldName[]::new)); + query.returnFields(returnedType.getInputProperties().stream() + .map(inputProperty -> new FieldName("$." + inputProperty, inputProperty)).toArray(FieldName[]::new)); } else { query.returnFields(returnFields); } @@ -432,7 +426,7 @@ private Object executeQuery(Object[] parameters) { boolean needsLimit = true; if (queryMethod.isPageQuery()) { maybePageable = Arrays.stream(parameters).filter(Pageable.class::isInstance).map(Pageable.class::cast) - .findFirst(); + .findFirst(); if (maybePageable.isPresent()) { Pageable pageable = maybePageable.get(); @@ -451,7 +445,7 @@ private Object executeQuery(Object[] parameters) { if (needsLimit) { if ((limit != null && limit != Integer.MIN_VALUE) || (offset != null && offset != Integer.MIN_VALUE)) { query.limit(offset != null ? offset : 0, - limit != null ? limit : redisOMProperties.getRepository().getQuery().getLimit()); + limit != null ? limit : redisOMProperties.getRepository().getQuery().getLimit()); } else { query.limit(0, redisOMProperties.getRepository().getQuery().getLimit()); } @@ -463,8 +457,7 @@ private Object executeQuery(Object[] parameters) { if (hasLanguageParameter) { Optional maybeSearchLanguage = Arrays.stream(parameters).filter(SearchLanguage.class::isInstance) - .map(SearchLanguage.class::cast) - .findFirst(); + .map(SearchLanguage.class::cast).findFirst(); maybeSearchLanguage.ifPresent(searchLanguage -> query.setLanguage(searchLanguage.getValue())); } @@ -472,10 +465,10 @@ private Object executeQuery(Object[] parameters) { // aggregation if (queryMethod.isCollectionQuery() && !queryMethod.getParameters().isEmpty()) { List> emptyCollectionParams = Arrays.stream(parameters) // - .filter(Collection.class::isInstance) // - .map(p -> (Collection) p) // - .filter(Collection::isEmpty) // - .collect(Collectors.toList()); + .filter(Collection.class::isInstance) // + .map(p -> (Collection) p) // + .filter(Collection::isEmpty) // + .collect(Collectors.toList()); if (!emptyCollectionParams.isEmpty()) { return Collections.emptyList(); } @@ -488,9 +481,7 @@ private Object executeQuery(Object[] parameters) { if (queryMethod.getReturnedObjectType() == SearchResult.class) { result = searchResult; } else if (queryMethod.isPageQuery()) { - List content = searchResult.getDocuments().stream() - .map(this::parseDocumentResult) - .toList(); + List content = searchResult.getDocuments().stream().map(this::parseDocumentResult).toList(); if (maybePageable.isPresent()) { Pageable pageable = maybePageable.get(); @@ -504,9 +495,7 @@ private Object executeQuery(Object[] parameters) { result = parseDocumentResult(doc); } } else if ((queryMethod.isCollectionQuery()) || this.type == RediSearchQueryType.DELETE) { - result = searchResult.getDocuments().stream() - .map(this::parseDocumentResult) - .toList(); + result = searchResult.getDocuments().stream().map(this::parseDocumentResult).toList(); } return processor.processResult(result); @@ -520,14 +509,11 @@ private Object parseDocumentResult(redis.clients.jedis.search.Document doc) { } if (doc.get("$") != null) { - return gsonInstance.fromJson(SafeEncoder.encode((byte[])doc.get("$")), domainType); + return gsonInstance.fromJson(SafeEncoder.encode((byte[]) doc.get("$")), domainType); } return gsonInstance.fromJson(gsonInstance.toJsonTree(StreamSupport.stream(doc.getProperties().spliterator(), false) - .collect(Collectors.toMap( - Entry::getKey, - entry -> SafeEncoder.encode((byte[]) entry.getValue()) - ))), domainType); + .collect(Collectors.toMap(Entry::getKey, entry -> SafeEncoder.encode((byte[]) entry.getValue())))), domainType); } private Object executeDeleteQuery(Object[] parameters) { @@ -563,7 +549,8 @@ private Object executeDeleteQuery(Object[] parameters) { // determine if we need to return the deleted entities or just obtain the keys Class returnType = queryMethod.getReturnedObjectType(); - if (Number.class.isAssignableFrom(returnType) || returnType.equals(int.class) || returnType.equals(long.class) || returnType.equals(short.class)) { + if (Number.class.isAssignableFrom(returnType) || returnType.equals(int.class) || returnType.equals( + long.class) || returnType.equals(short.class)) { // return the number of deleted entities, so we only need the ids if (keys.isEmpty()) { return 0; @@ -623,7 +610,7 @@ private Object executeAggregation(Object[] parameters) { boolean needsLimit = true; if (queryMethod.isPageQuery()) { maybePageable = Arrays.stream(parameters).filter(Pageable.class::isInstance).map(Pageable.class::cast) - .findFirst(); + .findFirst(); if (maybePageable.isPresent()) { Pageable pageable = maybePageable.get(); @@ -679,9 +666,8 @@ private Object executeAggregation(Object[] parameters) { List content = List.of(); if (queryMethod.getReturnedObjectType() == Map.class) { content = aggregationResult.getResults().stream().map(m -> m.entrySet().stream() // - .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), - e.getValue() != null ? e.getValue().toString() : "")) // - .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) // + .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue() != null ? e.getValue().toString() : "")) // + .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) // ).collect(Collectors.toList()); } if (queryMethod.isPageQuery() && maybePageable.isPresent()) { @@ -726,8 +712,8 @@ private String prepareQuery(final Object[] parameters, boolean excludeNullParams return orPart; }).collect(Collectors.joining(" | "))); } else { - @SuppressWarnings("unchecked") - Iterator iterator = (Iterator) queryMethod.getParameters().iterator(); + @SuppressWarnings("unchecked") Iterator iterator = (Iterator) queryMethod.getParameters() + .iterator(); int index = 0; if (value != null && !value.isBlank()) { @@ -851,8 +837,7 @@ private Object executeNullQuery(Object[] parameters) { // extract the keys from the aggregation result String[] keys = aggregationResult.getResults().stream() // - .map(d -> d.get("__key").toString()) - .toArray(String[]::new); + .map(d -> d.get("__key").toString()).toArray(String[]::new); var entities = modulesOperations.opsForJSON().mget(domainType, keys); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQueryCreator.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQueryCreator.java index 49a4bb42..1d564cc6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQueryCreator.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RediSearchQueryCreator.java @@ -11,7 +11,6 @@ /** * Building operations for criteria based queries - * */ public class RediSearchQueryCreator extends AbstractQueryCreator, RediSearchQuery> { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RedisEnhancedQuery.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RedisEnhancedQuery.java index e643f267..10cfbe50 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RedisEnhancedQuery.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/RedisEnhancedQuery.java @@ -56,59 +56,49 @@ public class RedisEnhancedQuery implements RepositoryQuery { private final QueryMethod queryMethod; private final String searchIndex; private final RedisOMProperties redisOMProperties; - - private RediSearchQueryType type; - private String value; - - // query fields - private String[] returnFields; - private Integer offset; - private Integer limit; - private String sortBy; - private Boolean sortAscending; private final boolean hasLanguageParameter; - // aggregation fields private final List> aggregationLoad = new ArrayList<>(); private final List> aggregationApply = new ArrayList<>(); - private String[] aggregationFilter; private final List aggregationGroups = new ArrayList<>(); private final List aggregationSortedFields = new ArrayList<>(); - private Integer aggregationSortByMax; - private Long aggregationTimeout; - private Boolean aggregationVerbatim; - // private final List>> queryOrParts = new ArrayList<>(); - // for non @Param annotated dynamic names private final List paramNames = new ArrayList<>(); private final Class domainType; - private final RedisModulesOperations modulesOperations; private final MappingRedisOMConverter mappingConverter; private final RediSearchIndexer indexer; - private final BloomQueryExecutor bloomQueryExecutor; private final CuckooQueryExecutor cuckooQueryExecutor; private final AutoCompleteQueryExecutor autoCompleteQueryExecutor; - private final boolean isANDQuery; - private boolean isNullParamQuery; private final KeyValueOperations keyValueOperations; private final RedisOperations redisOperations; + private RediSearchQueryType type; + private String value; + // query fields + private String[] returnFields; + private Integer offset; + private Integer limit; + private String sortBy; + private Boolean sortAscending; + private String[] aggregationFilter; + private Integer aggregationSortByMax; + private Long aggregationTimeout; + private Boolean aggregationVerbatim; + private boolean isNullParamQuery; @SuppressWarnings("unchecked") - public RedisEnhancedQuery( - QueryMethod queryMethod, // - RepositoryMetadata metadata, // - RediSearchIndexer indexer, // - QueryMethodEvaluationContextProvider evaluationContextProvider, // - KeyValueOperations keyValueOperations, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - Class> queryCreator, - RedisOMProperties redisOMProperties) { + public RedisEnhancedQuery(QueryMethod queryMethod, // + RepositoryMetadata metadata, // + RediSearchIndexer indexer, // + QueryMethodEvaluationContextProvider evaluationContextProvider, // + KeyValueOperations keyValueOperations, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + Class> queryCreator, RedisOMProperties redisOMProperties) { logger.info(String.format("Creating query %s", queryMethod.getName())); this.keyValueOperations = keyValueOperations; @@ -127,19 +117,20 @@ public RedisEnhancedQuery( autoCompleteQueryExecutor = new AutoCompleteQueryExecutor(this, modulesOperations); Class repoClass = metadata.getRepositoryInterface(); - @SuppressWarnings("rawtypes") - Class[] params = queryMethod.getParameters().stream().map(Parameter::getType).toArray(Class[]::new); + @SuppressWarnings("rawtypes") Class[] params = queryMethod.getParameters().stream().map(Parameter::getType) + .toArray(Class[]::new); hasLanguageParameter = Arrays.stream(params).anyMatch(c -> c.isAssignableFrom(SearchLanguage.class)); isANDQuery = QueryClause.hasContainingAllClause(queryMethod.getName()); - String methodName = isANDQuery ? QueryClause.getPostProcessMethodName(queryMethod.getName()) - : queryMethod.getName(); + String methodName = isANDQuery ? + QueryClause.getPostProcessMethodName(queryMethod.getName()) : + queryMethod.getName(); try { java.lang.reflect.Method method = repoClass.getDeclaredMethod(queryMethod.getName(), params); if (method.isAnnotationPresent(com.redis.om.spring.annotations.Query.class)) { - com.redis.om.spring.annotations.Query queryAnnotation = method - .getAnnotation(com.redis.om.spring.annotations.Query.class); + com.redis.om.spring.annotations.Query queryAnnotation = method.getAnnotation( + com.redis.om.spring.annotations.Query.class); this.type = RediSearchQueryType.QUERY; this.value = queryAnnotation.value(); this.returnFields = queryAnnotation.returnFields(); @@ -152,9 +143,9 @@ public RedisEnhancedQuery( this.type = RediSearchQueryType.AGGREGATION; this.value = aggregation.value(); Arrays.stream(aggregation.load()) - .forEach(load -> aggregationLoad.add(new SimpleEntry<>(load.property(), load.alias()))); + .forEach(load -> aggregationLoad.add(new SimpleEntry<>(load.property(), load.alias()))); Arrays.stream(aggregation.apply()) - .forEach(apply -> aggregationApply.add(new SimpleEntry<>(apply.alias(), apply.expression()))); + .forEach(apply -> aggregationApply.add(new SimpleEntry<>(apply.alias(), apply.expression()))); this.aggregationFilter = aggregation.filter(); this.aggregationTimeout = aggregation.timeout() > Long.MIN_VALUE ? aggregation.timeout() : null; this.aggregationVerbatim = aggregation.verbatim() ? true : null; @@ -205,9 +196,9 @@ public RedisEnhancedQuery( aggregationGroups.add(group); }); Arrays.stream(aggregation.sortBy()).forEach(sb -> { - SortedField sortedField = sb.direction().isAscending() ? SortedField.asc(sb.field()) - : SortedField.desc( - sb.field()); + SortedField sortedField = sb.direction().isAscending() ? + SortedField.asc(sb.field()) : + SortedField.desc(sb.field()); aggregationSortedFields.add(sortedField); }); @@ -237,13 +228,16 @@ public RedisEnhancedQuery( }); this.isNullParamQuery = !nullParamNames.isEmpty() || !notNullParamNames.isEmpty(); - this.type = queryMethod.getName().matches("(?:remove|delete).*") ? RediSearchQueryType.DELETE : RediSearchQueryType.QUERY; + this.type = queryMethod.getName().matches("(?:remove|delete).*") ? + RediSearchQueryType.DELETE : + RediSearchQueryType.QUERY; this.returnFields = new String[] {}; processPartTree(pt, nullParamNames, notNullParamNames); } } catch (NoSuchMethodException | SecurityException e) { - logger.debug(String.format("Could not resolved query method %s(%s): %s", queryMethod.getName(), - Arrays.toString(params), e.getMessage())); + logger.debug( + String.format("Could not resolved query method %s(%s): %s", queryMethod.getName(), Arrays.toString(params), + e.getMessage())); } } @@ -280,7 +274,7 @@ private List> extractQueryFields(Class type, Part p } private List> extractQueryFields(Class type, Part part, List path, - int level) { + int level) { List> qf = new ArrayList<>(); String property = path.get(level).getSegment(); String key = part.getProperty().toDotPath().replace(".", "_"); @@ -324,8 +318,8 @@ private List> extractQueryFields(Class type, Part p // // Any Numeric class -> Numeric Search Field // - else if (Number.class.isAssignableFrom(fieldType) || (fieldType == LocalDateTime.class) - || (field.getType() == LocalDate.class) || (field.getType() == Date.class)) { + else if (Number.class.isAssignableFrom( + fieldType) || (fieldType == LocalDateTime.class) || (field.getType() == LocalDate.class) || (field.getType() == Date.class)) { qf.add(Pair.of(actualKey, QueryClause.get(FieldType.NUMERIC, part.getType()))); } // @@ -393,7 +387,7 @@ public Object execute(Object[] parameters) { } else if (type == RediSearchQueryType.AUTOCOMPLETE) { Optional maybeAutoCompleteDictionaryKey = autoCompleteQueryExecutor.getAutoCompleteDictionaryKey(); return maybeAutoCompleteDictionaryKey.map(s -> autoCompleteQueryExecutor.executeAutoCompleteQuery(parameters, s)) - .orElse(null); + .orElse(null); } else { return null; } @@ -421,10 +415,8 @@ private Object executeQuery(Object[] parameters) { boolean canPerformQueryOptimization = isProjecting && !isOpenProjecting; if (canPerformQueryOptimization) { - query.returnFields(returnedType.getInputProperties() - .stream() - .map(inputProperty -> new FieldName( "$." + inputProperty, inputProperty)) - .toArray(FieldName[]::new)); + query.returnFields(returnedType.getInputProperties().stream() + .map(inputProperty -> new FieldName("$." + inputProperty, inputProperty)).toArray(FieldName[]::new)); } else { query.returnFields(returnFields); } @@ -434,7 +426,7 @@ private Object executeQuery(Object[] parameters) { boolean needsLimit = true; if (queryMethod.isPageQuery()) { maybePageable = Arrays.stream(parameters).filter(Pageable.class::isInstance).map(Pageable.class::cast) - .findFirst(); + .findFirst(); if (maybePageable.isPresent()) { Pageable pageable = maybePageable.get(); @@ -453,7 +445,7 @@ private Object executeQuery(Object[] parameters) { if (needsLimit) { if ((limit != null && limit != Integer.MIN_VALUE) || (offset != null && offset != Integer.MIN_VALUE)) { query.limit(offset != null ? offset : 0, - limit != null ? limit : redisOMProperties.getRepository().getQuery().getLimit()); + limit != null ? limit : redisOMProperties.getRepository().getQuery().getLimit()); } else { query.limit(0, redisOMProperties.getRepository().getQuery().getLimit()); } @@ -465,8 +457,7 @@ private Object executeQuery(Object[] parameters) { if (hasLanguageParameter) { Optional maybeSearchLanguage = Arrays.stream(parameters).filter(SearchLanguage.class::isInstance) - .map(SearchLanguage.class::cast) - .findFirst(); + .map(SearchLanguage.class::cast).findFirst(); maybeSearchLanguage.ifPresent(searchLanguage -> query.setLanguage(searchLanguage.getValue())); } @@ -474,10 +465,10 @@ private Object executeQuery(Object[] parameters) { // aggregation if (queryMethod.isCollectionQuery() && !queryMethod.getParameters().isEmpty()) { List> emptyCollectionParams = Arrays.stream(parameters) // - .filter(Collection.class::isInstance) // - .map(p -> (Collection) p) // - .filter(Collection::isEmpty) // - .collect(Collectors.toList()); + .filter(Collection.class::isInstance) // + .map(p -> (Collection) p) // + .filter(Collection::isEmpty) // + .collect(Collectors.toList()); if (!emptyCollectionParams.isEmpty()) { return Collections.emptyList(); } @@ -502,7 +493,8 @@ private Object executeQuery(Object[] parameters) { } } else if (!queryMethod.isCollectionQuery()) { if (searchResult.getTotalResults() > 0 && !searchResult.getDocuments().isEmpty()) { - result = ObjectUtils.documentToObject(searchResult.getDocuments().get(0), queryMethod.getReturnedObjectType(), mappingConverter); + result = ObjectUtils.documentToObject(searchResult.getDocuments().get(0), queryMethod.getReturnedObjectType(), + mappingConverter); } else { result = null; } @@ -550,7 +542,8 @@ private Object executeDeleteQuery(Object[] parameters) { // determine if we need to return the deleted entities or just obtain the keys Class returnType = queryMethod.getReturnedObjectType(); - if (Number.class.isAssignableFrom(returnType) || returnType.equals(int.class) || returnType.equals(long.class) || returnType.equals(short.class)) { + if (Number.class.isAssignableFrom(returnType) || returnType.equals(int.class) || returnType.equals( + long.class) || returnType.equals(short.class)) { // return the number of deleted entities, so we only need the ids if (keys.isEmpty()) { return 0; @@ -572,7 +565,7 @@ private Object executeDeleteQuery(Object[] parameters) { List results = connection.closePipeline(); for (Object result : results) { - Map hashMap = (Map) result; + @SuppressWarnings("unchecked") Map hashMap = (Map) result; Object entity = mappingConverter.read(returnType, new RedisData(hashMap)); entities.add(entity); } @@ -626,7 +619,7 @@ private Object executeAggregation(Object[] parameters) { boolean needsLimit = true; if (queryMethod.isPageQuery()) { maybePageable = Arrays.stream(parameters).filter(Pageable.class::isInstance).map(Pageable.class::cast) - .findFirst(); + .findFirst(); if (maybePageable.isPresent()) { Pageable pageable = maybePageable.get(); @@ -682,9 +675,8 @@ private Object executeAggregation(Object[] parameters) { List content = List.of(); if (queryMethod.getReturnedObjectType() == Map.class) { content = aggregationResult.getResults().stream().map(m -> m.entrySet().stream() // - .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), - e.getValue() != null ? e.getValue().toString() : "")) // - .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) // + .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue() != null ? e.getValue().toString() : "")) // + .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) // ).collect(Collectors.toList()); } if (queryMethod.isPageQuery() && maybePageable.isPresent()) { @@ -730,8 +722,8 @@ private String prepareQuery(final Object[] parameters, boolean excludeNullParams return orPart; }).collect(Collectors.joining(" | "))); } else { - @SuppressWarnings("unchecked") - Iterator iterator = (Iterator) queryMethod.getParameters().iterator(); + @SuppressWarnings("unchecked") Iterator iterator = (Iterator) queryMethod.getParameters() + .iterator(); int index = 0; if (value != null && !value.isBlank()) { @@ -758,7 +750,7 @@ private String prepareQuery(final Object[] parameters, boolean excludeNullParams } var regex = "(\\$" + key + ")(\\W+|\\*|\\+)(.*)"; - preparedQuery = new StringBuilder(preparedQuery.toString().replaceAll(regex, v+"$2$3")); + preparedQuery = new StringBuilder(preparedQuery.toString().replaceAll(regex, v + "$2$3")); } index++; } @@ -847,10 +839,8 @@ private Object executeNullQuery(Object[] parameters) { AggregationResult aggregationResult = ops.aggregate(aggregation); // extract the keys from the aggregation result - var ids = aggregationResult.getResults().stream() - .map(d -> d.get("__key").toString().split(":")) - .map(parts -> parts[parts.length - 1]) - .toList(); + var ids = aggregationResult.getResults().stream().map(d -> d.get("__key").toString().split(":")) + .map(parts -> parts[parts.length - 1]).toList(); var entities = new ArrayList<>(); ids.forEach(id -> keyValueOperations.findById(id, domainType).ifPresent(entities::add)); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/Sort.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/Sort.java index 90f6129c..7110d936 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/Sort.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/Sort.java @@ -8,16 +8,19 @@ public class Sort extends org.springframework.data.domain.Sort { + @Serial + private static final long serialVersionUID = 7789210988714363618L; + protected Sort(List orders) { super(orders); } - + /** * Creates a new {@link org.springframework.data.domain.Sort} for the given {@link Order}s * use {@link com.redis.om.spring.metamodel.MetamodelField} * * @param direction must not be {@literal null}. - * @param fields must not be {@literal null}. + * @param fields must not be {@literal null}. * @return a Spring Sort object */ public static org.springframework.data.domain.Sort by(Direction direction, MetamodelField... fields) { @@ -30,6 +33,4 @@ public static org.springframework.data.domain.Sort by(MetamodelField... fi return org.springframework.data.domain.Sort.by(properties); } - @Serial private static final long serialVersionUID = 7789210988714363618L; - } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteOptions.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteOptions.java index a950c51b..4ecad468 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteOptions.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteOptions.java @@ -37,31 +37,31 @@ public boolean isFuzzy() { return fuzzy; } + public void setFuzzy(boolean fuzzy) { + this.fuzzy = fuzzy; + } + public boolean isWithScore() { return withScore; } + public void setWithScore(boolean withScore) { + this.withScore = withScore; + } + public boolean isWithPayload() { return withPayload; } - public int getLimit() { - return limit; + public void setWithPayload(boolean withPayload) { + this.withPayload = withPayload; } - public void setFuzzy(boolean fuzzy) { - this.fuzzy = fuzzy; + public int getLimit() { + return limit; } public void setLimit(int limit) { this.limit = limit; } - - public void setWithScore(boolean withScore) { - this.withScore = withScore; - } - - public void setWithPayload(boolean withPayload) { - this.withPayload = withPayload; - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteQueryExecutor.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteQueryExecutor.java index 828b0dcd..0abb83e8 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteQueryExecutor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/autocomplete/AutoCompleteQueryExecutor.java @@ -17,9 +17,8 @@ public class AutoCompleteQueryExecutor { - private static final Log logger = LogFactory.getLog(AutoCompleteQueryExecutor.class); public static final String AUTOCOMPLETE_PREFIX = "autoComplete"; - + private static final Log logger = LogFactory.getLog(AutoCompleteQueryExecutor.class); final RepositoryQuery query; final RedisModulesOperations modulesOperations; @@ -32,8 +31,7 @@ public Optional getAutoCompleteDictionaryKey() { String methodName = query.getQueryMethod().getName(); boolean hasExistByPrefix = methodName.startsWith(AUTOCOMPLETE_PREFIX); if (hasExistByPrefix && query.getQueryMethod().isCollectionQuery()) { - String targetProperty = ObjectUtils - .firstToLowercase(methodName.substring(AUTOCOMPLETE_PREFIX.length())); + String targetProperty = ObjectUtils.firstToLowercase(methodName.substring(AUTOCOMPLETE_PREFIX.length())); logger.debug(String.format("Target Property : %s", targetProperty)); Class entityClass = query.getQueryMethod().getEntityInformation().getJavaType(); @@ -44,8 +42,9 @@ public Optional getAutoCompleteDictionaryKey() { } if (field.isAnnotationPresent(AutoComplete.class)) { AutoComplete bloom = field.getAnnotation(AutoComplete.class); - return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(bloom.name()) ? bloom.name() - : String.format(Suggestion.KEY_FORMAT_STRING, entityClass.getSimpleName(), field.getName())); + return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(bloom.name()) ? + bloom.name() : + String.format(Suggestion.KEY_FORMAT_STRING, entityClass.getSimpleName(), field.getName())); } } catch (SecurityException e) { return Optional.empty(); @@ -59,7 +58,7 @@ public List executeAutoCompleteQuery(Object[] parameters, String aut SearchOperations ops = modulesOperations.opsForSearch(autoCompleteKey); if ((parameters.length > 1) && (parameters[1].getClass() == AutoCompleteOptions.class)) { - AutoCompleteOptions options = (AutoCompleteOptions)parameters[1]; + AutoCompleteOptions options = (AutoCompleteOptions) parameters[1]; return ops.getSuggestion(autoCompleteKey, parameters[0].toString(), options); } else { return ops.getSuggestion(autoCompleteKey, parameters[0].toString()); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/bloom/BloomQueryExecutor.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/bloom/BloomQueryExecutor.java index bc6bd770..6202b1f5 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/bloom/BloomQueryExecutor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/bloom/BloomQueryExecutor.java @@ -14,12 +14,12 @@ import java.util.Optional; public class BloomQueryExecutor { - - private static final Log logger = LogFactory.getLog(BloomQueryExecutor.class); + public static final String EXISTS_BY_PREFIX = "existsBy"; + private static final Log logger = LogFactory.getLog(BloomQueryExecutor.class); final RepositoryQuery query; final RedisModulesOperations modulesOperations; - + public BloomQueryExecutor(RepositoryQuery query, RedisModulesOperations modulesOperations) { this.query = query; this.modulesOperations = modulesOperations; @@ -40,8 +40,9 @@ public Optional getBloomFilter() { } if (field.isAnnotationPresent(Bloom.class)) { Bloom bloom = field.getAnnotation(Bloom.class); - return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(bloom.name()) ? bloom.name() - : String.format("bf:%s:%s", entityClass.getSimpleName(), field.getName())); + return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(bloom.name()) ? + bloom.name() : + String.format("bf:%s:%s", entityClass.getSimpleName(), field.getName())); } } catch (SecurityException e) { // NO-OP @@ -49,7 +50,7 @@ public Optional getBloomFilter() { } return Optional.empty(); } - + public Object executeBloomQuery(Object[] parameters, String bloomFilter) { logger.debug(String.format("filter:%s, params:%s", bloomFilter, Arrays.toString(parameters))); BloomOperations ops = modulesOperations.opsForBloom(); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClause.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClause.java index ab3c83ce..f0e4adef 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClause.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClause.java @@ -16,103 +16,105 @@ public enum QueryClause { // FULL TEXT TEXT_ALL( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.SIMPLE_PROPERTY, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.SIMPLE_PROPERTY, QueryClause.FIRST_PARAM, 1) // ), TEXT_SIMPLE_PROPERTY( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_EQUAL, 1) // ), TEXT_NEGATING_SIMPLE_PROPERTY( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NON_EQUAL_PARAM_0, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NON_EQUAL_PARAM_0, 1) // ), TEXT_STARTING_WITH( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.STARTING_WITH, QueryClause.FIELD_TEXT_STARTING_WITH, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.STARTING_WITH, QueryClause.FIELD_TEXT_STARTING_WITH, 1) // ), TEXT_ENDING_WITH( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.ENDING_WITH, QueryClause.FIELD_TEXT_ENDING_WITH, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.ENDING_WITH, QueryClause.FIELD_TEXT_ENDING_WITH, 1) // ), TEXT_LIKE( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.LIKE, QueryClause.FIELD_LIKE, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.LIKE, QueryClause.FIELD_LIKE, 1) // ), TEXT_NOT_LIKE( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_LIKE, QueryClause.FIELD_NOT_LIKE, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_LIKE, QueryClause.FIELD_NOT_LIKE, 1) // ), TEXT_CONTAINING( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.CONTAINING, QueryClause.FIELD_LIKE, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.CONTAINING, QueryClause.FIELD_LIKE, 1) // ), TEXT_NOT_CONTAINING( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_CONTAINING, QueryClause.FIELD_NOT_LIKE, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_CONTAINING, QueryClause.FIELD_NOT_LIKE, 1) // ), TEXT_NOT_IN( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_IN, QueryClause.FIELD_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.NOT_IN, QueryClause.FIELD_EQUAL, 1) // ), TEXT_IN( // - QueryClauseTemplate.of(FieldType.TEXT, Part.Type.IN, QueryClause.FIELD_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TEXT, Part.Type.IN, QueryClause.FIELD_EQUAL, 1) // ), // NUMERIC NUMERIC_SIMPLE_PROPERTY( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NUMERIC_EQUAL_PARAM_0, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NUMERIC_EQUAL_PARAM_0, 1) // ), NUMERIC_NEGATING_SIMPLE_PROPERTY( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NUMERIC_NOT_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_NUMERIC_NOT_EQUAL, 1) // ), NUMERIC_BETWEEN( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.BETWEEN, QueryClause.FIELD_NUMERIC_BETWEEN, 2) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.BETWEEN, QueryClause.FIELD_NUMERIC_BETWEEN, 2) // ), NUMERIC_LESS_THAN( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.LESS_THAN, QueryClause.FIELD_NUMERIC_LESS_THAN, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.LESS_THAN, QueryClause.FIELD_NUMERIC_LESS_THAN, 1) // ), NUMERIC_LESS_THAN_EQUAL( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.LESS_THAN_EQUAL, QueryClause.FIELD_NUMERIC_LESS_THAN_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.LESS_THAN_EQUAL, QueryClause.FIELD_NUMERIC_LESS_THAN_EQUAL, 1) + // ), NUMERIC_GREATER_THAN( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.GREATER_THAN, QueryClause.FIELD_NUMERIC_GREATER_THAN, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.GREATER_THAN, QueryClause.FIELD_NUMERIC_GREATER_THAN, 1) // ), NUMERIC_GREATER_THAN_EQUAL( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.GREATER_THAN_EQUAL, QueryClause.FIELD_NUMERIC_GREATER_THAN_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.GREATER_THAN_EQUAL, + QueryClause.FIELD_NUMERIC_GREATER_THAN_EQUAL, 1) // ), NUMERIC_BEFORE( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.BEFORE, QueryClause.FIELD_NUMERIC_BEFORE, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.BEFORE, QueryClause.FIELD_NUMERIC_BEFORE, 1) // ), NUMERIC_AFTER( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.AFTER, QueryClause.FIELD_NUMERIC_AFTER, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.AFTER, QueryClause.FIELD_NUMERIC_AFTER, 1) // ), NUMERIC_CONTAINING( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // ), NUMERIC_CONTAINING_ALL( // - QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.NUMERIC, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // ), // GEO GEO_NEAR( // - QueryClauseTemplate.of(FieldType.GEO, Part.Type.NEAR, QueryClause.FIELD_GEO_NEAR, 2) // + QueryClauseTemplate.of(FieldType.GEO, Part.Type.NEAR, QueryClause.FIELD_GEO_NEAR, 2) // ), GEO_CONTAINING( // - QueryClauseTemplate.of(FieldType.GEO, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.GEO, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // ), GEO_CONTAINING_ALL( // - QueryClauseTemplate.of(FieldType.GEO, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.GEO, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // ), // TAG TAG_SIMPLE_PROPERTY( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_TAG_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.SIMPLE_PROPERTY, QueryClause.FIELD_TAG_EQUAL, 1) // ), TAG_NOT_IN( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.NOT_IN, QueryClause.FIELD_TAG_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.NOT_IN, QueryClause.FIELD_TAG_EQUAL, 1) // ), TAG_IN( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.IN, QueryClause.FIELD_TAG_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.IN, QueryClause.FIELD_TAG_EQUAL, 1) // ), TAG_CONTAINING( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.CONTAINING, QueryClause.FIELD_EQUAL, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.CONTAINING, QueryClause.FIELD_EQUAL, 1) // ), TAG_CONTAINING_ALL( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.CONTAINING, QueryClause.FIRST_PARAM, 1) // ), TAG_STARTING_WITH( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.STARTING_WITH, QueryClause.FIELD_TAG_STARTING_WITH, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.STARTING_WITH, QueryClause.FIELD_TAG_STARTING_WITH, 1) // ), TAG_ENDING_WITH( // - QueryClauseTemplate.of(FieldType.TAG, Part.Type.ENDING_WITH, QueryClause.FIELD_TAG_ENDING_WITH, 1) // + QueryClauseTemplate.of(FieldType.TAG, Part.Type.ENDING_WITH, QueryClause.FIELD_TAG_ENDING_WITH, 1) // ), // ALL FIELDS IS_NULL( // @@ -122,18 +124,21 @@ public enum QueryClause { QueryClauseTemplate.of(FieldType.TAG, Type.IS_NOT_NULL, QueryClause.FIELD_IS_NOT_NULL, 0) // ); + public static final Map methodNameMap = Map.of("IsContainingAll", "IsContaining", "ContainingAll", + "Containing", "ContainsAll", "Contains"); + public static final Pattern CONTAINING_ALL_PATTERN = Pattern.compile("(IsContainingAll|ContainingAll|ContainsAll)"); private static final String PARAM_PREFIX = "$param_"; private static final String FIRST_PARAM = "$param_0"; - private static final String FIELD_EQUAL ="@$field:$param_0"; - private static final String FIELD_NON_EQUAL_PARAM_0 ="-@$field:$param_0"; + private static final String FIELD_EQUAL = "@$field:$param_0"; + private static final String FIELD_NON_EQUAL_PARAM_0 = "-@$field:$param_0"; private static final String FIELD_TAG_EQUAL = "@$field:{$param_0}"; private static final String FIELD_LIKE = "@$field:%%%$param_0%%%"; private static final String FIELD_NOT_LIKE = "-@$field:%%%$param_0%%%"; private static final String FIELD_NUMERIC_EQUAL_PARAM_0 = "@$field:[$param_0 $param_0]"; - private static final String FIELD_TEXT_STARTING_WITH ="@$field:$param_0*"; - private static final String FIELD_TAG_STARTING_WITH ="@$field:{$param_0*}"; - private static final String FIELD_TEXT_ENDING_WITH ="@$field:*$param_0"; - private static final String FIELD_TAG_ENDING_WITH ="@$field:{*$param_0}"; + private static final String FIELD_TEXT_STARTING_WITH = "@$field:$param_0*"; + private static final String FIELD_TAG_STARTING_WITH = "@$field:{$param_0*}"; + private static final String FIELD_TEXT_ENDING_WITH = "@$field:*$param_0"; + private static final String FIELD_TAG_ENDING_WITH = "@$field:{*$param_0}"; private static final String FIELD_NUMERIC_NOT_EQUAL = "@$field:-[$param_0 $param_0]"; private static final String FIELD_NUMERIC_BETWEEN = "@$field:[$param_0 $param_1]"; private static final String FIELD_NUMERIC_LESS_THAN = "@$field:[-inf ($param_0]"; @@ -145,7 +150,6 @@ public enum QueryClause { private static final String FIELD_GEO_NEAR = "@$field:[$param_0 $param_1 $param_2]"; private static final String FIELD_IS_NULL = "!exists(@$field)"; private static final String FIELD_IS_NOT_NULL = "exists(@$field)"; - private final QueryClauseTemplate clauseTemplate; private final MappingRedisOMConverter converter = new MappingRedisOMConverter(); @@ -153,12 +157,41 @@ public enum QueryClause { this.clauseTemplate = value; } + public static QueryClause get(FieldType fieldType, Part.Type partType) { + try { + return QueryClause.valueOf(fieldType.toString() + "_" + partType.name()); + } catch (IllegalArgumentException | NullPointerException e) { + return TAG_SIMPLE_PROPERTY; + } + } + + public static boolean hasContainingAllClause(String methodName) { + return CONTAINING_ALL_PATTERN.matcher(methodName).find(); + } + + public static String getPostProcessMethodName(String methodName) { + if (hasContainingAllClause(methodName)) { + Optional maybeMatchSubstring = CONTAINING_ALL_PATTERN.matcher(methodName).results().map(mr -> mr.group(1)) + .findFirst(); + if (maybeMatchSubstring.isPresent()) { + String matchSubstring = maybeMatchSubstring.get(); + return methodName.replace(matchSubstring, methodNameMap.get(matchSubstring)); + } else { + return methodName; + } + + } + return methodName; + } + public QueryClauseTemplate getClauseTemplate() { return clauseTemplate; } public String prepareQuery(String field, Object... params) { - String prepared = field.equalsIgnoreCase("__ALL__") ? clauseTemplate.getQuerySegmentTemplate() : clauseTemplate.getQuerySegmentTemplate().replace("$field", field); + String prepared = field.equalsIgnoreCase("__ALL__") ? + clauseTemplate.getQuerySegmentTemplate() : + clauseTemplate.getQuerySegmentTemplate().replace("$field", field); Iterator iter = Arrays.asList(params).iterator(); @@ -181,11 +214,17 @@ public String prepareQuery(String field, Object... params) { if (param instanceof Collection c) { String value; if (this == QueryClause.TAG_CONTAINING_ALL) { - value = c.stream().map(n -> "@" + field + ":{" + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "}").collect(Collectors.joining(" ")); + value = c.stream() + .map(n -> "@" + field + ":{" + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "}") + .collect(Collectors.joining(" ")); } else if (this == QueryClause.NUMERIC_CONTAINING) { - value = c.stream().map(n -> "@" + field + ":[" + QueryUtils.escape(ObjectUtils.asString(n, converter)) + " " + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "]").collect(Collectors.joining("|")); + value = c.stream().map(n -> "@" + field + ":[" + QueryUtils.escape( + ObjectUtils.asString(n, converter)) + " " + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "]") + .collect(Collectors.joining("|")); } else if (this == QueryClause.NUMERIC_CONTAINING_ALL) { - value = c.stream().map(n -> "@" + field + ":[" + QueryUtils.escape(ObjectUtils.asString(n, converter)) + " " + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "]").collect(Collectors.joining(" ")); + value = c.stream().map(n -> "@" + field + ":[" + QueryUtils.escape( + ObjectUtils.asString(n, converter)) + " " + QueryUtils.escape(ObjectUtils.asString(n, converter)) + "]") + .collect(Collectors.joining(" ")); } else if (this == QueryClause.GEO_CONTAINING) { value = c.stream().map(n -> { Point p = (Point) n; @@ -197,7 +236,8 @@ public String prepareQuery(String field, Object... params) { return "@" + field + ":[" + p.getX() + " " + p.getY() + " .000001 ft]"; }).collect(Collectors.joining(" ")); } else { - value = c.stream().map(n -> QueryUtils.escape(ObjectUtils.asString(n, converter), false)).collect(Collectors.joining("|")); + value = c.stream().map(n -> QueryUtils.escape(ObjectUtils.asString(n, converter), false)) + .collect(Collectors.joining("|")); } prepared = prepared.replace(PARAM_PREFIX + i++, value); @@ -205,7 +245,8 @@ public String prepareQuery(String field, Object... params) { if (clauseTemplate.getIndexType() == FieldType.TEXT) { prepared = prepared.replace(PARAM_PREFIX + i++, param.toString()); } else { - prepared = prepared.replace(PARAM_PREFIX + i++, QueryUtils.escape(ObjectUtils.asString(param, converter))); + prepared = prepared.replace(PARAM_PREFIX + i++, + QueryUtils.escape(ObjectUtils.asString(param, converter))); } } break; @@ -214,38 +255,4 @@ public String prepareQuery(String field, Object... params) { return prepared; } - - public static QueryClause get(FieldType fieldType, Part.Type partType) { - try { - return QueryClause.valueOf(fieldType.toString() + "_" + partType.name()); - } catch (IllegalArgumentException | NullPointerException e) { - return TAG_SIMPLE_PROPERTY; - } - } - - public static final Map methodNameMap = Map.of( - "IsContainingAll", "IsContaining", - "ContainingAll", "Containing", - "ContainsAll", "Contains" - ); - - public static final Pattern CONTAINING_ALL_PATTERN = Pattern.compile("(IsContainingAll|ContainingAll|ContainsAll)"); - - public static boolean hasContainingAllClause(String methodName) { - return CONTAINING_ALL_PATTERN.matcher(methodName).find(); - } - - public static String getPostProcessMethodName(String methodName) { - if (hasContainingAllClause(methodName)) { - Optional maybeMatchSubstring = CONTAINING_ALL_PATTERN.matcher(methodName).results().map(mr -> mr.group(1)).findFirst(); - if (maybeMatchSubstring.isPresent()) { - String matchSubstring = maybeMatchSubstring.get(); - return methodName.replace(matchSubstring, methodNameMap.get(matchSubstring)); - } else { - return methodName; - } - - } - return methodName; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClauseTemplate.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClauseTemplate.java index 2088d97e..61ce767e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClauseTemplate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/clause/QueryClauseTemplate.java @@ -5,42 +5,41 @@ import redis.clients.jedis.search.Schema.FieldType; public class QueryClauseTemplate { - + private final FieldType indexType; - + private final Part.Type queryPartType; - private final String querySegmentTemplate; - + private final Integer numberOfArguments; - private QueryClauseTemplate( Schema.FieldType indexType, Part.Type queryPartType, - String querySegmentTemplate, Integer numberOfArguments) { + private QueryClauseTemplate(Schema.FieldType indexType, Part.Type queryPartType, String querySegmentTemplate, + Integer numberOfArguments) { this.indexType = indexType; this.queryPartType = queryPartType; this.querySegmentTemplate = querySegmentTemplate; this.numberOfArguments = numberOfArguments; } - public static QueryClauseTemplate of( Schema.FieldType indexType, Part.Type queryPartType, - String querySegmentTemplate, Integer numberOfArguments) { + public static QueryClauseTemplate of(Schema.FieldType indexType, Part.Type queryPartType, String querySegmentTemplate, + Integer numberOfArguments) { return new QueryClauseTemplate(indexType, queryPartType, querySegmentTemplate, numberOfArguments); } - public FieldType getIndexType() { + public FieldType getIndexType() { return this.indexType; } - public Part.Type getQueryPartType() { + public Part.Type getQueryPartType() { return this.queryPartType; } - public String getQuerySegmentTemplate() { + public String getQuerySegmentTemplate() { return this.querySegmentTemplate; } - public Integer getNumberOfArguments() { + public Integer getNumberOfArguments() { return this.numberOfArguments; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/cuckoo/CuckooQueryExecutor.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/cuckoo/CuckooQueryExecutor.java index 52755c41..38625c17 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/cuckoo/CuckooQueryExecutor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/query/cuckoo/CuckooQueryExecutor.java @@ -15,8 +15,8 @@ public class CuckooQueryExecutor { - private static final Log logger = LogFactory.getLog(CuckooQueryExecutor.class); public static final String EXISTS_BY_PREFIX = "existsBy"; + private static final Log logger = LogFactory.getLog(CuckooQueryExecutor.class); final RepositoryQuery query; final RedisModulesOperations modulesOperations; @@ -40,8 +40,9 @@ public Optional getCuckooFilter() { } if (field.isAnnotationPresent(Cuckoo.class)) { Cuckoo cuckoo = field.getAnnotation(Cuckoo.class); - return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(cuckoo.name()) ? cuckoo.name() - : String.format("cf:%s:%s", entityClass.getSimpleName(), field.getName())); + return Optional.of(!org.apache.commons.lang3.ObjectUtils.isEmpty(cuckoo.name()) ? + cuckoo.name() : + String.format("cf:%s:%s", entityClass.getSimpleName(), field.getName())); } } catch (SecurityException e) { // NO-OP @@ -49,7 +50,7 @@ public Optional getCuckooFilter() { } return Optional.empty(); } - + public Object executeCuckooQuery(Object[] parameters, String cuckooFilter) { logger.debug(String.format("filter:%s, params:%s", cuckooFilter, Arrays.toString(parameters))); CuckooFilterOperations ops = modulesOperations.opsForCuckoFilter(); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactory.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactory.java index 40bd03d8..10eee92d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactory.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactory.java @@ -58,23 +58,23 @@ public class RedisDocumentRepositoryFactory extends KeyValueRepositoryFactory { * @param properties must not be {@literal null}. */ public RedisDocumentRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - RedisMappingContext mappingContext, // - GsonBuilder gsonBuilder, // - FeatureExtractor featureExtractor, // - RedisOMProperties properties // + KeyValueOperations keyValueOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + RedisMappingContext mappingContext, // + GsonBuilder gsonBuilder, // + FeatureExtractor featureExtractor, // + RedisOMProperties properties // ) { this( // - keyValueOperations, // - rmo, // - indexer, // - DEFAULT_QUERY_CREATOR, // - mappingContext, // - gsonBuilder, // - featureExtractor, // - properties // + keyValueOperations, // + rmo, // + indexer, // + DEFAULT_QUERY_CREATOR, // + mappingContext, // + gsonBuilder, // + featureExtractor, // + properties // ); // } @@ -90,25 +90,25 @@ public RedisDocumentRepositoryFactory( // * @param gsonBuilder must not be {@literal null}. */ public RedisDocumentRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - Class> queryCreator, // - RedisMappingContext mappingContext, // - GsonBuilder gsonBuilder, // - FeatureExtractor featureExtractor, // - RedisOMProperties properties // + KeyValueOperations keyValueOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + Class> queryCreator, // + RedisMappingContext mappingContext, // + GsonBuilder gsonBuilder, // + FeatureExtractor featureExtractor, // + RedisOMProperties properties // ) { this( // - keyValueOperations, // - rmo, // - indexer, // - queryCreator, // - RediSearchQuery.class, // - mappingContext, // - gsonBuilder, // - featureExtractor, // - properties // + keyValueOperations, // + rmo, // + indexer, // + queryCreator, // + RediSearchQuery.class, // + mappingContext, // + gsonBuilder, // + featureExtractor, // + properties // ); } @@ -127,15 +127,15 @@ public RedisDocumentRepositoryFactory( // * @param properties must not be {@literal null}. */ public RedisDocumentRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - Class> queryCreator, // - Class repositoryQueryType, // - RedisMappingContext mappingContext, // - GsonBuilder gsonBuilder, // - FeatureExtractor featureExtractor, // - RedisOMProperties properties // + KeyValueOperations keyValueOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + Class> queryCreator, // + Class repositoryQueryType, // + RedisMappingContext mappingContext, // + GsonBuilder gsonBuilder, // + FeatureExtractor featureExtractor, // + RedisOMProperties properties // ) { super(keyValueOperations, queryCreator, repositoryQueryType); @@ -163,15 +163,15 @@ public RedisDocumentRepositoryFactory( // protected Object getTargetRepository(RepositoryInformation repositoryInformation) { EntityInformation entityInformation = getEntityInformation(repositoryInformation.getDomainType()); return super.getTargetRepositoryViaReflection( // - repositoryInformation, // - entityInformation, // - keyValueOperations, // - rmo, // - indexer, // - mappingContext, // - gsonBuilder, // - featureExtractor, // - properties // + repositoryInformation, // + entityInformation, // + keyValueOperations, // + rmo, // + indexer, // + mappingContext, // + gsonBuilder, // + featureExtractor, // + properties // ); } @@ -182,17 +182,17 @@ protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { @Override protected Optional getQueryLookupStrategy(@Nullable Key key, // - QueryMethodEvaluationContextProvider evaluationContextProvider // + QueryMethodEvaluationContextProvider evaluationContextProvider // ) { return Optional.of(new RediSearchQueryLookupStrategy(evaluationContextProvider, // - this.keyValueOperations, // - this.rmo, // - this.indexer, // - this.properties, // - this.queryCreator, // - this.repositoryQueryType, // - this.gsonBuilder // - ) // + this.keyValueOperations, // + this.rmo, // + this.indexer, // + this.properties, // + this.queryCreator, // + this.repositoryQueryType, // + this.gsonBuilder // + ) // ); } @@ -234,40 +234,40 @@ private record RediSearchQueryLookupStrategy( // @Override @SuppressWarnings("unchecked") public RepositoryQuery resolveQuery( // - Method method, // - RepositoryMetadata metadata, // - ProjectionFactory factory, // - NamedQueries namedQueries // + Method method, // + RepositoryMetadata metadata, // + ProjectionFactory factory, // + NamedQueries namedQueries // ) { QueryMethod queryMethod = new QueryMethod(method, metadata, factory); Constructor constructor = (Constructor) ClassUtils.getConstructorIfAvailable( - this.repositoryQueryType, // - QueryMethod.class, // - RepositoryMetadata.class, // - RediSearchIndexer.class, // - QueryMethodEvaluationContextProvider.class, // - KeyValueOperations.class, // - RedisModulesOperations.class, // - Class.class, // - GsonBuilder.class, // - RedisOMProperties.class); + this.repositoryQueryType, // + QueryMethod.class, // + RepositoryMetadata.class, // + RediSearchIndexer.class, // + QueryMethodEvaluationContextProvider.class, // + KeyValueOperations.class, // + RedisModulesOperations.class, // + Class.class, // + GsonBuilder.class, // + RedisOMProperties.class); Assert.state(constructor != null, String.format( - "Constructor %s(QueryMethod, RepositoryMetadata, RediSearchIndexer, EvaluationContextProvider, KeyValueOperations, RedisModulesOperations, Class, GsonBuilder, RedisOMSpringProperties) not available!", - ClassUtils.getShortName(this.repositoryQueryType))); + "Constructor %s(QueryMethod, RepositoryMetadata, RediSearchIndexer, EvaluationContextProvider, KeyValueOperations, RedisModulesOperations, Class, GsonBuilder, RedisOMSpringProperties) not available!", + ClassUtils.getShortName(this.repositoryQueryType))); return BeanUtils.instantiateClass( // - constructor, // - queryMethod, // - metadata, // - indexer, // - evaluationContextProvider, // - this.keyValueOperations, // - this.rmo, // - this.queryCreator, // - this.gsonBuilder, // - this.properties // + constructor, // + queryMethod, // + metadata, // + indexer, // + evaluationContextProvider, // + this.keyValueOperations, // + this.rmo, // + this.queryCreator, // + this.gsonBuilder, // + this.properties // ); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactoryBean.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactoryBean.java index fd2ef847..58ec1c4d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactoryBean.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisDocumentRepositoryFactoryBean.java @@ -16,7 +16,7 @@ import org.springframework.util.Assert; public class RedisDocumentRepositoryFactoryBean, S, ID> - extends KeyValueRepositoryFactoryBean { + extends KeyValueRepositoryFactoryBean { @Autowired private @Nullable RedisModulesOperations rmo; @@ -44,12 +44,12 @@ public RedisDocumentRepositoryFactoryBean(Class repositoryInterface @Override protected final RedisDocumentRepositoryFactory createRepositoryFactory( // - KeyValueOperations operations, // - Class> queryCreator, // - Class repositoryQueryType // + KeyValueOperations operations, // + Class> queryCreator, // + Class repositoryQueryType // ) { return new RedisDocumentRepositoryFactory(operations, rmo, indexer, queryCreator, repositoryQueryType, - this.mappingContext, this.gsonBuilder, this.featureExtractor, this.properties); + this.mappingContext, this.gsonBuilder, this.featureExtractor, this.properties); } @Override diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactory.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactory.java index 8fd74fb8..fa9771a3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactory.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactory.java @@ -60,12 +60,12 @@ public class RedisEnhancedRepositoryFactory extends RepositoryFactorySupport { * @param properties must not be {@literal null}. */ public RedisEnhancedRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - RedisOMProperties properties) { + KeyValueOperations keyValueOperations, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + RedisOMProperties properties) { this(keyValueOperations, redisOperations, rmo, indexer, featureExtractor, DEFAULT_QUERY_CREATOR, properties); } @@ -82,23 +82,23 @@ public RedisEnhancedRepositoryFactory( // * @param properties must not be {@literal null}. */ public RedisEnhancedRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - Class> queryCreator, // - RedisOMProperties properties) { + KeyValueOperations keyValueOperations, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + Class> queryCreator, // + RedisOMProperties properties) { this( // - keyValueOperations, // - redisOperations, // - rmo, // - indexer, // - featureExtractor, // - queryCreator, // - RedisEnhancedQuery.class, // - properties // + keyValueOperations, // + redisOperations, // + rmo, // + indexer, // + featureExtractor, // + queryCreator, // + RedisEnhancedQuery.class, // + properties // ); // } @@ -114,14 +114,14 @@ public RedisEnhancedRepositoryFactory( // * @param repositoryQueryType must not be {@literal null}. */ public RedisEnhancedRepositoryFactory( // - KeyValueOperations keyValueOperations, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - Class> queryCreator, // - Class repositoryQueryType, // - RedisOMProperties properties) { + KeyValueOperations keyValueOperations, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + Class> queryCreator, // + Class repositoryQueryType, // + RedisOMProperties properties) { Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!"); Assert.notNull(redisOperations, "RedisOperations must not be null!"); @@ -166,7 +166,7 @@ public EntityInformation getEntityInformation(Class domainClas protected Object getTargetRepository(RepositoryInformation repositoryInformation) { EntityInformation entityInformation = getEntityInformation(repositoryInformation.getDomainType()); return super.getTargetRepositoryViaReflection(repositoryInformation, entityInformation, keyValueOperations, rmo, - indexer, featureExtractor, properties); + indexer, featureExtractor, properties); } /* (non-Javadoc) @@ -189,14 +189,14 @@ protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { * org.springframework.data.repository.query.EvaluationContextProvider) */ @Override protected Optional getQueryLookupStrategy(@Nullable Key key, - QueryMethodEvaluationContextProvider evaluationContextProvider) { + QueryMethodEvaluationContextProvider evaluationContextProvider) { return Optional.of(new RedisEnhancedQueryLookupStrategy(key, evaluationContextProvider, this.keyValueOperations, // - this.redisOperations, // - this.rmo, // - this.indexer, // - this.properties, // - this.queryCreator, // - this.repositoryQueryType // + this.redisOperations, // + this.rmo, // + this.indexer, // + this.properties, // + this.queryCreator, // + this.repositoryQueryType // )); } @@ -224,15 +224,15 @@ private static class RedisEnhancedQueryLookupStrategy implements QueryLookupStra * @since 1.1 */ public RedisEnhancedQueryLookupStrategy( // - @Nullable Key key, // - QueryMethodEvaluationContextProvider evaluationContextProvider, // - KeyValueOperations keyValueOperations, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - RedisOMProperties properties, // - Class> queryCreator, // - Class repositoryQueryType) { + @Nullable Key key, // + QueryMethodEvaluationContextProvider evaluationContextProvider, // + KeyValueOperations keyValueOperations, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + RedisOMProperties properties, // + Class> queryCreator, // + Class repositoryQueryType) { Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!"); Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!"); @@ -263,40 +263,40 @@ public RedisEnhancedQueryLookupStrategy( // @Override @SuppressWarnings("unchecked") public RepositoryQuery resolveQuery( // - Method method, // - RepositoryMetadata metadata, // - ProjectionFactory factory, // - NamedQueries namedQueries // + Method method, // + RepositoryMetadata metadata, // + ProjectionFactory factory, // + NamedQueries namedQueries // ) { QueryMethod queryMethod = new QueryMethod(method, metadata, factory); Constructor constructor = (Constructor) ClassUtils.getConstructorIfAvailable( - // - this.repositoryQueryType, // - QueryMethod.class, // - RepositoryMetadata.class, // - RediSearchIndexer.class, // - QueryMethodEvaluationContextProvider.class, // - KeyValueOperations.class, // - RedisOperations.class, // - RedisModulesOperations.class, // - Class.class, // - RedisOMProperties.class); + // + this.repositoryQueryType, // + QueryMethod.class, // + RepositoryMetadata.class, // + RediSearchIndexer.class, // + QueryMethodEvaluationContextProvider.class, // + KeyValueOperations.class, // + RedisOperations.class, // + RedisModulesOperations.class, // + Class.class, // + RedisOMProperties.class); Assert.state(constructor != null, String.format( - "Constructor %s(QueryMethod, RepositoryMetadata, RediSearchIndexer, EvaluationContextProvider, KeyValueOperations, RedisOperations, RedisModulesOperations, Class, RedisOMSpringProperties) not available!", - ClassUtils.getShortName(this.repositoryQueryType))); + "Constructor %s(QueryMethod, RepositoryMetadata, RediSearchIndexer, EvaluationContextProvider, KeyValueOperations, RedisOperations, RedisModulesOperations, Class, RedisOMSpringProperties) not available!", + ClassUtils.getShortName(this.repositoryQueryType))); return BeanUtils.instantiateClass(constructor, // - queryMethod, // - metadata, // - indexer, // - evaluationContextProvider, // - this.keyValueOperations, // - this.redisOperations, // - this.rmo, // - this.queryCreator, // - this.properties // + queryMethod, // + metadata, // + indexer, // + evaluationContextProvider, // + this.keyValueOperations, // + this.redisOperations, // + this.rmo, // + this.queryCreator, // + this.properties // ); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactoryBean.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactoryBean.java index e71cf13f..f0ef4118 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactoryBean.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/RedisEnhancedRepositoryFactoryBean.java @@ -19,7 +19,7 @@ import org.springframework.util.Assert; public class RedisEnhancedRepositoryFactoryBean, S, ID> - extends RepositoryFactoryBeanSupport { + extends RepositoryFactoryBeanSupport { private @Nullable KeyValueOperations operations; private @Nullable RedisModulesOperations rmo; @@ -36,18 +36,17 @@ public class RedisEnhancedRepositoryFactoryBean, S, * interface. * * @param repositoryInterface must not be {@literal null}. - * @param redisOperations must not be {@literal null}. - * @param rmo must not be {@literal null}. - * @param indexer must not be {@literal null}. + * @param redisOperations must not be {@literal null}. + * @param rmo must not be {@literal null}. + * @param indexer must not be {@literal null}. */ public RedisEnhancedRepositoryFactoryBean( // - Class repositoryInterface, // - RedisOperations redisOperations, // - RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - FeatureExtractor featureExtractor, // - RedisOMProperties properties - ) { + Class repositoryInterface, // + RedisOperations redisOperations, // + RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + FeatureExtractor featureExtractor, // + RedisOMProperties properties) { super(repositoryInterface); setRedisModulesOperations(rmo); setRedisOperations(redisOperations); @@ -103,7 +102,7 @@ public void setRedisOMSpringProperties(RedisOMProperties properties) { } /* (non-Javadoc) - * + * * @see * org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport * #setMappingContext(org.springframework.data.mapping.context. @@ -112,8 +111,8 @@ public void setRedisOMSpringProperties(RedisOMProperties properties) { public void setMappingContext(MappingContext mappingContext) { super.setMappingContext(mappingContext); } - - public void setKeyspaceToIndexMap(RediSearchIndexer keyspaceToIndexMap) { + + public void setKeyspaceToIndexMap(RediSearchIndexer keyspaceToIndexMap) { this.indexer = keyspaceToIndexMap; } @@ -141,7 +140,7 @@ public void setQueryType(Class repositoryQueryType) { } /* (non-Javadoc) - * + * * @see * org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport * #createRepositoryFactory() */ @@ -159,15 +158,16 @@ protected final RepositoryFactorySupport createRepositoryFactory() { * @return must not be {@literal null}. */ protected RedisEnhancedRepositoryFactory createRepositoryFactory( // - KeyValueOperations operations, // - Class> queryCreator, // - Class repositoryQueryType // + KeyValueOperations operations, // + Class> queryCreator, // + Class repositoryQueryType // ) { - return new RedisEnhancedRepositoryFactory(operations, redisOperations, rmo, indexer, featureExtractor, queryCreator, RedisEnhancedQuery.class, properties); + return new RedisEnhancedRepositoryFactory(operations, redisOperations, rmo, indexer, featureExtractor, queryCreator, + RedisEnhancedQuery.class, properties); } /* (non-Javadoc) - * + * * @see * org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport * #afterPropertiesSet() */ diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisDocumentRepository.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisDocumentRepository.java index b2ad80ac..d0ecccb7 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisDocumentRepository.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisDocumentRepository.java @@ -63,44 +63,39 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static com.redis.om.spring.util.ObjectUtils.isPrimitiveOfType; -import static com.redis.om.spring.util.ObjectUtils.pageFromSlice; +import static com.redis.om.spring.util.ObjectUtils.*; import static redis.clients.jedis.json.JsonProtocol.JsonCommand; -import static com.redis.om.spring.util.ObjectUtils.getFieldsWithAnnotation; public class SimpleRedisDocumentRepository extends SimpleKeyValueRepository - implements RedisDocumentRepository { + implements RedisDocumentRepository { - private final GsonBuilder gsonBuilder; protected final RedisModulesOperations modulesOperations; protected final EntityInformation metadata; protected final KeyValueOperations operations; protected final RediSearchIndexer indexer; protected final MappingRedisOMConverter mappingConverter; + protected final EntityAuditor auditor; + protected final FeatureExtractor featureExtractor; + private final GsonBuilder gsonBuilder; private final ULIDIdentifierGenerator generator; private final RedisOMProperties properties; private final RedisMappingContext mappingContext; private final EntityStream entityStream; - protected final EntityAuditor auditor; - protected final FeatureExtractor featureExtractor; @SuppressWarnings("unchecked") public SimpleRedisDocumentRepository( // - EntityInformation metadata, // - KeyValueOperations operations, // - @Qualifier("redisModulesOperations") RedisModulesOperations rmo, // - RediSearchIndexer indexer, // - RedisMappingContext mappingContext, - GsonBuilder gsonBuilder, - FeatureExtractor featureExtractor, // - RedisOMProperties properties) { + EntityInformation metadata, // + KeyValueOperations operations, // + @Qualifier("redisModulesOperations") RedisModulesOperations rmo, // + RediSearchIndexer indexer, // + RedisMappingContext mappingContext, GsonBuilder gsonBuilder, FeatureExtractor featureExtractor, // + RedisOMProperties properties) { super(metadata, operations); this.modulesOperations = (RedisModulesOperations) rmo; this.metadata = metadata; this.operations = operations; this.indexer = indexer; - this.mappingConverter = new MappingRedisOMConverter(null, - new ReferenceResolverImpl(modulesOperations.template())); + this.mappingConverter = new MappingRedisOMConverter(null, new ReferenceResolverImpl(modulesOperations.template())); this.generator = ULIDIdentifierGenerator.INSTANCE; this.gsonBuilder = gsonBuilder; this.mappingContext = mappingContext; @@ -122,8 +117,7 @@ public Iterable getIds() { SearchResult searchResult = getSearchOps().search(query); return searchResult.getDocuments().stream() - .map(d -> gson.fromJson(SafeEncoder.encode((byte[])d.get(idField)), metadata.getIdType())) - .toList(); + .map(d -> gson.fromJson(SafeEncoder.encode((byte[]) d.get(idField)), metadata.getIdType())).toList(); } @Override @@ -143,17 +137,16 @@ public void deleteById(ID id, Path2 path) { @Override public void updateField(T entity, MetamodelField field, Object value) { - modulesOperations.opsForJSON().set(getKey(Objects.requireNonNull(metadata.getId(entity))), value, - Path2.of(field.getJSONPath())); + modulesOperations.opsForJSON() + .set(getKey(Objects.requireNonNull(metadata.getId(entity))), value, Path2.of(field.getJSONPath())); } @SuppressWarnings("unchecked") @Override public Iterable getFieldsByIds(Iterable ids, MetamodelField field) { String[] keys = StreamSupport.stream(ids.spliterator(), false).map(this::getKey).toArray(String[]::new); - return (Iterable) modulesOperations.opsForJSON() - .mget(Path2.of(field.getJSONPath()), List.class, keys).stream().flatMap(List::stream) - .toList(); + return (Iterable) modulesOperations.opsForJSON().mget(Path2.of(field.getJSONPath()), List.class, keys).stream() + .flatMap(List::stream).toList(); } @Override @@ -174,10 +167,12 @@ public List saveAll(Iterable entities) { boolean isNew = metadata.isNew(entity); KeyValuePersistentEntity keyValueEntity = mappingConverter.getMappingContext() - .getRequiredPersistentEntity(ClassUtils.getUserClass(entity)); - Object id = isNew ? generator.generateIdentifierOfType(Objects.requireNonNull(keyValueEntity.getIdProperty()).getTypeInformation()) - : keyValueEntity.getPropertyAccessor(entity).getProperty( - Objects.requireNonNull(keyValueEntity.getIdProperty())); + .getRequiredPersistentEntity(ClassUtils.getUserClass(entity)); + Object id = isNew ? + generator.generateIdentifierOfType( + Objects.requireNonNull(keyValueEntity.getIdProperty()).getTypeInformation()) : + keyValueEntity.getPropertyAccessor(entity) + .getProperty(Objects.requireNonNull(keyValueEntity.getIdProperty())); keyValueEntity.getPropertyAccessor(entity).setProperty(keyValueEntity.getIdProperty(), id); String keyspace = keyValueEntity.getKeySpace(); @@ -200,7 +195,10 @@ public List saveAll(Iterable entities) { processReferenceAnnotations(objectKey, entity, pipeline); - maybeTtl.ifPresent(ttl -> { if (ttl > 0) pipeline.expire(objectKey, ttl); }); + maybeTtl.ifPresent(ttl -> { + if (ttl > 0) + pipeline.expire(objectKey, ttl); + }); saved.add(entity); } @@ -210,7 +208,8 @@ public List saveAll(Iterable entities) { return saved; } - @Override public Iterable bulkLoad(String file) throws IOException { + @Override + public Iterable bulkLoad(String file) throws IOException { try (Reader reader = Files.newBufferedReader(Paths.get(file))) { Gson gson = gsonBuilder.create(); List entities = gson.fromJson(reader, new GsonListOfType<>(metadata.getJavaType())); @@ -230,12 +229,10 @@ public void delete(T entity) { } @Override - public List findAllById(Iterable ids) { + public List findAllById(Iterable ids) { String[] keys = StreamSupport.stream(ids.spliterator(), false).map(this::getKey).toArray(String[]::new); - return modulesOperations.opsForJSON() - .mget(metadata.getJavaType(), keys).stream() - .toList(); + return modulesOperations.opsForJSON().mget(metadata.getJavaType(), keys).stream().toList(); } @Override @@ -302,7 +299,8 @@ private Optional getTTLForEntity(Object entity) { try { Field fld = ReflectionUtils.findField(entity.getClass(), settings.getTimeToLivePropertyName()); ttlGetter = ObjectUtils.getGetterForField(entity.getClass(), Objects.requireNonNull(fld)); - long ttlPropertyValue = ((Number) Objects.requireNonNull(ReflectionUtils.invokeMethod(ttlGetter, entity))).longValue(); + long ttlPropertyValue = ((Number) Objects.requireNonNull( + ReflectionUtils.invokeMethod(ttlGetter, entity))).longValue(); ReflectionUtils.invokeMethod(ttlGetter, entity); @@ -328,15 +326,15 @@ private void checkVersion(T entity) { BeanWrapper wrapper = new BeanWrapperImpl(entity); Field versionField = fields.get(0); String property = versionField.getName(); - if ((versionField.getType() == Integer.class || isPrimitiveOfType(versionField.getType(), Integer.class)) || - (versionField.getType() == Long.class || isPrimitiveOfType(versionField.getType(), Long.class))) { + if ((versionField.getType() == Integer.class || isPrimitiveOfType(versionField.getType(), + Integer.class)) || (versionField.getType() == Long.class || isPrimitiveOfType(versionField.getType(), + Long.class))) { Number version = (Number) wrapper.getPropertyValue(property); Number dbVersion = getEntityVersion(getKey(this.metadata.getRequiredId(entity)), property); if (dbVersion != null && version != null && dbVersion.longValue() != version.longValue()) { throw new OptimisticLockingFailureException( - String.format("Cannot delete entity %s with version %s as it is outdated", entity, - version)); + String.format("Cannot delete entity %s with version %s as it is outdated", entity, version)); } } } @@ -344,7 +342,8 @@ private void checkVersion(T entity) { private Number getEntityVersion(String key, String versionProperty) { JSONOperations ops = modulesOperations.opsForJSON(); - Class type = new TypeToken() {}.getRawType(); + Class type = new TypeToken() { + }.getRawType(); Long[] dbVersionArray = (Long[]) ops.get(key, type, Path2.of("$." + versionProperty)); return dbVersionArray != null ? dbVersionArray[0] : null; } @@ -403,8 +402,7 @@ public Page findAll(Pageable pageable) { Gson gson = gsonBuilder.create(); List content = searchResult.getDocuments().stream() - .map(d -> gson.fromJson(SafeEncoder.encode((byte[]) d.get("$")), metadata.getJavaType())) - .toList(); + .map(d -> gson.fromJson(SafeEncoder.encode((byte[]) d.get("$")), metadata.getJavaType())).toList(); return new PageImpl<>(content, pageable, searchResult.getTotalResults()); } else { @@ -450,7 +448,8 @@ public R findBy(Example example, Function(example, example.getProbeType(), entityStream, getSearchOps())); + return queryFunction.apply( + new FluentQueryByExample<>(example, example.getProbeType(), entityStream, getSearchOps())); } private SearchOperations getSearchOps() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisEnhancedRepository.java b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisEnhancedRepository.java index 44d99895..24916274 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisEnhancedRepository.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/repository/support/SimpleRedisEnhancedRepository.java @@ -48,7 +48,7 @@ import static com.redis.om.spring.util.ObjectUtils.pageFromSlice; public class SimpleRedisEnhancedRepository extends SimpleKeyValueRepository - implements RedisEnhancedRepository { + implements RedisEnhancedRepository { protected final RedisModulesOperations modulesOperations; protected final EntityInformation metadata; @@ -78,9 +78,9 @@ public SimpleRedisEnhancedRepository( // this.metadata = metadata; this.operations = operations; this.indexer = indexer; - this.mappingConverter = new MappingRedisOMConverter(null, - new ReferenceResolverImpl(modulesOperations.template())); - this.enhancedKeyValueAdapter = new RedisEnhancedKeyValueAdapter(rmo.template(), rmo, indexer, featureExtractor, properties); + this.mappingConverter = new MappingRedisOMConverter(null, new ReferenceResolverImpl(modulesOperations.template())); + this.enhancedKeyValueAdapter = new RedisEnhancedKeyValueAdapter(rmo.template(), rmo, indexer, featureExtractor, + properties); this.generator = ULIDIdentifierGenerator.INSTANCE; this.auditor = new EntityAuditor(modulesOperations.template()); this.featureExtractor = featureExtractor; @@ -98,16 +98,16 @@ public Iterable getIds() { SearchOperations searchOps = modulesOperations.opsForSearch(maybeSearchIndex.get()); Optional maybeIdField = ObjectUtils.getIdFieldForEntityClass(metadata.getJavaType()); String idField = maybeIdField.map(Field::getName).orElse("id"); - + Query query = new Query("*"); query.limit(0, MAX_SEARCH_RESULTS); query.returnFields(idField); SearchResult searchResult = searchOps.search(query); - + result = (List) searchResult.getDocuments().stream() // - .map(d -> ObjectUtils.documentToObject(d, metadata.getJavaType(), mappingConverter)) // - .map(e -> ObjectUtils.getIdFieldForEntity(maybeIdField.get(), e)) // - .toList(); + .map(d -> ObjectUtils.documentToObject(d, metadata.getJavaType(), mappingConverter)) // + .map(e -> ObjectUtils.getIdFieldForEntity(maybeIdField.get(), e)) // + .toList(); } return result; @@ -119,14 +119,14 @@ public Page getIds(Pageable pageable) { int fromIndex = Long.valueOf(pageable.getOffset()).intValue(); int toIndex = fromIndex + pageable.getPageSize(); - + return new PageImpl<>(ids.subList(fromIndex, toIndex), pageable, ids.size()); } @Override public void updateField(T entity, MetamodelField field, Object value) { - PartialUpdate update = new PartialUpdate<>(metadata.getId(entity).toString(), metadata.getJavaType()) - .set(field.getSearchAlias(), value); + PartialUpdate update = new PartialUpdate<>(metadata.getId(entity).toString(), metadata.getJavaType()).set( + field.getSearchAlias(), value); enhancedKeyValueAdapter.update(update); } @@ -136,11 +136,11 @@ public void updateField(T entity, MetamodelField field, Object value) { public Iterable getFieldsByIds(Iterable ids, MetamodelField field) { RedisTemplate template = modulesOperations.template(); List keys = StreamSupport.stream(ids.spliterator(), false) // - .map(this::getKey).toList(); + .map(this::getKey).toList(); return (Iterable) keys.stream() // - .map(key -> template.opsForHash().get(key, field.getSearchAlias())) // - .collect(Collectors.toList()); + .map(key -> template.opsForHash().get(key, field.getSearchAlias())) // + .collect(Collectors.toList()); } @Override @@ -150,7 +150,7 @@ public Long getExpiration(ID id) { } /* (non-Javadoc) - * + * * @see org.springframework.data.repository.CrudRepository#findAll() */ @Override public List findAll() { @@ -162,7 +162,7 @@ public List findAll() { // ------------------------------------------------------------------------- /* (non-Javadoc) - * + * * @see * org.springframework.data.repository.PagingAndSortingRepository#findAll(org. * springframework.data.domain.Sort) */ @@ -170,14 +170,14 @@ public List findAll() { public List findAll(Sort sort) { Assert.notNull(sort, "Sort must not be null!"); - + Pageable pageRequest = PageRequest.of(0, properties.getRepository().getQuery().getLimit(), sort); return findAll(pageRequest).toList(); } /* (non-Javadoc) - * + * * @see * org.springframework.data.repository.PagingAndSortingRepository#findAll(org. * springframework.data.domain.Pageable) */ @@ -205,19 +205,18 @@ public Page findAll(Pageable pageable) { SearchResult searchResult = searchOps.search(query); - @SuppressWarnings("unchecked") - List content = (List) searchResult.getDocuments().stream() // - .map(d -> ObjectUtils.documentToObject(d, metadata.getJavaType(), mappingConverter)) // - .toList(); + @SuppressWarnings("unchecked") List content = (List) searchResult.getDocuments().stream() // + .map(d -> ObjectUtils.documentToObject(d, metadata.getJavaType(), mappingConverter)) // + .toList(); return new PageImpl<>(content, pageable, searchResult.getTotalResults()); } else { return Page.empty(); } - + } else { Iterable content = operations.findInRange(pageable.getOffset(), pageable.getPageSize(), pageable.getSort(), - metadata.getJavaType()); + metadata.getJavaType()); return new PageImpl<>(IterableConverter.toList(content), pageable, this.operations.count(metadata.getJavaType())); } @@ -227,7 +226,7 @@ public Page findAll(Pageable pageable) { public String getKeyspace() { return indexer.getKeyspaceForEntityClass(metadata.getJavaType()); } - + private String getKey(Object id) { return getKeyspace() + id.toString(); } @@ -243,8 +242,11 @@ public List saveAll(Iterable entities) { for (S entity : entities) { boolean isNew = metadata.isNew(entity); - KeyValuePersistentEntity keyValueEntity = mappingConverter.getMappingContext().getRequiredPersistentEntity(ClassUtils.getUserClass(entity)); - Object id = isNew ? generator.generateIdentifierOfType(keyValueEntity.getIdProperty().getTypeInformation()) : keyValueEntity.getPropertyAccessor(entity).getProperty(keyValueEntity.getIdProperty()); + KeyValuePersistentEntity keyValueEntity = mappingConverter.getMappingContext() + .getRequiredPersistentEntity(ClassUtils.getUserClass(entity)); + Object id = isNew ? + generator.generateIdentifierOfType(keyValueEntity.getIdProperty().getTypeInformation()) : + keyValueEntity.getPropertyAccessor(entity).getProperty(keyValueEntity.getIdProperty()); keyValueEntity.getPropertyAccessor(entity).setProperty(keyValueEntity.getIdProperty(), id); String keyspace = keyValueEntity.getKeySpace(); @@ -322,7 +324,8 @@ public R findBy(Example example, Function(example, example.getProbeType(), entityStream, getSearchOps())); + return queryFunction.apply( + new FluentQueryByExample<>(example, example.getProbeType(), entityStream, getSearchOps())); } private SearchOperations getSearchOps() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationPage.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationPage.java index e03a1ab6..26204ddc 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationPage.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationPage.java @@ -13,17 +13,18 @@ import java.util.function.Function; public class AggregationPage implements Slice, Serializable { - private List content; private final transient Pageable pageable; - private transient AggregationStream aggregationStream; - private long cursorId = -1; - private AggregationResult aggregationResult; private final transient Gson gson; private final Class entityClass; private final boolean isDocument; private final transient MappingRedisOMConverter mappingConverter; + private List content; + private transient AggregationStream aggregationStream; + private long cursorId = -1; + private AggregationResult aggregationResult; - public AggregationPage(AggregationStream aggregationStream, Pageable pageable, Class entityClass, Gson gson, MappingRedisOMConverter mappingConverter, boolean isDocument) { + public AggregationPage(AggregationStream aggregationStream, Pageable pageable, Class entityClass, Gson gson, + MappingRedisOMConverter mappingConverter, boolean isDocument) { this.aggregationStream = aggregationStream; this.pageable = pageable; this.entityClass = entityClass; @@ -32,7 +33,8 @@ public AggregationPage(AggregationStream aggregationStream, Pageable pageable this.mappingConverter = mappingConverter; } - public AggregationPage(AggregationResult aggregationResult, Pageable pageable, Class entityClass, Gson gson, MappingRedisOMConverter mappingConverter, boolean isDocument) { + public AggregationPage(AggregationResult aggregationResult, Pageable pageable, Class entityClass, Gson gson, + MappingRedisOMConverter mappingConverter, boolean isDocument) { this.aggregationResult = aggregationResult; this.pageable = pageable; this.entityClass = entityClass; @@ -58,7 +60,7 @@ public int getNumberOfElements() { } @Override - public List getContent() { + public List getContent() { return resolveContent(); } @@ -68,7 +70,7 @@ public boolean hasContent() { } @Override - public Sort getSort() { + public Sort getSort() { return pageable.getSort(); } @@ -88,17 +90,16 @@ public boolean hasNext() { } @Override - public Pageable nextPageable() { + public Pageable nextPageable() { Pageable next = PageRequest.of(getNumber() + 1, pageable.getPageSize(), pageable.getSort()); return hasNext() ? new AggregationPageable(next, resolveAggregation().getCursorId()) : Pageable.unpaged(); } @Override - public Slice map(Function converter) { + public Slice map(Function converter) { return new SliceImpl<>(getConvertedContent(converter), pageable, hasNext()); } - @Override public Iterator iterator() { return resolveContent().iterator(); @@ -111,7 +112,7 @@ public boolean hasPrevious() { } @Override - public Pageable previousPageable() { + public Pageable previousPageable() { return Pageable.unpaged(); } // END - Unsupported operations @@ -148,9 +149,11 @@ protected List getConvertedContent(Function conve @SuppressWarnings("unchecked") List toEntityList(AggregationResult aggregationResult) { if (isDocument) { - return aggregationResult.getResults().stream().map(d -> gson.fromJson(d.get("$").toString(), entityClass)).toList(); + return aggregationResult.getResults().stream().map(d -> gson.fromJson(d.get("$").toString(), entityClass)) + .toList(); } else { - return aggregationResult.getResults().stream().map(h -> (E) ObjectUtils.mapToObject(h, entityClass, mappingConverter)).toList(); + return aggregationResult.getResults().stream() + .map(h -> (E) ObjectUtils.mapToObject(h, entityClass, mappingConverter)).toList(); } } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStream.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStream.java index ce97c0e0..5a0b4ae1 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStream.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStream.java @@ -24,7 +24,7 @@ public interface AggregationStream { AggregationStream sorted(Order... fields); - AggregationStream sorted(int max, Order ...fields); + AggregationStream sorted(int max, Order... fields); AggregationStream reduce(ReducerFunction reducer); @@ -52,6 +52,8 @@ public interface AggregationStream { // Cursor API AggregationStream cursor(int i, Duration duration); + Slice toList(PageRequest pageRequest, Class... contentTypes); + Slice toList(PageRequest pageRequest, Duration duration, Class... contentTypes); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStreamImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStreamImpl.java index 4dc2bdb3..8ff344e5 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStreamImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/AggregationStreamImpl.java @@ -22,98 +22,19 @@ import java.util.*; public class AggregationStreamImpl implements AggregationStream { + private static final Integer MAX_LIMIT = 10000; private final Class entityClass; private final boolean isDocument; private final AggregationBuilder aggregation; - private Group currentGroup; - private ReducerFieldPair currentReducer; private final MappingRedisOMConverter mappingConverter; private final Gson gson; - private final SearchOperations search; private final Set returnFields = new LinkedHashSet<>(); private final Map> returnFieldsTypeHints = new HashMap<>(); - - private static final Integer MAX_LIMIT = 10000; + private Group currentGroup; + private ReducerFieldPair currentReducer; private boolean limitSet = false; - private static class ReducerFieldPair { - private String alias; - private final Reducer reducer; - private final MetamodelField field; - - private final ReducerFunction reducerFunction; - - private ReducerFieldPair(Reducer reducer, MetamodelField field, ReducerFunction reducerFunction) { - this.reducer = reducer; - this.field = field; - this.reducerFunction = reducerFunction; - } - - public static ReducerFieldPair of(Reducer reducer, MetamodelField field, ReducerFunction reducerFunction) { - return new ReducerFieldPair(reducer, field, reducerFunction); - } - - public Reducer getReducer() { - return this.reducer; - } - - public MetamodelField getField() { - return this.field; - } - - public String getAlias() { - return this.alias; - } - - public void setAlias(String alias) { - this.alias = alias; - reducer.as(alias); - } - - public ReducerFunction getReducerFunction() { - return reducerFunction; - } - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof ReducerFieldPair other)) - return false; - if (!other.canEqual(this)) - return false; - final Object this$reducer = this.getReducer(); - final Object other$reducer = other.getReducer(); - if (!Objects.equals(this$reducer, other$reducer)) - return false; - final Object this$field = this.getField(); - final Object other$field = other.getField(); - if (!Objects.equals(this$field, other$field)) - return false; - final Object this$alias = this.getAlias(); - final Object other$alias = other.getAlias(); - return Objects.equals(this$alias, other$alias); - } - - protected boolean canEqual(final Object other) { - return other instanceof AggregationStreamImpl.ReducerFieldPair; - } - - public int hashCode() { - final int PRIME = 59; - int result = 1; - final Object $reducer = this.getReducer(); - result = result * PRIME + ($reducer == null ? 43 : $reducer.hashCode()); - final Object $field = this.getField(); - result = result * PRIME + ($field == null ? 43 : $field.hashCode()); - return result; - } - - public String toString() { - return "AggregationStreamImpl.ReducerFieldPair(reducer=" + this.getReducer() + ", field=" + this.getField() + ")"; - } - } - @SafeVarargs public AggregationStreamImpl(String searchIndex, RedisModulesOperations modulesOperations, Gson gson, Class entityClass, String query, MetamodelField... fields) { @@ -454,8 +375,6 @@ public List toList(Class... contentTypes) { return (List) asList; } - // Cursor API - @Override public AggregationStream cursor(int count, Duration timeout) { applyCurrentGroupBy(); @@ -463,8 +382,10 @@ public AggregationStream cursor(int count, Duration timeout) { return this; } + // Cursor API + @Override - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public Slice toList(PageRequest pageRequest, Class... contentTypes) { applyCurrentGroupBy(); aggregation.cursor(pageRequest.getPageSize(), 300000); @@ -472,7 +393,7 @@ public Slice toList(PageRequest pageRequest, Class... conten } @Override - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public Slice toList(PageRequest pageRequest, Duration timeout, Class... contentTypes) { applyCurrentGroupBy(); aggregation.cursor(pageRequest.getPageSize(), timeout.toMillis()); @@ -527,4 +448,80 @@ List toEntityList(AggregationResult aggregationResult) { } } + private static class ReducerFieldPair { + private final Reducer reducer; + private final MetamodelField field; + private final ReducerFunction reducerFunction; + private String alias; + + private ReducerFieldPair(Reducer reducer, MetamodelField field, ReducerFunction reducerFunction) { + this.reducer = reducer; + this.field = field; + this.reducerFunction = reducerFunction; + } + + public static ReducerFieldPair of(Reducer reducer, MetamodelField field, ReducerFunction reducerFunction) { + return new ReducerFieldPair(reducer, field, reducerFunction); + } + + public Reducer getReducer() { + return this.reducer; + } + + public MetamodelField getField() { + return this.field; + } + + public String getAlias() { + return this.alias; + } + + public void setAlias(String alias) { + this.alias = alias; + reducer.as(alias); + } + + public ReducerFunction getReducerFunction() { + return reducerFunction; + } + + public boolean equals(final Object o) { + if (o == this) + return true; + if (!(o instanceof ReducerFieldPair other)) + return false; + if (!other.canEqual(this)) + return false; + final Object this$reducer = this.getReducer(); + final Object other$reducer = other.getReducer(); + if (!Objects.equals(this$reducer, other$reducer)) + return false; + final Object this$field = this.getField(); + final Object other$field = other.getField(); + if (!Objects.equals(this$field, other$field)) + return false; + final Object this$alias = this.getAlias(); + final Object other$alias = other.getAlias(); + return Objects.equals(this$alias, other$alias); + } + + protected boolean canEqual(final Object other) { + return other instanceof AggregationStreamImpl.ReducerFieldPair; + } + + public int hashCode() { + final int PRIME = 59; + int result = 1; + final Object $reducer = this.getReducer(); + result = result * PRIME + ($reducer == null ? 43 : $reducer.hashCode()); + final Object $field = this.getField(); + result = result * PRIME + ($field == null ? 43 : $field.hashCode()); + return result; + } + + public String toString() { + return "AggregationStreamImpl.ReducerFieldPair(reducer=" + this.getReducer() + ", field=" + this.getField() + ")"; + } + } + } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ExampleToNodeConverter.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ExampleToNodeConverter.java index e142b66e..ca0cd1f6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ExampleToNodeConverter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ExampleToNodeConverter.java @@ -62,7 +62,8 @@ public Node processExample(Example example, Node rootNode) { if (values.iterator().hasNext()) { QueryNode and = QueryBuilders.intersect(); for (Object v : values) { - if (!v.toString().isBlank()) and.add(fieldName, "{" + v + "}"); + if (!v.toString().isBlank()) + and.add(fieldName, "{" + v + "}"); } if (matchingAll) { rootNode = QueryBuilders.intersect(rootNode, and); @@ -83,14 +84,19 @@ public Node processExample(Example example, Node rootNode) { // else if (schemaField instanceof TextField) { switch (example.getMatcher().getDefaultStringMatcher()) { - case DEFAULT, EXACT -> - rootNode = isNotEmpty(value) ? QueryBuilders.intersect(rootNode).add(fieldName, QueryUtils.escape(value.toString(), false)) : rootNode; - case STARTING -> - rootNode = isNotEmpty(value) ? QueryBuilders.intersect(rootNode).add(fieldName, QueryUtils.escape(value.toString(), false) + "*") : rootNode; - case ENDING -> - rootNode = isNotEmpty(value) ? QueryBuilders.intersect(rootNode).add(fieldName, "*" + QueryUtils.escape(value.toString(), false)) : rootNode; - case CONTAINING -> - rootNode = isNotEmpty(value) ? QueryBuilders.intersect(rootNode).add(fieldName, "*" + QueryUtils.escape(value.toString(), false) + "*") : rootNode; + case DEFAULT, EXACT -> rootNode = isNotEmpty(value) ? + QueryBuilders.intersect(rootNode).add(fieldName, QueryUtils.escape(value.toString(), false)) : + rootNode; + case STARTING -> rootNode = isNotEmpty(value) ? + QueryBuilders.intersect(rootNode).add(fieldName, QueryUtils.escape(value.toString(), false) + "*") : + rootNode; + case ENDING -> rootNode = isNotEmpty(value) ? + QueryBuilders.intersect(rootNode).add(fieldName, "*" + QueryUtils.escape(value.toString(), false)) : + rootNode; + case CONTAINING -> rootNode = isNotEmpty(value) ? + QueryBuilders.intersect(rootNode) + .add(fieldName, "*" + QueryUtils.escape(value.toString(), false) + "*") : + rootNode; case REGEX -> { // NOT SUPPORTED } @@ -144,11 +150,14 @@ else if (schemaField instanceof NumericField) { } else if (elementClass == Instant.class) { and.add(QueryBuilders.intersect(rootNode).add(fieldName, JedisValues.eq((Instant) v))); } else if (elementClass == Integer.class) { - and.add(QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Integer.parseInt(v.toString())))); + and.add( + QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Integer.parseInt(v.toString())))); } else if (elementClass == Long.class) { - and.add(QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Long.parseLong(v.toString())))); + and.add( + QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Long.parseLong(v.toString())))); } else if (elementClass == Double.class) { - and.add(QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Double.parseDouble(v.toString())))); + and.add(QueryBuilders.intersect(rootNode) + .add(fieldName, Values.eq(Double.parseDouble(v.toString())))); } } else { if (elementClass == LocalDate.class) { @@ -160,11 +169,13 @@ else if (schemaField instanceof NumericField) { } else if (elementClass == Instant.class) { and.add(QueryBuilders.union(rootNode).add(fieldName, JedisValues.eq((Instant) v))); } else if (elementClass == Integer.class) { - and.add(QueryBuilders.union(rootNode).add(fieldName, Values.eq(Integer.parseInt(v.toString())))); + and.add( + QueryBuilders.union(rootNode).add(fieldName, Values.eq(Integer.parseInt(v.toString())))); } else if (elementClass == Long.class) { and.add(QueryBuilders.union(rootNode).add(fieldName, Values.eq(Long.parseLong(v.toString())))); } else if (elementClass == Double.class) { - and.add(QueryBuilders.union(rootNode).add(fieldName, Values.eq(Double.parseDouble(v.toString())))); + and.add( + QueryBuilders.union(rootNode).add(fieldName, Values.eq(Double.parseDouble(v.toString())))); } } } @@ -185,11 +196,14 @@ else if (schemaField instanceof NumericField) { } else if (cls == Instant.class) { rootNode = QueryBuilders.intersect(rootNode).add(fieldName, JedisValues.eq((Instant) value)); } else if (cls == Integer.class) { - rootNode = QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Integer.parseInt(value.toString()))); + rootNode = QueryBuilders.intersect(rootNode) + .add(fieldName, Values.eq(Integer.parseInt(value.toString()))); } else if (cls == Long.class) { - rootNode = QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Long.parseLong(value.toString()))); + rootNode = QueryBuilders.intersect(rootNode) + .add(fieldName, Values.eq(Long.parseLong(value.toString()))); } else if (cls == Double.class) { - rootNode = QueryBuilders.intersect(rootNode).add(fieldName, Values.eq(Double.parseDouble(value.toString()))); + rootNode = QueryBuilders.intersect(rootNode) + .add(fieldName, Values.eq(Double.parseDouble(value.toString()))); } } else { if (cls == LocalDate.class) { @@ -201,11 +215,14 @@ else if (schemaField instanceof NumericField) { } else if (cls == Instant.class) { rootNode = QueryBuilders.union(rootNode).add(fieldName, JedisValues.eq((Instant) value)); } else if (cls == Integer.class) { - rootNode = QueryBuilders.union(rootNode).add(fieldName, Values.eq(Integer.parseInt(value.toString()))); + rootNode = QueryBuilders.union(rootNode) + .add(fieldName, Values.eq(Integer.parseInt(value.toString()))); } else if (cls == Long.class) { - rootNode = QueryBuilders.union(rootNode).add(fieldName, Values.eq(Long.parseLong(value.toString()))); + rootNode = QueryBuilders.union(rootNode) + .add(fieldName, Values.eq(Long.parseLong(value.toString()))); } else if (cls == Double.class) { - rootNode = QueryBuilders.union(rootNode).add(fieldName, Values.eq(Double.parseDouble(value.toString()))); + rootNode = QueryBuilders.union(rootNode) + .add(fieldName, Values.eq(Double.parseDouble(value.toString()))); } } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/FluentQueryByExample.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/FluentQueryByExample.java index 05d29881..166968c9 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/FluentQueryByExample.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/FluentQueryByExample.java @@ -14,17 +14,17 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -public class FluentQueryByExample implements FluentQuery.FetchableFluentQuery { +public class FluentQueryByExample implements FluentQuery.FetchableFluentQuery { private final SearchStream searchStream; private final Class probeType; private final SearchOperations searchOps; public FluentQueryByExample( // - Example example, // - Class probeType, // - EntityStream entityStream, // - SearchOperations searchOps // + Example example, // + Class probeType, // + EntityStream entityStream, // + SearchOperations searchOps // ) { this.probeType = probeType; this.searchOps = searchOps; @@ -46,9 +46,8 @@ public FetchableFluentQuery as(Class resultType) { @Override @SuppressWarnings("unchecked") public FetchableFluentQuery project(Collection properties) { - List> metamodelFields = MetamodelUtils.getMetamodelFieldsForProperties(probeType, - properties); - metamodelFields.forEach(mmf -> searchStream.project((MetamodelField) mmf)); + List> metamodelFields = MetamodelUtils.getMetamodelFieldsForProperties(probeType, properties); + metamodelFields.forEach(mmf -> searchStream.project((MetamodelField) mmf)); return this; } @@ -83,7 +82,8 @@ public Page page(Pageable pageable) { query.limit(0, 0); SearchResult searchResult = searchOps.search(query); var count = searchResult.getTotalResults(); - var pageContents = searchStream.limit(pageable.getPageSize()).skip(pageable.getOffset()).collect(Collectors.toList()); + var pageContents = searchStream.limit(pageable.getPageSize()).skip(pageable.getOffset()) + .collect(Collectors.toList()); return new PageImpl<>(pageContents, pageable, count); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ReturnFieldsSearchStreamImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ReturnFieldsSearchStreamImpl.java index daac4792..b8379a55 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ReturnFieldsSearchStreamImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/ReturnFieldsSearchStreamImpl.java @@ -41,10 +41,10 @@ public class ReturnFieldsSearchStreamImpl implements SearchStream { private final SearchStreamImpl entitySearchStream; private final List> returning; - private Stream resolvedStream; - private Runnable closeHandler; private final boolean useNoContent; private final boolean isDocument; + private Stream resolvedStream; + private Runnable closeHandler; public ReturnFieldsSearchStreamImpl( // SearchStreamImpl entitySearchStream, // @@ -128,6 +128,7 @@ public SearchStream filter(Example example) { throw new UnsupportedOperationException("Filter on Example predicate is not supported on mapped stream"); } + @SuppressWarnings("resource") @Override public SearchStream map(Function mapper) { return new WrapperSearchStream<>(resolveStream()).map(mapper); @@ -148,21 +149,25 @@ public DoubleStream mapToDouble(ToDoubleFunction mapper) { return resolveStream().mapToDouble(mapper); } + @SuppressWarnings("resource") @Override public SearchStream flatMap(Function> mapper) { return new WrapperSearchStream<>(resolveStream()).flatMap(mapper); } + @SuppressWarnings("resource") @Override public IntStream flatMapToInt(Function mapper) { return new WrapperSearchStream<>(resolveStream()).flatMapToInt(mapper); } + @SuppressWarnings("resource") @Override public LongStream flatMapToLong(Function mapper) { return new WrapperSearchStream<>(resolveStream()).flatMapToLong(mapper); } + @SuppressWarnings("resource") @Override public DoubleStream flatMapToDouble(Function mapper) { return new WrapperSearchStream<>(resolveStream()).flatMapToDouble(mapper); @@ -294,32 +299,34 @@ private Stream resolveStream() { if (!searchResult.getDocuments().isEmpty()) { String keySample = searchResult.getDocuments().get(0).getId(); int idBegin = keySample.indexOf(":") + 1; - resolvedStream = (Stream) searchResult.getDocuments().stream().map(Document::getId).map(key -> key.substring(idBegin)); + resolvedStream = (Stream) searchResult.getDocuments().stream().map(Document::getId) + .map(key -> key.substring(idBegin)); } else { resolvedStream = Stream.empty(); } } else { - boolean returningFullEntity = (returning.stream().anyMatch(foi -> foi.getSearchAlias().equalsIgnoreCase("__this"))); + boolean returningFullEntity = (returning.stream() + .anyMatch(foi -> foi.getSearchAlias().equalsIgnoreCase("__this"))); String[] returnFields = !returningFullEntity ? returning.stream() // - .map(foi -> ObjectUtils.isCollection(foi.getTargetClass()) ? "$." + foi.getSearchAlias() : foi.getSearchAlias()) - .toArray(String[]::new) : new String[]{}; + .map( + foi -> ObjectUtils.isCollection(foi.getTargetClass()) ? "$." + foi.getSearchAlias() : foi.getSearchAlias()) + .toArray(String[]::new) : new String[] {}; boolean resultSetHasNonIndexedFields = returning.stream().anyMatch(foi -> !foi.isIndexed()); if (resultSetHasNonIndexedFields) { SearchResult searchResult = entitySearchStream.getOps().search(query); - List entities = searchResult - .getDocuments() // - .stream() // - .map(d -> { // - if (isDocument) { - return gson.fromJson(SafeEncoder.encode((byte[])d.get("$")), entitySearchStream.getEntityClass()); - } else { - return (E) ObjectUtils.documentToObject(d, entitySearchStream.getEntityClass(), mappingConverter); - } - }).toList(); + List entities = searchResult.getDocuments() // + .stream() // + .map(d -> { // + if (isDocument) { + return gson.fromJson(SafeEncoder.encode((byte[]) d.get("$")), entitySearchStream.getEntityClass()); + } else { + return (E) ObjectUtils.documentToObject(d, entitySearchStream.getEntityClass(), mappingConverter); + } + }).toList(); results = toResultTuple(entities, returnFields); @@ -338,7 +345,7 @@ private List toResultTuple(SearchResult searchResult, String[] returnFields) List results = new ArrayList<>(); searchResult.getDocuments().forEach(doc -> { Map props = StreamSupport.stream(doc.getProperties().spliterator(), false) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); List mappedResults = new ArrayList<>(); returning.forEach(foi -> { @@ -394,7 +401,8 @@ public Stream> mapToLabelledMaps() { return resolveStream().map(Tuple.class::cast).map(Tuple::labelledMap); } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream groupBy(MetamodelField... field) { throw new UnsupportedOperationException("groupBy is not supported on a ReturnFieldSearchStream"); } @@ -404,7 +412,8 @@ public AggregationStream apply(String expression, String alias) { throw new UnsupportedOperationException("apply is not supported on a ReturnFieldSearchStream"); } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream load(MetamodelField... fields) { throw new UnsupportedOperationException("load is not supported on a ReturnFieldSearchStream"); } @@ -424,7 +433,8 @@ public Optional max(NumericField field) { throw new UnsupportedOperationException("max is not supported on a ReturnFieldSearchStream"); } - @Override public SearchStream dialect(int dialect) { + @Override + public SearchStream dialect(int dialect) { throw new UnsupportedOperationException("dialect is not supported on a ReturnFieldSearchStream"); } @@ -475,7 +485,7 @@ public SearchStream highlight(Function field) { } @Override - public SearchStream highlight(Function field, Pair tags) { + public SearchStream highlight(Function field, Pair tags) { throw new UnsupportedOperationException("highlight is not supported on a ReturnFieldSearchStream"); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStream.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStream.java index 4e6d209d..6198e5dc 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStream.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStream.java @@ -49,6 +49,7 @@ public interface SearchStream extends BaseStream> { SearchStream sorted(Comparator comparator); SearchStream sorted(Comparator comparator, SortOrder order); + SearchStream sorted(Sort sort); SearchStream peek(Consumer action); @@ -111,15 +112,16 @@ public interface SearchStream extends BaseStream> { SearchStream dialect(int dialect); - AggregationStream cursor(int i, Duration duration); + AggregationStream cursor(int i, Duration duration); SearchOperations getSearchOperations(); Slice getSlice(Pageable pageable); SearchStream project(Function field); + @SuppressWarnings("unchecked") - SearchStream project(MetamodelField ...field); + SearchStream project(MetamodelField... field); String backingQuery(); @@ -128,5 +130,6 @@ public interface SearchStream extends BaseStream> { SearchStream summarize(Function field, SummarizeParams params); SearchStream highlight(Function field); - SearchStream highlight(Function field, Pair tags); + + SearchStream highlight(Function field, Pair tags); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStreamImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStreamImpl.java index fbbe0207..69495df6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStreamImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SearchStreamImpl.java @@ -59,35 +59,30 @@ public class SearchStreamImpl implements SearchStream { private final JSONOperations json; private final String searchIndex; private final Class entityClass; - private Node rootNode = QueryBuilders.union(); private final GsonBuilder gsonBuilder; + private final Field idField; + private final boolean isDocument; + private final MappingRedisOMConverter mappingConverter; + private final List> projections = new ArrayList<>(); + private final List> summaryFields = new ArrayList<>(); + private final List> highlightFields = new ArrayList<>(); + private final ExampleToNodeConverter exampleToNodeConverter; + private final RediSearchIndexer indexer; + private Node rootNode = QueryBuilders.union(); private Gson gson; private Long limit; private Long skip; private SortedField sortBy; private boolean onlyIds = false; - private final Field idField; private Runnable closeHandler; private Stream resolvedStream; - private KNNPredicate knnPredicate; - private final boolean isDocument; - private final MappingRedisOMConverter mappingConverter; + private KNNPredicate knnPredicate; private int dialect = 1; - - private final List> projections = new ArrayList<>(); - - private final List> summaryFields = new ArrayList<>(); private SummarizeParams summarizeParams; - private final List> highlightFields = new ArrayList<>(); - - private Pair highlightTags; - - private final ExampleToNodeConverter exampleToNodeConverter; + private Pair highlightTags; - private final RediSearchIndexer indexer; - - public SearchStreamImpl(Class entityClass, RedisModulesOperations modulesOperations, GsonBuilder gsonBuilder, - RediSearchIndexer indexer) { + public SearchStreamImpl(Class entityClass, RedisModulesOperations modulesOperations, + GsonBuilder gsonBuilder, RediSearchIndexer indexer) { this.indexer = indexer; this.modulesOperations = modulesOperations; this.entityClass = entityClass; @@ -103,8 +98,7 @@ public SearchStreamImpl(Class entityClass, RedisModulesOperations mod throw new IllegalArgumentException(entityClass.getName() + " does not appear to have an ID field"); } this.isDocument = entityClass.isAnnotationPresent(Document.class); - this.mappingConverter = new MappingRedisOMConverter(null, - new ReferenceResolverImpl(modulesOperations.template())); + this.mappingConverter = new MappingRedisOMConverter(null, new ReferenceResolverImpl(modulesOperations.template())); this.exampleToNodeConverter = new ExampleToNodeConverter<>(indexer); } @@ -112,7 +106,7 @@ public SearchStreamImpl(Class entityClass, RedisModulesOperations mod @SuppressWarnings("unchecked") public SearchStream filter(SearchFieldPredicate predicate) { if (predicate instanceof KNNPredicate) { - knnPredicate = (KNNPredicate) predicate; + knnPredicate = (KNNPredicate) predicate; } else { rootNode = processPredicate(predicate); } @@ -135,7 +129,7 @@ public String toString() { @Override public String toString(Parenthesize mode) { - return switch(mode) { + return switch (mode) { case NEVER -> toString(); case ALWAYS, DEFAULT -> String.format("(%s)", this); }; @@ -157,7 +151,9 @@ public Node processPredicate(SearchFieldPredicate predicate) { private Node processPredicate(Predicate predicate) { if (SearchFieldPredicate.class.isAssignableFrom(predicate.getClass())) { - SearchFieldPredicate p = (SearchFieldPredicate) predicate; + @SuppressWarnings( + "unchecked" + ) SearchFieldPredicate p = (SearchFieldPredicate) predicate; return processPredicate(p); } return rootNode; @@ -168,17 +164,14 @@ public SearchStream map(Function mapper) { List> returning = new ArrayList<>(); if (MetamodelField.class.isAssignableFrom(mapper.getClass())) { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) mapper; + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) mapper; returning.add(foi); } else if (TupleMapper.class.isAssignableFrom(mapper.getClass())) { - @SuppressWarnings("rawtypes") - AbstractTupleMapper tm = (AbstractTupleMapper) mapper; + @SuppressWarnings("rawtypes") AbstractTupleMapper tm = (AbstractTupleMapper) mapper; IntStream.range(0, tm.degree()).forEach(i -> { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) tm.get(i); + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) tm.get(i); returning.add(foi); }); } else { @@ -232,8 +225,7 @@ public DoubleStream flatMapToDouble(Function @Override public SearchStream sorted(Comparator comparator) { if (MetamodelField.class.isAssignableFrom(comparator.getClass())) { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) comparator; + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) comparator; sortBy = SortedField.asc(foi.getSearchAlias()); } return this; @@ -242,8 +234,7 @@ public SearchStream sorted(Comparator comparator) { @Override public SearchStream sorted(Comparator comparator, SortOrder order) { if (MetamodelField.class.isAssignableFrom(comparator.getClass())) { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) comparator; + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) comparator; sortBy = new SortedField(foi.getSearchAlias(), order); } return this; @@ -442,7 +433,9 @@ Query prepareQuery() { if (knnPredicate != null) { query = new Query(knnPredicate.apply(rootNode).toString()); - query.addParam(knnPredicate.getBlobAttributeName(), knnPredicate.getBlobAttribute() != null ? knnPredicate.getBlobAttribute() : floatArrayToByteArray(knnPredicate.getDoublesAttribute())); + query.addParam(knnPredicate.getBlobAttributeName(), knnPredicate.getBlobAttribute() != null ? + knnPredicate.getBlobAttribute() : + floatArrayToByteArray(knnPredicate.getDoublesAttribute())); query.addParam("K", knnPredicate.getK()); query.dialect(2); } else { @@ -482,7 +475,7 @@ Query prepareQuery() { if (highlightTags == null) { query.highlightFields(fields.toArray(String[]::new)); } else { - HighlightTags tags = new HighlightTags(highlightTags.getFirst(),highlightTags.getSecond()); + HighlightTags tags = new HighlightTags(highlightTags.getFirst(), highlightTags.getSecond()); query.highlightFields(tags, fields.toArray(String[]::new)); } } @@ -491,8 +484,8 @@ Query prepareQuery() { query.returnFields(idField.getName()); } else if (!projections.isEmpty()) { var returnFields = projections.stream() // - .map(foi -> ObjectUtils.isCollection(foi.getTargetClass()) ? "$." + foi.getSearchAlias() : foi.getSearchAlias()) - .collect(toCollection(ArrayList::new)); + .map(foi -> ObjectUtils.isCollection(foi.getTargetClass()) ? "$." + foi.getSearchAlias() : foi.getSearchAlias()) + .collect(toCollection(ArrayList::new)); returnFields.add(idField.getName()); query.returnFields(returnFields.toArray(String[]::new)); @@ -511,16 +504,16 @@ private List toEntityList(SearchResult searchResult) { if (isDocument) { Gson g = getGson(); return searchResult.getDocuments().stream() - .map(d -> g.fromJson(SafeEncoder.encode((byte[]) d.get("$")), entityClass)).toList(); + .map(d -> g.fromJson(SafeEncoder.encode((byte[]) d.get("$")), entityClass)).toList(); } else { return searchResult.getDocuments().stream() - .map(d -> (E) ObjectUtils.documentToObject(d, entityClass, mappingConverter)).toList(); + .map(d -> (E) ObjectUtils.documentToObject(d, entityClass, mappingConverter)).toList(); } } else { List projectedEntities = new ArrayList<>(); searchResult.getDocuments().forEach(doc -> { Map props = StreamSupport.stream(doc.getProperties().spliterator(), false) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); E entity = BeanUtils.instantiateClass(this.entityClass); projections.forEach(foi -> { @@ -568,26 +561,25 @@ public Stream map(ToLongFunction mapper) { Method idSetter = ObjectUtils.getSetterForField(entityClass, idField); Stream wrappedIds = (Stream) executeQuery().getDocuments() // - .stream() // - .map(d -> { - try { - String key = idField.getType().getDeclaredConstructor(idField.getType()) - .newInstance(d.getId()).toString(); - return key.substring(key.indexOf(":") + 1); - } catch (Exception e) { - return null; - } - }).filter(Objects::nonNull).map(id -> { - Object entity; - try { - entity = entityClass.getDeclaredConstructor().newInstance(); - idSetter.invoke(entity, id); - } catch (Exception e) { - entity = null; - } + .stream() // + .map(d -> { + try { + String key = idField.getType().getDeclaredConstructor(idField.getType()).newInstance(d.getId()).toString(); + return key.substring(key.indexOf(":") + 1); + } catch (Exception e) { + return null; + } + }).filter(Objects::nonNull).map(id -> { + Object entity; + try { + entity = entityClass.getDeclaredConstructor().newInstance(); + idSetter.invoke(entity, id); + } catch (Exception e) { + entity = null; + } - return entity; - }); + return entity; + }); result = wrappedIds.mapToLong(mapper).boxed(); } @@ -601,7 +593,8 @@ public Stream> mapToLabelledMaps() { throw new UnsupportedOperationException("mapToLabelledMaps is not supported on a SearchStream"); } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream groupBy(MetamodelField... fields) { resolvedStream = Stream.empty(); String query = (rootNode.toString().isBlank()) ? "*" : rootNode.toString(); @@ -612,16 +605,19 @@ public final AggregationStream groupBy(MetamodelField... fields) { public AggregationStream apply(String expression, String alias) { resolvedStream = Stream.empty(); String query = (rootNode.toString().isBlank()) ? "*" : rootNode.toString(); - AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), entityClass, query); + AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), + entityClass, query); aggregationStream.apply(expression, alias); return aggregationStream; } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream load(MetamodelField... fields) { resolvedStream = Stream.empty(); String query = (rootNode.toString().isBlank()) ? "*" : rootNode.toString(); - AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), entityClass, query); + AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), + entityClass, query); aggregationStream.load(fields); return aggregationStream; } @@ -630,7 +626,8 @@ public final AggregationStream load(MetamodelField... fields) { public AggregationStream loadAll() { resolvedStream = Stream.empty(); String query = (rootNode.toString().isBlank()) ? "*" : rootNode.toString(); - AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), entityClass, query); + AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), + entityClass, query); aggregationStream.loadAll(); return aggregationStream; } @@ -639,7 +636,8 @@ public AggregationStream loadAll() { public AggregationStream cursor(int count, Duration timeout) { resolvedStream = Stream.empty(); String query = (rootNode.toString().isBlank()) ? "*" : rootNode.toString(); - AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), entityClass, query); + AggregationStream aggregationStream = new AggregationStreamImpl<>(searchIndex, modulesOperations, getGson(), + entityClass, query); aggregationStream.cursor(count, timeout); return aggregationStream; } @@ -648,32 +646,36 @@ public AggregationStream cursor(int count, Duration timeout) { public Optional min(NumericField field) { resolvedStream = Stream.empty(); List> minByField = this // - .load(new MetamodelField("__key", String.class)) // - .sorted(Order.asc("@" + field.getSearchAlias())) - .limit(1) // - .toList(String.class, Double.class); + .load(new MetamodelField("__key", String.class)) // + .sorted(Order.asc("@" + field.getSearchAlias())).limit(1) // + .toList(String.class, Double.class); - return minByField.isEmpty() ? Optional.empty() : Optional.ofNullable(json.get(minByField.get(0).getFirst(), entityClass)); + return minByField.isEmpty() ? + Optional.empty() : + Optional.ofNullable(json.get(minByField.get(0).getFirst(), entityClass)); } @Override public Optional max(NumericField field) { resolvedStream = Stream.empty(); List> maxByField = this // - .load(new MetamodelField("__key", String.class)) // - .sorted(1, Order.desc("@" + field.getSearchAlias())) - .limit(1) // - .toList(String.class, Double.class); + .load(new MetamodelField("__key", String.class)) // + .sorted(1, Order.desc("@" + field.getSearchAlias())).limit(1) // + .toList(String.class, Double.class); - return maxByField.isEmpty() ? Optional.empty() : Optional.ofNullable(json.get(maxByField.get(0).getFirst(), entityClass)); + return maxByField.isEmpty() ? + Optional.empty() : + Optional.ofNullable(json.get(maxByField.get(0).getFirst(), entityClass)); } - @Override public SearchStream dialect(int dialect) { + @Override + public SearchStream dialect(int dialect) { this.dialect = dialect; return this; } - @Override public SearchOperations getSearchOperations() { + @Override + public SearchOperations getSearchOperations() { return search; } @@ -693,16 +695,13 @@ public Slice getSlice(Pageable pageable) { @SuppressWarnings("unchecked") public SearchStream project(Function field) { if (MetamodelField.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) field; projections.add(foi); } else if (TupleMapper.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("rawtypes") - AbstractTupleMapper tm = (AbstractTupleMapper) field; + @SuppressWarnings("rawtypes") AbstractTupleMapper tm = (AbstractTupleMapper) field; IntStream.range(0, tm.degree()).forEach(i -> { - @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) tm.get(i); projections.add(foi); }); @@ -714,7 +713,7 @@ public SearchStream project(Function field) { @SuppressWarnings("unchecked") @Override public SearchStream project(MetamodelField... fields) { - for (MetamodelField field: fields) { + for (MetamodelField field : fields) { projections.add((MetamodelField) field); } return this; @@ -728,17 +727,14 @@ public String backingQuery() { @Override public SearchStream summarize(Function field) { if (MetamodelField.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) field; + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) field; summaryFields.add(foi); } else if (TupleMapper.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("rawtypes") - AbstractTupleMapper tm = (AbstractTupleMapper) field; + @SuppressWarnings("rawtypes") AbstractTupleMapper tm = (AbstractTupleMapper) field; IntStream.range(0, tm.degree()).forEach(i -> { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) tm.get(i); + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) tm.get(i); summaryFields.add(foi); }); } @@ -754,17 +750,14 @@ public SearchStream summarize(Function field, Sum @Override public SearchStream highlight(Function field) { if (MetamodelField.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) field; + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) field; highlightFields.add(foi); } else if (TupleMapper.class.isAssignableFrom(field.getClass())) { - @SuppressWarnings("rawtypes") - AbstractTupleMapper tm = (AbstractTupleMapper) field; + @SuppressWarnings("rawtypes") AbstractTupleMapper tm = (AbstractTupleMapper) field; IntStream.range(0, tm.degree()).forEach(i -> { - @SuppressWarnings("unchecked") - MetamodelField foi = (MetamodelField) tm.get(i); + @SuppressWarnings("unchecked") MetamodelField foi = (MetamodelField) tm.get(i); highlightFields.add(foi); }); } @@ -772,7 +765,7 @@ public SearchStream highlight(Function field) { } @Override - public SearchStream highlight(Function field, Pair tags) { + public SearchStream highlight(Function field, Pair tags) { highlightTags = tags; return highlight(field); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SummarizeParams.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SummarizeParams.java index 11817110..693a172f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SummarizeParams.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/SummarizeParams.java @@ -1,6 +1,14 @@ package com.redis.om.spring.search.stream; public class SummarizeParams { + private Integer fragsNum = 3; + private Integer fragSize = 20; + private String separator = "..."; + + public static SummarizeParams instance() { + return new SummarizeParams(); + } + public Integer getFragsNum() { return fragsNum; } @@ -13,10 +21,6 @@ public String getSeparator() { return separator; } - private Integer fragsNum = 3; - private Integer fragSize = 20; - private String separator = "..."; - public SummarizeParams fragments(int num) { this.fragsNum = num; return this; @@ -31,8 +35,4 @@ public SummarizeParams separator(String separator) { this.separator = separator; return this; } - - public static SummarizeParams instance() { - return new SummarizeParams(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/WrapperSearchStream.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/WrapperSearchStream.java index ab989ae9..1dae092c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/WrapperSearchStream.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/WrapperSearchStream.java @@ -260,7 +260,8 @@ public Stream> mapToLabelledMaps() { throw new UnsupportedOperationException("mapToLabelledMaps is not supported on a WrappedSearchStream"); } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream groupBy(MetamodelField... fields) { throw new UnsupportedOperationException("groupBy is not supported on a WrappedSearchStream"); } @@ -270,7 +271,8 @@ public AggregationStream apply(String expression, String alias) { throw new UnsupportedOperationException("apply is not supported on a WrappedSearchStream"); } - @SafeVarargs @Override + @SafeVarargs + @Override public final AggregationStream load(MetamodelField... fields) { throw new UnsupportedOperationException("load is not supported on a WrappedSearchStream"); } @@ -290,7 +292,8 @@ public Optional max(NumericField field) { throw new UnsupportedOperationException("max is not supported on a WrappedSearchStream"); } - @Override public SearchStream dialect(int dialect) { + @Override + public SearchStream dialect(int dialect) { throw new UnsupportedOperationException("dialect is not supported on a WrappedSearchStream"); } @@ -341,11 +344,10 @@ public SearchStream highlight(Function field) { } @Override - public SearchStream highlight(Function field, Pair tags) { + public SearchStream highlight(Function field, Pair tags) { throw new UnsupportedOperationException("highlight is not supported on a WrappedSearchStream"); } - @Override public SearchStream findFirstOrElse(Supplier supplier) { throw new UnsupportedOperationException("findFirstOrElse is not supported on a WrappedSearchStream"); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/actions/BaseAbstractAction.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/actions/BaseAbstractAction.java index 28131246..beea37db 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/actions/BaseAbstractAction.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/actions/BaseAbstractAction.java @@ -20,7 +20,7 @@ protected BaseAbstractAction(SearchFieldAccessor field) { this.idField = maybeId.get(); } else { throw new NullPointerException( - String.format("Entity Class %s does not have an ID field", entityClass.getSimpleName())); + String.format("Entity Class %s does not have an ID field", entityClass.getSimpleName())); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/BaseAbstractPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/BaseAbstractPredicate.java index 21fad76c..88fcc9b5 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/BaseAbstractPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/BaseAbstractPredicate.java @@ -27,19 +27,6 @@ protected BaseAbstractPredicate(SearchFieldAccessor field) { this.fieldType = getFieldTypeFor(field.getField()); } - @Override - public String getSearchAlias() { return field.getSearchAlias(); } - - @Override - public Field getField() { - return field.getField(); - } - - @Override - public FieldType getSearchFieldType() { - return fieldType; - } - private static FieldType getFieldTypeFor(java.lang.reflect.Field field) { FieldType result = null; // Searchable - behaves like Text indexed @@ -71,8 +58,8 @@ else if (field.isAnnotationPresent(NumericIndexed.class)) { // // Any Numeric class -> Numeric Search Field // - else if (Number.class.isAssignableFrom(field.getType()) || (field.getType() == LocalDateTime.class) - || (field.getType() == LocalDate.class) || (field.getType() == Date.class) || (field.getType() == Instant.class)) { + else if (Number.class.isAssignableFrom( + field.getType()) || (field.getType() == LocalDateTime.class) || (field.getType() == LocalDate.class) || (field.getType() == Date.class) || (field.getType() == Instant.class)) { result = FieldType.NUMERIC; } // @@ -91,6 +78,21 @@ else if (field.getType() == Point.class) { return result; } + @Override + public String getSearchAlias() { + return field.getSearchAlias(); + } + + @Override + public Field getField() { + return field.getField(); + } + + @Override + public FieldType getSearchFieldType() { + return fieldType; + } + @Override public boolean test(T t) { // TODO: determine what to do here! diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/ContainingPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/ContainingPredicate.java index 64b6607a..d74a1424 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/ContainingPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/ContainingPredicate.java @@ -21,7 +21,9 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root).add(getSearchAlias(), "*" + getValue().toString() + "*") : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root).add(getSearchAlias(), "*" + getValue().toString() + "*") : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EndsWithPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EndsWithPredicate.java index ac793f25..a4c2ea19 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EndsWithPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EndsWithPredicate.java @@ -23,8 +23,8 @@ public T getValue() { @Override public Node apply(Node root) { return ObjectUtils.isNotEmpty(getValue()) ? - QueryBuilders.intersect(root).add(getSearchAlias(), "*" + QueryUtils.escape(getValue().toString(), true)) : - root; + QueryBuilders.intersect(root).add(getSearchAlias(), "*" + QueryUtils.escape(getValue().toString(), true)) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EqualPredicate.java index 4cf22550..b8b72862 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/EqualPredicate.java @@ -21,7 +21,9 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root).add(getSearchAlias(), QueryUtils.escape(getValue().toString())) : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root).add(getSearchAlias(), QueryUtils.escape(getValue().toString())) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/InPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/InPredicate.java index 54f65559..80628a8c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/InPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/InPredicate.java @@ -32,7 +32,8 @@ public Node apply(Node root) { } return QueryBuilders.intersect(root).add(getSearchAlias(), sj.toString()); - } else return root; + } else + return root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/LikePredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/LikePredicate.java index 14df6c31..e5f0213f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/LikePredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/LikePredicate.java @@ -22,7 +22,10 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root).add(getSearchAlias(), "%%%" + QueryUtils.escape(getValue().toString(), true) + "%%%") : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root) + .add(getSearchAlias(), "%%%" + QueryUtils.escape(getValue().toString(), true) + "%%%") : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotContainingPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotContainingPredicate.java index 01d38b65..3a025fcf 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotContainingPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotContainingPredicate.java @@ -23,8 +23,10 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.value("*" + QueryUtils.escape(getValue().toString(), true) + "*"))) : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), + Values.value("*" + QueryUtils.escape(getValue().toString(), true) + "*"))) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotEqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotEqualPredicate.java index 98b96f79..a356816c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotEqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotEqualPredicate.java @@ -22,8 +22,10 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), Values.value( - QueryUtils.escape(getValue().toString(), true)))) : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root) + .add(QueryBuilders.disjunct(getSearchAlias(), Values.value(QueryUtils.escape(getValue().toString(), true)))) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotLikePredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotLikePredicate.java index 6cebda71..c7d1b71d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotLikePredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/NotLikePredicate.java @@ -23,8 +23,10 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.value("%%%" + QueryUtils.escape(getValue().toString(), true) + "%%%"))) : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), + Values.value("%%%" + QueryUtils.escape(getValue().toString(), true) + "%%%"))) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/StartsWithPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/StartsWithPredicate.java index 5fc3c304..3c382e9d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/StartsWithPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/fulltext/StartsWithPredicate.java @@ -22,7 +22,9 @@ public T getValue() { @Override public Node apply(Node root) { - return ObjectUtils.isNotEmpty(getValue()) ? QueryBuilders.intersect(root).add(getSearchAlias(), QueryUtils.escape(getValue().toString(), true) + "*") : root; + return ObjectUtils.isNotEmpty(getValue()) ? + QueryBuilders.intersect(root).add(getSearchAlias(), QueryUtils.escape(getValue().toString(), true) + "*") : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/EqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/EqualPredicate.java index 6c911462..c8d39e60 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/EqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/EqualPredicate.java @@ -42,7 +42,9 @@ public T getValue() { @Override public Node apply(Node root) { boolean paramsPresent = ObjectUtils.isNotEmpty(x) && ObjectUtils.isNotEmpty(y); - return paramsPresent ? QueryBuilders.intersect(root).add(getSearchAlias(), String.format("[%s %s 0.0001 mi]", x, y)) : root; + return paramsPresent ? + QueryBuilders.intersect(root).add(getSearchAlias(), String.format("[%s %s 0.0001 mi]", x, y)) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NearPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NearPredicate.java index e86efd45..5f75be72 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NearPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NearPredicate.java @@ -34,9 +34,11 @@ public Distance getDistance() { public Node apply(Node root) { boolean paramsPresent = isNotEmpty(point) && isNotEmpty(distance); if (paramsPresent) { - GeoValue geoValue = new GeoValue(getPoint().getX(), getPoint().getY(), getDistance().getValue(), ObjectUtils.getDistanceUnit(getDistance())); + GeoValue geoValue = new GeoValue(getPoint().getX(), getPoint().getY(), getDistance().getValue(), + ObjectUtils.getDistanceUnit(getDistance())); return QueryBuilders.intersect(root).add(getSearchAlias(), geoValue); - } else return root; + } else + return root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NotEqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NotEqualPredicate.java index 48e52540..cb6b8cda 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NotEqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/NotEqualPredicate.java @@ -43,8 +43,10 @@ public T getValue() { @Override public Node apply(Node root) { boolean paramsPresent = ObjectUtils.isNotEmpty(x) && ObjectUtils.isNotEmpty(y); - return paramsPresent ? QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.value(String.format("[%s %s 0.0001 mi]", x, y)))) : root; + return paramsPresent ? + QueryBuilders.intersect(root) + .add(QueryBuilders.disjunct(getSearchAlias(), Values.value(String.format("[%s %s 0.0001 mi]", x, y)))) : + root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/OutsideOfPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/OutsideOfPredicate.java index 6435465a..7bc6e6c2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/OutsideOfPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/geo/OutsideOfPredicate.java @@ -34,10 +34,12 @@ public Distance getDistance() { public Node apply(Node root) { boolean paramsPresent = isNotEmpty(point) && isNotEmpty(distance); if (paramsPresent) { - GeoValue geoValue = new GeoValue(getPoint().getX(), getPoint().getY(), getDistance().getValue(), ObjectUtils.getDistanceUnit(getDistance())); + GeoValue geoValue = new GeoValue(getPoint().getX(), getPoint().getY(), getDistance().getValue(), + ObjectUtils.getDistanceUnit(getDistance())); return QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), geoValue)); - } else return root; + } else + return root; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/jedis/DateRangeValue.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/jedis/DateRangeValue.java index 02074197..22d8db1a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/jedis/DateRangeValue.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/jedis/DateRangeValue.java @@ -6,11 +6,10 @@ import java.util.Date; public class DateRangeValue extends RangeValue { - private final Date from; - private final Date to; - public static final Date MIN = new Date(Long.MIN_VALUE); public static final Date MAX = new Date(Long.MAX_VALUE); + private final Date from; + private final Date to; public DateRangeValue(Date from, Date to) { this.from = from; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/BetweenPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/BetweenPredicate.java index a0ed94dd..114d9c8a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/BetweenPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/BetweenPredicate.java @@ -45,18 +45,18 @@ public Node apply(Node root) { return QueryBuilders.intersect(root).add(getSearchAlias(), JedisValues.between((Date) min, (Date) max)); } else if (cls == LocalDateTime.class) { return QueryBuilders.intersect(root) - .add(getSearchAlias(), JedisValues.between((LocalDateTime) min, (LocalDateTime) max)); + .add(getSearchAlias(), JedisValues.between((LocalDateTime) min, (LocalDateTime) max)); } else if (cls == Instant.class) { return QueryBuilders.intersect(root).add(getSearchAlias(), JedisValues.between((Instant) min, (Instant) max)); } else if (cls == Integer.class) { return QueryBuilders.intersect(root).add(getSearchAlias(), - Values.between(Integer.parseInt(getMin().toString()), Integer.parseInt(getMax().toString()))); + Values.between(Integer.parseInt(getMin().toString()), Integer.parseInt(getMax().toString()))); } else if (cls == Long.class) { return QueryBuilders.intersect(root).add(getSearchAlias(), - Values.between(Long.parseLong(getMin().toString()), Long.parseLong(getMax().toString()))); + Values.between(Long.parseLong(getMin().toString()), Long.parseLong(getMax().toString()))); } else if (cls == Double.class) { return QueryBuilders.intersect(root).add(getSearchAlias(), - Values.between(Double.parseDouble(getMin().toString()), Double.parseDouble(getMax().toString()))); + Values.between(Double.parseDouble(getMin().toString()), Double.parseDouble(getMax().toString()))); } else { return root; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/NotEqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/NotEqualPredicate.java index 6ee28f11..ed9985c4 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/NotEqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/numeric/NotEqualPredicate.java @@ -33,25 +33,25 @@ public Node apply(Node root) { Class cls = value.getClass(); if (cls == LocalDate.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((LocalDate) getValue()))); + .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((LocalDate) getValue()))); } else if (cls == Date.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((Date) getValue()))); + .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((Date) getValue()))); } else if (cls == LocalDateTime.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((LocalDateTime) getValue()))); + .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((LocalDateTime) getValue()))); } else if (cls == Instant.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((Instant) getValue()))); + .add(QueryBuilders.disjunct(getSearchAlias(), JedisValues.eq((Instant) getValue()))); } else if (cls == Integer.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Integer.parseInt(getValue().toString())))); + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Integer.parseInt(getValue().toString())))); } else if (cls == Long.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Long.parseLong(getValue().toString())))); + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Long.parseLong(getValue().toString())))); } else if (cls == Double.class) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Double.parseDouble(getValue().toString())))); + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Double.parseDouble(getValue().toString())))); } else { return root; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/EqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/EqualPredicate.java index 008a54fa..3fb23e1c 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/EqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/EqualPredicate.java @@ -37,7 +37,8 @@ public Node apply(Node root) { } else if (cls == Long.class) { return QueryBuilders.intersect(root).add(getSearchAlias(), Values.eq(Long.parseLong(referenceKey.toString()))); } else if (cls == Double.class) { - return QueryBuilders.intersect(root).add(getSearchAlias(), Values.eq(Double.parseDouble(referenceKey.toString()))); + return QueryBuilders.intersect(root) + .add(getSearchAlias(), Values.eq(Double.parseDouble(referenceKey.toString()))); } else if (CharSequence.class.isAssignableFrom(cls)) { return QueryBuilders.intersect(root).add(getSearchAlias(), "{" + referenceKey + "}"); } else { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/NotEqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/NotEqualPredicate.java index b386a070..8025cb93 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/NotEqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/reference/NotEqualPredicate.java @@ -33,17 +33,17 @@ public T getValue() { public Node apply(Node root) { Class cls = referenceKey.getClass(); if (cls == Integer.class) { - return QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Integer.parseInt( - referenceKey.toString())))); + return QueryBuilders.intersect(root) + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Integer.parseInt(referenceKey.toString())))); } else if (cls == Long.class) { - return QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Long.parseLong( - referenceKey.toString())))); + return QueryBuilders.intersect(root) + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Long.parseLong(referenceKey.toString())))); } else if (cls == Double.class) { - return QueryBuilders.intersect(root).add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Double.parseDouble( - referenceKey.toString())))); + return QueryBuilders.intersect(root) + .add(QueryBuilders.disjunct(getSearchAlias(), Values.eq(Double.parseDouble(referenceKey.toString())))); } else if (CharSequence.class.isAssignableFrom(cls)) { return QueryBuilders.intersect(root) - .add(QueryBuilders.disjunct(getSearchAlias(), Values.value("{" + referenceKey + "}"))); + .add(QueryBuilders.disjunct(getSearchAlias(), Values.value("{" + referenceKey + "}"))); } else { return root; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/ContainsAllPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/ContainsAllPredicate.java index 1d58cc4f..ae0e2ab2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/ContainsAllPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/ContainsAllPredicate.java @@ -26,7 +26,8 @@ public List getValues() { @Override public Node apply(Node root) { - if (isEmpty(getValues())) return root; + if (isEmpty(getValues())) + return root; QueryNode and = QueryBuilders.intersect(); for (String value : getValues()) { and.add(getSearchAlias(), "{" + value + "}"); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EndsWithPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EndsWithPredicate.java index 1179afba..893b3f5d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EndsWithPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EndsWithPredicate.java @@ -24,7 +24,8 @@ public T getValue() { @Override public Node apply(Node root) { - if (isEmpty(getValue())) return root; + if (isEmpty(getValue())) + return root; if (Iterable.class.isAssignableFrom(getValue().getClass())) { Iterable values = (Iterable) getValue(); QueryNode and = QueryBuilders.intersect(); @@ -33,7 +34,8 @@ public Node apply(Node root) { } return QueryBuilders.intersect(root, and); } else { - return QueryBuilders.intersect(root).add(getSearchAlias(), "{*" + QueryUtils.escape(value.toString(), true) + "}"); + return QueryBuilders.intersect(root) + .add(getSearchAlias(), "{*" + QueryUtils.escape(value.toString(), true) + "}"); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EqualPredicate.java index 4aefefd6..08ae400e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/EqualPredicate.java @@ -23,7 +23,8 @@ public T getValue() { @Override public Node apply(Node root) { - if (isEmpty(getValue())) return root; + if (isEmpty(getValue())) + return root; if (Iterable.class.isAssignableFrom(getValue().getClass())) { Iterable values = (Iterable) getValue(); QueryNode and = QueryBuilders.intersect(); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/InPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/InPredicate.java index 0ea6c71c..8763adee 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/InPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/InPredicate.java @@ -26,7 +26,8 @@ public List getValues() { @Override public Node apply(Node root) { - if (isEmpty(getValues())) return root; + if (isEmpty(getValues())) + return root; StringJoiner sj = new StringJoiner(" | "); for (Object value : getValues()) { sj.add(value.toString()); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/NotEqualPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/NotEqualPredicate.java index 150bcdc7..82ec9f18 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/NotEqualPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/NotEqualPredicate.java @@ -33,12 +33,13 @@ public Iterable getValues() { @Override public Node apply(Node root) { - if (isEmpty(getValues())) return root; + if (isEmpty(getValues())) + return root; QueryNode and = QueryBuilders.intersect(); StreamSupport.stream(getValues().spliterator(), false) // - .map(v -> Values.value("{" + v.toString() + "}")) - .forEach(val -> and.add(QueryBuilders.disjunct(getSearchAlias(), val))); + .map(v -> Values.value("{" + v.toString() + "}")) + .forEach(val -> and.add(QueryBuilders.disjunct(getSearchAlias(), val))); return QueryBuilders.intersect(root, and); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/StartsWithPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/StartsWithPredicate.java index d99120eb..64186775 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/StartsWithPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/tag/StartsWithPredicate.java @@ -24,7 +24,8 @@ public T getValue() { @Override public Node apply(Node root) { - if (isEmpty(getValue())) return root; + if (isEmpty(getValue())) + return root; if (Iterable.class.isAssignableFrom(getValue().getClass())) { Iterable values = (Iterable) getValue(); QueryNode and = QueryBuilders.intersect(); @@ -33,7 +34,8 @@ public Node apply(Node root) { } return QueryBuilders.intersect(root, and); } else { - return QueryBuilders.intersect(root).add(getSearchAlias(), "{" + QueryUtils.escape(value.toString(), true) + "*}"); + return QueryBuilders.intersect(root) + .add(getSearchAlias(), "{" + QueryUtils.escape(value.toString(), true) + "*}"); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/vector/KNNPredicate.java b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/vector/KNNPredicate.java index 92297717..3ec3531d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/vector/KNNPredicate.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/search/stream/predicates/vector/KNNPredicate.java @@ -42,7 +42,8 @@ public String getBlobAttributeName() { @Override public Node apply(Node root) { - String query = String.format("(%s)=>[KNN $K @%s $%s]", root.toString().isBlank() ? "*" : root.toString(), getSearchAlias(), getBlobAttributeName()); + String query = String.format("(%s)=>[KNN $K @%s $%s]", root.toString().isBlank() ? "*" : root.toString(), + getSearchAlias(), getBlobAttributeName()); return new Node() { @Override diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/DateTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/DateTypeAdapter.java index 2d8745d6..ed819983 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/DateTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/DateTypeAdapter.java @@ -5,21 +5,21 @@ import java.lang.reflect.Type; import java.util.Date; -public class DateTypeAdapter implements JsonSerializer, JsonDeserializer{ +public class DateTypeAdapter implements JsonSerializer, JsonDeserializer { + + public static DateTypeAdapter getInstance() { + return new DateTypeAdapter(); + } @Override public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(date.getTime()); } - + @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { return new Date(json.getAsLong()); } - - public static DateTypeAdapter getInstance() { - return new DateTypeAdapter(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/EnumTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/EnumTypeAdapter.java index 45036314..252a5603 100755 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/EnumTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/EnumTypeAdapter.java @@ -4,8 +4,7 @@ import java.lang.reflect.Type; -public class EnumTypeAdapter> implements JsonSerializer, - JsonDeserializer { +public class EnumTypeAdapter> implements JsonSerializer, JsonDeserializer { private final T[] values; @@ -19,14 +18,12 @@ public static > EnumTypeAdapter of(Class enumType) { } @Override - public JsonElement serialize(T o, Type type, - JsonSerializationContext jsonSerializationContext) { + public JsonElement serialize(T o, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(o.ordinal()); } @Override - public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) - throws JsonParseException { + public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return values[json.getAsInt()]; } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferenceSerializerRegistrar.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferenceSerializerRegistrar.java index f7bc08ef..9736496e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferenceSerializerRegistrar.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferenceSerializerRegistrar.java @@ -22,10 +22,10 @@ @Component public class GsonReferenceSerializerRegistrar { private static final Log logger = LogFactory.getLog(GsonReferenceSerializerRegistrar.class); + private static final String SKIPPING_REFERENCE_SEARCH = "Skipping @Reference search for %s because %s"; private final GsonBuilder builder; - private JSONOperations ops; private final ApplicationContext ac; - private static final String SKIPPING_REFERENCE_SEARCH = "Skipping @Reference search for %s because %s"; + private JSONOperations ops; public GsonReferenceSerializerRegistrar(GsonBuilder builder, ApplicationContext ac) { this.builder = builder; @@ -71,14 +71,9 @@ private void processField(Field field) { typeToken = TypeToken.get(field.getType()); } - builder.registerTypeAdapter( - typeToken.getType(), - new ReferenceDeserializer( - field, - ops, - ac.getBean(RedisOMProperties.class), - ac.getBean("redisOMCacheManager", CacheManager.class)) - ); + builder.registerTypeAdapter(typeToken.getType(), + new ReferenceDeserializer(field, ops, ac.getBean(RedisOMProperties.class), + ac.getBean("redisOMCacheManager", CacheManager.class))); processEntity(field.getType()); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferencesSerializationExclusionStrategy.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferencesSerializationExclusionStrategy.java index 7aee0bbe..d74e42c3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferencesSerializationExclusionStrategy.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/GsonReferencesSerializationExclusionStrategy.java @@ -6,6 +6,8 @@ public final class GsonReferencesSerializationExclusionStrategy implements ExclusionStrategy { + public static final GsonReferencesSerializationExclusionStrategy INSTANCE = new GsonReferencesSerializationExclusionStrategy(); + @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(Reference.class) != null; @@ -15,6 +17,4 @@ public boolean shouldSkipField(FieldAttributes f) { public boolean shouldSkipClass(Class clazz) { return false; } - - public static final GsonReferencesSerializationExclusionStrategy INSTANCE = new GsonReferencesSerializationExclusionStrategy(); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/InstantTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/InstantTypeAdapter.java index 8a4035b3..a868399a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/InstantTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/InstantTypeAdapter.java @@ -7,6 +7,10 @@ public class InstantTypeAdapter implements JsonSerializer, JsonDeserializer { + public static InstantTypeAdapter getInstance() { + return new InstantTypeAdapter(); + } + @Override public JsonElement serialize(Instant instant, Type typeOfSrc, JsonSerializationContext context) { long timeInMillis = instant.toEpochMilli(); @@ -15,12 +19,8 @@ public JsonElement serialize(Instant instant, Type typeOfSrc, JsonSerializationC @Override public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { return Instant.ofEpochMilli(json.getAsLong()); } - public static InstantTypeAdapter getInstance() { - return new InstantTypeAdapter(); - } - } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTimeTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTimeTypeAdapter.java index a2e5052d..1df1143f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTimeTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTimeTypeAdapter.java @@ -13,23 +13,23 @@ * In order to perform range searches we need to store this as GSon serialized Java longs * so that they can be indexed as NUMERIC in the index's schema */ -public class LocalDateTimeTypeAdapter implements JsonSerializer, JsonDeserializer{ +public class LocalDateTimeTypeAdapter implements JsonSerializer, JsonDeserializer { + + public static LocalDateTimeTypeAdapter getInstance() { + return new LocalDateTimeTypeAdapter(); + } @Override public JsonElement serialize(LocalDateTime localDateTime, Type typeOfSrc, JsonSerializationContext context) { Instant instant = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant(); - long timeInMillis = instant.toEpochMilli(); + long timeInMillis = instant.toEpochMilli(); return new JsonPrimitive(timeInMillis); } - + @Override public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { return LocalDateTime.ofInstant(Instant.ofEpochMilli(json.getAsLong()), ZoneId.systemDefault()); } - - public static LocalDateTimeTypeAdapter getInstance() { - return new LocalDateTimeTypeAdapter(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTypeAdapter.java index e4f579de..e8f59b89 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/LocalDateTypeAdapter.java @@ -9,25 +9,24 @@ /** * GSON Serializer/Deserializer for LocalDate to Unix Timestamp - * */ -public class LocalDateTypeAdapter implements JsonSerializer, JsonDeserializer{ +public class LocalDateTypeAdapter implements JsonSerializer, JsonDeserializer { + + public static LocalDateTypeAdapter getInstance() { + return new LocalDateTypeAdapter(); + } @Override public JsonElement serialize(LocalDate localDate, Type typeOfSrc, JsonSerializationContext context) { - Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); + Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); long unixTime = instant.getEpochSecond(); return new JsonPrimitive(unixTime); } - + @Override public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { return LocalDate.ofInstant(Instant.ofEpochSecond(json.getAsLong()), ZoneId.systemDefault()); } - - public static LocalDateTypeAdapter getInstance() { - return new LocalDateTypeAdapter(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/OffsetDateTimeTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/OffsetDateTimeTypeAdapter.java index c6047727..564ef265 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/OffsetDateTimeTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/OffsetDateTimeTypeAdapter.java @@ -9,16 +9,17 @@ public class OffsetDateTimeTypeAdapter implements JsonSerializer, JsonDeserializer { - public JsonElement serialize(OffsetDateTime offsetDateTime, Type typeOfSrc, JsonSerializationContext context) { - long timeInMillis = offsetDateTime.toInstant().toEpochMilli(); - return new JsonPrimitive(timeInMillis); - } + public static OffsetDateTimeTypeAdapter getInstance() { + return new OffsetDateTimeTypeAdapter(); + } - public OffsetDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(json.getAsLong()), ZoneId.systemDefault()); - } + public JsonElement serialize(OffsetDateTime offsetDateTime, Type typeOfSrc, JsonSerializationContext context) { + long timeInMillis = offsetDateTime.toInstant().toEpochMilli(); + return new JsonPrimitive(timeInMillis); + } - public static OffsetDateTimeTypeAdapter getInstance() { - return new OffsetDateTimeTypeAdapter(); - } + public OffsetDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(json.getAsLong()), ZoneId.systemDefault()); + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/PointTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/PointTypeAdapter.java index 2fd3233a..6b79e216 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/PointTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/PointTypeAdapter.java @@ -6,17 +6,21 @@ import java.lang.reflect.Type; import java.util.StringTokenizer; -public class PointTypeAdapter implements JsonSerializer, JsonDeserializer{ +public class PointTypeAdapter implements JsonSerializer, JsonDeserializer { + + public static PointTypeAdapter getInstance() { + return new PointTypeAdapter(); + } @Override public JsonElement serialize(Point src, Type typeOfSrc, JsonSerializationContext context) { String lonlat = src.getX() + "," + src.getY(); return new JsonPrimitive(lonlat); } - + @Override public Point deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { String lon; String lat; if (json.isJsonArray()) { @@ -29,11 +33,7 @@ public Point deserialize(JsonElement json, Type typeOfT, JsonDeserializationCont lon = st.nextToken(); lat = st.nextToken(); } - + return new Point(Double.parseDouble(lon), Double.parseDouble(lat)); } - - public static PointTypeAdapter getInstance() { - return new PointTypeAdapter(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/ReferenceDeserializer.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/ReferenceDeserializer.java index 512e7fde..1fd319b2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/ReferenceDeserializer.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/ReferenceDeserializer.java @@ -10,6 +10,8 @@ import com.redis.om.spring.util.ObjectUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -18,9 +20,6 @@ import java.util.*; import java.util.stream.Collectors; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; - public class ReferenceDeserializer implements JsonDeserializer { private static final Log logger = LogFactory.getLog(ReferenceDeserializer.class); @@ -32,11 +31,12 @@ public class ReferenceDeserializer implements JsonDeserializer { private final List cachedReferenceClasses; @SuppressWarnings("unchecked") - public ReferenceDeserializer(Field field, JSONOperations ops, RedisOMProperties properties, CacheManager cacheManager) { + public ReferenceDeserializer(Field field, JSONOperations ops, RedisOMProperties properties, + CacheManager cacheManager) { this.ops = (JSONOperations) ops; Map> instanceCreators = new HashMap<>(); ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators, true, - Collections.emptyList()); + Collections.emptyList()); if (ObjectUtils.isCollection(field)) { Optional> collectionType = ObjectUtils.getCollectionElementClass(field); if (collectionType.isPresent()) { @@ -55,7 +55,7 @@ public ReferenceDeserializer(Field field, JSONOperations ops, RedisOMProperti } @Override - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Object reference = null; @@ -81,10 +81,8 @@ public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationCon JsonArray jsonArray = json.getAsJsonArray(); reference = instantiateCollection(typeOfT); - String[] keys = jsonArray.asList().stream() - .filter(JsonElement::isJsonPrimitive) - .map(jsonElement -> ObjectUtils.unQuote(jsonElement.toString())) - .toArray(String[]::new); + String[] keys = jsonArray.asList().stream().filter(JsonElement::isJsonPrimitive) + .map(jsonElement -> ObjectUtils.unQuote(jsonElement.toString())).toArray(String[]::new); List values; if (keys.length > 0) { @@ -104,9 +102,7 @@ public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationCon values = ops.mget(keys); } ((Collection) reference).addAll( - values.stream() - .map(raw -> gson.fromJson(raw, JsonObject.class)) - .map(jo -> deserializeEntity(jo, context)) + values.stream().map(raw -> gson.fromJson(raw, JsonObject.class)).map(jo -> deserializeEntity(jo, context)) .toList()); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/UlidTypeAdapter.java b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/UlidTypeAdapter.java index 63d8443d..e6f1ce33 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/UlidTypeAdapter.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/serialization/gson/UlidTypeAdapter.java @@ -5,22 +5,22 @@ import java.lang.reflect.Type; -public class UlidTypeAdapter implements JsonSerializer, JsonDeserializer{ +public class UlidTypeAdapter implements JsonSerializer, JsonDeserializer { + + public static UlidTypeAdapter getInstance() { + return new UlidTypeAdapter(); + } @Override public JsonElement serialize(Ulid src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } - + @Override public Ulid deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { String ulidAsString = json.getAsString(); - + return Ulid.from(ulidAsString); } - - public static UlidTypeAdapter getInstance() { - return new UlidTypeAdapter(); - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Decuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Decuple.java index 25955947..33e44c0b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Decuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Decuple.java @@ -4,6 +4,46 @@ public interface Decuple extends Tuple { + static FirstAccessor, T0> getFirstGetter() { + return Decuple::getFirst; + } + + static SecondAccessor, T1> getSecondGetter() { + return Decuple::getSecond; + } + + static ThirdAccessor, T2> getThirdGetter() { + return Decuple::getThird; + } + + static FourthAccessor, T3> getFourthGetter() { + return Decuple::getFourth; + } + + static FifthAccessor, T4> getFifthGetter() { + return Decuple::getFifth; + } + + static SixthAccessor, T5> getSixthGetter() { + return Decuple::getSixth; + } + + static SeventhAccessor, T6> getSeventhGetter() { + return Decuple::getSeventh; + } + + static EighthAccessor, T7> getEighthGetter() { + return Decuple::getEighth; + } + + static NinthAccessor, T8> getNinthGetter() { + return Decuple::getNinth; + } + + static TenthAccessor, T9> getTenthGetter() { + return Decuple::getTenth; + } + T0 getFirst(); T1 getSecond(); @@ -42,47 +82,7 @@ default Object get(int index) { case 8 -> getNinth(); case 9 -> getTenth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, T0> getFirstGetter() { - return Decuple::getFirst; - } - - static SecondAccessor, T1> getSecondGetter() { - return Decuple::getSecond; - } - - static ThirdAccessor, T2> getThirdGetter() { - return Decuple::getThird; - } - - static FourthAccessor, T3> getFourthGetter() { - return Decuple::getFourth; - } - - static FifthAccessor, T4> getFifthGetter() { - return Decuple::getFifth; - } - - static SixthAccessor, T5> getSixthGetter() { - return Decuple::getSixth; - } - - static SeventhAccessor, T6> getSeventhGetter() { - return Decuple::getSeventh; - } - - static EighthAccessor, T7> getEighthGetter() { - return Decuple::getEighth; - } - - static NinthAccessor, T8> getNinthGetter() { - return Decuple::getNinth; - } - - static TenthAccessor, T9> getTenthGetter() { - return Decuple::getTenth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Duodecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Duodecuple.java index f4417cd8..fd46a902 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Duodecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Duodecuple.java @@ -4,54 +4,6 @@ public interface Duodecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - @Override - default int size() { - return 12; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Duodecuple::getFirst; } @@ -99,4 +51,52 @@ static EleventhAccessor TwelfthAccessor, E12> getTwelfthGetter() { return Duodecuple::getTwelfth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + @Override + default int size() { + return 12; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Fields.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Fields.java index b7713dfa..6e225ef3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Fields.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Fields.java @@ -6,7 +6,8 @@ public final class Fields { - private Fields() {} + private Fields() { + } @SuppressWarnings("unchecked") public static Function of() { @@ -22,124 +23,124 @@ public static Function> of(Function m0, Funct } public static Function> of(Function m0, Function m1, - Function m2) { + Function m2) { return new TripleMapperImpl<>(m0, m1, m2); } public static Function> of(Function m0, Function m1, - Function m2, Function m3) { + Function m2, Function m3) { return new QuadMapperImpl<>(m0, m1, m2, m3); } public static Function> of(Function m0, - Function m1, Function m2, Function m3, Function m4) { + Function m1, Function m2, Function m3, Function m4) { return new QuintupleMapperImpl<>(m0, m1, m2, m3, m4); } public static Function> of(Function m0, - Function m1, Function m2, Function m3, Function m4, Function m5) { + Function m1, Function m2, Function m3, Function m4, Function m5) { return new HextupleMapperImpl<>(m0, m1, m2, m3, m4, m5); } - public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6) { + public static Function> of(Function m0, + Function m1, Function m2, Function m3, Function m4, Function m5, + Function m6) { return new SeptupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7) { return new OctupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8) { return new NonupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9) { return new DecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10) { return new UndecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11) { return new DuodecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12) { return new TredecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13) { return new QuattuordecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14) { return new QuindecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15) { return new SexdecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16) { return new SeptendecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17) { return new OctodecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17, Function m18) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17, Function m18) { return new NovemdecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17, - m18); + m18); } public static Function> of( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17, Function m18, Function m19) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17, Function m18, Function m19) { return new VigintupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17, - m18, m19); + m18, m19); } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/GenericTuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/GenericTuple.java index dd26ea71..32dc5462 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/GenericTuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/GenericTuple.java @@ -9,7 +9,7 @@ public interface GenericTuple { R get(int index); Stream streamOf(Class clazz); - - Map labelledMap(); + + Map labelledMap(); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Hextuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Hextuple.java index e462ba79..7640de5e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Hextuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Hextuple.java @@ -4,6 +4,30 @@ public interface Hextuple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Hextuple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Hextuple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Hextuple::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Hextuple::getFourth; + } + + static FifthAccessor, E5> getFifthGetter() { + return Hextuple::getFifth; + } + + static SixthAccessor, E6> getSixthGetter() { + return Hextuple::getSixth; + } + E1 getFirst(); E2 getSecond(); @@ -30,31 +54,7 @@ default Object get(int index) { case 4 -> getFifth(); case 5 -> getSixth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Hextuple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Hextuple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Hextuple::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Hextuple::getFourth; - } - - static FifthAccessor, E5> getFifthGetter() { - return Hextuple::getFifth; - } - - static SixthAccessor, E6> getSixthGetter() { - return Hextuple::getSixth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Nonuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Nonuple.java index 0bfbb333..e1876eaf 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Nonuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Nonuple.java @@ -4,6 +4,42 @@ public interface Nonuple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Nonuple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Nonuple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Nonuple::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Nonuple::getFourth; + } + + static FifthAccessor, E5> getFifthGetter() { + return Nonuple::getFifth; + } + + static SixthAccessor, E6> getSixthGetter() { + return Nonuple::getSixth; + } + + static SeventhAccessor, E7> getSeventhGetter() { + return Nonuple::getSeventh; + } + + static EighthAccessor, E8> getEighthGetter() { + return Nonuple::getEighth; + } + + static NinthAccessor, E9> getNinthGetter() { + return Nonuple::getNinth; + } + E1 getFirst(); E2 getSecond(); @@ -39,43 +75,7 @@ default Object get(int index) { case 7 -> getEighth(); case 8 -> getNinth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Nonuple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Nonuple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Nonuple::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Nonuple::getFourth; - } - - static FifthAccessor, E5> getFifthGetter() { - return Nonuple::getFifth; - } - - static SixthAccessor, E6> getSixthGetter() { - return Nonuple::getSixth; - } - - static SeventhAccessor, E7> getSeventhGetter() { - return Nonuple::getSeventh; - } - - static EighthAccessor, E8> getEighthGetter() { - return Nonuple::getEighth; - } - - static NinthAccessor, E9> getNinthGetter() { - return Nonuple::getNinth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Novemdecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Novemdecuple.java index 2719078b..0e5eb226 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Novemdecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Novemdecuple.java @@ -3,76 +3,7 @@ import com.redis.om.spring.tuple.accessor.*; public interface Novemdecuple - extends Tuple { - - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - E16 getSixteenth(); - - E17 getSeventeenth(); - - E18 getEighteenth(); - - E19 getNineteenth(); - - @Override - default int size() { - return 19; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - case 15 -> getSixteenth(); - case 16 -> getSeventeenth(); - case 17 -> getEighteenth(); - case 18 -> getNineteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } + extends Tuple { static FirstAccessor, E1> getFirstGetter() { return Novemdecuple::getFirst; @@ -149,4 +80,73 @@ static NineteenthAccessor, E19> getNineteenthGetter() { return Novemdecuple::getNineteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + E16 getSixteenth(); + + E17 getSeventeenth(); + + E18 getEighteenth(); + + E19 getNineteenth(); + + @Override + default int size() { + return 19; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + case 15 -> getSixteenth(); + case 16 -> getSeventeenth(); + case 17 -> getEighteenth(); + case 18 -> getNineteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octodecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octodecuple.java index bbfe0039..4f753b3d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octodecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octodecuple.java @@ -3,73 +3,7 @@ import com.redis.om.spring.tuple.accessor.*; public interface Octodecuple - extends Tuple { - - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - E16 getSixteenth(); - - E17 getSeventeenth(); - - E18 getEighteenth(); - - @Override - default int size() { - return 18; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - case 15 -> getSixteenth(); - case 16 -> getSeventeenth(); - case 17 -> getEighteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } + extends Tuple { static FirstAccessor, E1> getFirstGetter() { return Octodecuple::getFirst; @@ -142,4 +76,70 @@ static EighteenthAccessor, E27> getEighteenthGetter() { return Octodecuple::getEighteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + E16 getSixteenth(); + + E17 getSeventeenth(); + + E18 getEighteenth(); + + @Override + default int size() { + return 18; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + case 15 -> getSixteenth(); + case 16 -> getSeventeenth(); + case 17 -> getEighteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octuple.java index 8d29bc8f..0e1f5b24 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Octuple.java @@ -4,6 +4,38 @@ public interface Octuple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Octuple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Octuple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Octuple::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Octuple::getFourth; + } + + static FifthAccessor, E5> getFifthGetter() { + return Octuple::getFifth; + } + + static SixthAccessor, E6> getSixthGetter() { + return Octuple::getSixth; + } + + static SeventhAccessor, E7> getSeventhGetter() { + return Octuple::getSeventh; + } + + static EighthAccessor, T7> getEighthGetter() { + return Octuple::getEighth; + } + E1 getFirst(); E2 getSecond(); @@ -36,39 +68,7 @@ default Object get(int index) { case 6 -> getSeventh(); case 7 -> getEighth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Octuple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Octuple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Octuple::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Octuple::getFourth; - } - - static FifthAccessor, E5> getFifthGetter() { - return Octuple::getFifth; - } - - static SixthAccessor, E6> getSixthGetter() { - return Octuple::getSixth; - } - - static SeventhAccessor, E7> getSeventhGetter() { - return Octuple::getSeventh; - } - - static EighthAccessor, T7> getEighthGetter() { - return Octuple::getEighth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Pair.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Pair.java index d0f500d4..357a97aa 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Pair.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Pair.java @@ -5,6 +5,14 @@ public interface Pair extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Pair::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Pair::getSecond; + } + E1 getFirst(); E2 getSecond(); @@ -19,15 +27,7 @@ default Object get(int index) { case 0 -> getFirst(); case 1 -> getSecond(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Pair::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Pair::getSecond; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quad.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quad.java index 729ea05b..d35072dd 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quad.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quad.java @@ -7,6 +7,22 @@ public interface Quad extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Quad::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Quad::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Quad::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Quad::getFourth; + } + E1 getFirst(); E2 getSecond(); @@ -27,23 +43,7 @@ default Object get(int index) { case 2 -> getThird(); case 3 -> getFourth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Quad::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Quad::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Quad::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Quad::getFourth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quattuordecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quattuordecuple.java index d741a4f5..d1112ea1 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quattuordecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quattuordecuple.java @@ -4,60 +4,6 @@ public interface Quattuordecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - @Override - default int size() { - return 14; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Quattuordecuple::getFirst; } @@ -113,4 +59,58 @@ static ThirteenthA static FourteenthAccessor, E14> getFourteenthGetter() { return Quattuordecuple::getFourteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + @Override + default int size() { + return 14; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quindecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quindecuple.java index dafe9e76..fb5f599b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quindecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quindecuple.java @@ -4,63 +4,6 @@ public interface Quindecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - @Override - default int size() { - return 15; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Quindecuple::getFirst; } @@ -120,4 +63,61 @@ static Fourte static FifteenthAccessor, E15> getFifteenthGetter() { return Quindecuple::getFifteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + @Override + default int size() { + return 15; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quintuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quintuple.java index 062a7dd2..75dc1509 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quintuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Quintuple.java @@ -4,6 +4,26 @@ public interface Quintuple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Quintuple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Quintuple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Quintuple::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Quintuple::getFourth; + } + + static FifthAccessor, E5> getFifthGetter() { + return Quintuple::getFifth; + } + E1 getFirst(); E2 getSecond(); @@ -27,27 +47,7 @@ default Object get(int index) { case 3 -> getFourth(); case 4 -> getFifth(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Quintuple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Quintuple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Quintuple::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Quintuple::getFourth; - } - - static FifthAccessor, E5> getFifthGetter() { - return Quintuple::getFifth; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septendecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septendecuple.java index 6cb011ab..c38c0a04 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septendecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septendecuple.java @@ -3,70 +3,7 @@ import com.redis.om.spring.tuple.accessor.*; public interface Septendecuple - extends Tuple { - - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - E16 getSixteenth(); - - E17 getSeventeenth(); - - @Override - default int size() { - return 17; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - case 15 -> getSixteenth(); - case 16 -> getSeventeenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } + extends Tuple { static FirstAccessor, E1> getFirstGetter() { return Septendecuple::getFirst; @@ -135,4 +72,67 @@ static SeventeenthAccessor, E17> getSeventeenthGetter() { return Septendecuple::getSeventeenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + E16 getSixteenth(); + + E17 getSeventeenth(); + + @Override + default int size() { + return 17; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + case 15 -> getSixteenth(); + case 16 -> getSeventeenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septuple.java index 66393870..3fc86513 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Septuple.java @@ -4,6 +4,34 @@ public interface Septuple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Septuple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Septuple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Septuple::getThird; + } + + static FourthAccessor, E4> getFourthGetter() { + return Septuple::getFourth; + } + + static FifthAccessor, E5> getFifthGetter() { + return Septuple::getFifth; + } + + static SixthAccessor, E6> getSixthGetter() { + return Septuple::getSixth; + } + + static SeventhAccessor, E7> getSeventhGetter() { + return Septuple::getSeventh; + } + E1 getFirst(); E2 getSecond(); @@ -33,35 +61,7 @@ default Object get(int index) { case 5 -> getSixth(); case 6 -> getSeventh(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Septuple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Septuple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Septuple::getThird; - } - - static FourthAccessor, E4> getFourthGetter() { - return Septuple::getFourth; - } - - static FifthAccessor, E5> getFifthGetter() { - return Septuple::getFifth; - } - - static SixthAccessor, E6> getSixthGetter() { - return Septuple::getSixth; - } - - static SeventhAccessor, E7> getSeventhGetter() { - return Septuple::getSeventh; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Sexdecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Sexdecuple.java index f71b14d3..2bb760c5 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Sexdecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Sexdecuple.java @@ -4,66 +4,6 @@ public interface Sexdecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - E16 getSixteenth(); - - @Override - default int size() { - return 16; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - case 15 -> getSixteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Sexdecuple::getFirst; } @@ -127,4 +67,64 @@ static F static SixteenthAccessor, E16> getSixteenthGetter() { return Sexdecuple::getSixteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + E16 getSixteenth(); + + @Override + default int size() { + return 16; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + case 15 -> getSixteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Single.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Single.java index d8f55cb1..c926d15d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Single.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Single.java @@ -4,6 +4,10 @@ public interface Single extends Tuple { + static FirstAccessor, T0> getFirstGetter() { + return Single::getFirst; + } + T0 getFirst(); @Override @@ -16,11 +20,7 @@ default Object get(int index) { return getFirst(); } else { throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); } } - - static FirstAccessor, T0> getFirstGetter() { - return Single::getFirst; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tredecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tredecuple.java index 1e0a471b..dcf6db6d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tredecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tredecuple.java @@ -4,57 +4,6 @@ public interface Tredecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - @Override - default int size() { - return 13; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Tredecuple::getFirst; } @@ -106,4 +55,55 @@ static TwelfthAccessor< static ThirteenthAccessor, E13> getThirteenthGetter() { return Tredecuple::getThirteenth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + @Override + default int size() { + return 13; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Triple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Triple.java index 326da9b7..c40da939 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Triple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Triple.java @@ -6,6 +6,18 @@ public interface Triple extends Tuple { + static FirstAccessor, E1> getFirstGetter() { + return Triple::getFirst; + } + + static SecondAccessor, E2> getSecondGetter() { + return Triple::getSecond; + } + + static ThirdAccessor, E3> getThirdGetter() { + return Triple::getThird; + } + E1 getFirst(); E2 getSecond(); @@ -23,19 +35,7 @@ default Object get(int index) { case 1 -> getSecond(); case 2 -> getThird(); default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); }; } - - static FirstAccessor, E1> getFirstGetter() { - return Triple::getFirst; - } - - static SecondAccessor, E2> getSecondGetter() { - return Triple::getSecond; - } - - static ThirdAccessor, E3> getThirdGetter() { - return Triple::getThird; - } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuple.java index c6d4ed7b..edf573f6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuple.java @@ -15,9 +15,9 @@ default Stream stream() { default Stream streamOf(Class clazz) { return stream().filter(clazz::isInstance).map(clazz::cast); } - + @Override - default Map labelledMap() { + default Map labelledMap() { return Collections.emptyMap(); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuples.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuples.java index b1839ea5..d9aef6ba 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuples.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Tuples.java @@ -7,7 +7,8 @@ public final class Tuples { - private Tuples() {} + private Tuples() { + } public static EmptyTuple of() { return EmptyTupleImpl.EMPTY_TUPLE; @@ -16,7 +17,7 @@ public static EmptyTuple of() { public static Single of(T0 e0) { return new SingleImpl<>(new String[] {}, e0); } - + public static Single of(String[] labels, T0 e0) { return new SingleImpl<>(labels, e0); } @@ -24,7 +25,7 @@ public static Single of(String[] labels, T0 e0) { public static Pair of(T0 e0, T1 e1) { return new PairImpl<>(new String[] {}, e0, e1); } - + public static Pair of(String[] labels, T0 e0, T1 e1) { return new PairImpl<>(labels, e0, e1); } @@ -32,7 +33,7 @@ public static Pair of(String[] labels, T0 e0, T1 e1) { public static Triple of(T0 e0, T1 e1, T2 e2) { return new TripleImpl<>(new String[] {}, e0, e1, e2); } - + public static Triple of(String[] labels, T0 e0, T1 e1, T2 e2) { return new TripleImpl<>(labels, e0, e1, e2); } @@ -40,7 +41,7 @@ public static Triple of(String[] labels, T0 e0, T1 e1, public static Quad of(T0 e0, T1 e1, T2 e2, T3 e3) { return new QuadImpl<>(new String[] {}, e0, e1, e2, e3); } - + public static Quad of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3) { return new QuadImpl<>(labels, e0, e1, e2, e3); } @@ -48,172 +49,178 @@ public static Quad of(String[] labels, T0 e0, T public static Quintuple of(T0 e0, T1 e1, T2 e2, T3 e3, T4 e4) { return new QuintupleImpl<>(new String[] {}, e0, e1, e2, e3, e4); } - - public static Quintuple of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4) { + + public static Quintuple of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, + T4 e4) { return new QuintupleImpl<>(labels, e0, e1, e2, e3, e4); } public static Hextuple of(T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) { return new HextupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5); } - - public static Hextuple of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) { + + public static Hextuple of(String[] labels, T0 e0, T1 e1, T2 e2, + T3 e3, T4 e4, T5 e5) { return new HextupleImpl<>(labels, e0, e1, e2, e3, e4, e5); } public static Septuple of(T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, - T5 e5, T6 e6) { + T5 e5, T6 e6) { return new SeptupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6); } - - public static Septuple of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, - T5 e5, T6 e6) { + + public static Septuple of(String[] labels, T0 e0, T1 e1, + T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) { return new SeptupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6); } public static Octuple of(T0 e0, T1 e1, T2 e2, T3 e3, - T4 e4, T5 e5, T6 e6, T7 e7) { + T4 e4, T5 e5, T6 e6, T7 e7) { return new OctupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7); } - - public static Octuple of(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, - T4 e4, T5 e5, T6 e6, T7 e7) { + + public static Octuple of(String[] labels, T0 e0, + T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7) { return new OctupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7); } public static Nonuple of(T0 e0, T1 e1, T2 e2, - T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8) { + T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8) { return new NonupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8); } - - public static Nonuple of(String[] labels, T0 e0, T1 e1, T2 e2, - T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8) { + + public static Nonuple of(String[] labels, + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8) { return new NonupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8); } public static Decuple of(T0 e0, - T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9) { + T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9) { return new DecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9); } - - public static Decuple of(String[] labels, T0 e0, - T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9) { + + public static Decuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9) { return new DecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9); } public static Undecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10) { return new UndecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); } - - public static Undecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10) { + + public static Undecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10) { return new UndecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); } public static Duodecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11) { return new DuodecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } - - public static Duodecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11) { + + public static Duodecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11) { return new DuodecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } public static Tredecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12) { return new TredecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); } - - public static Tredecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12) { + + public static Tredecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12) { return new TredecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); } - + public static Quattuordecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13) { return new QuattuordecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13); } - - public static Quattuordecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13) { + public static Quattuordecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13) { return new QuattuordecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13); } public static Quindecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, - T14 e14) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14) { return new QuindecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14); } - - public static Quindecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, - T14 e14) { + + public static Quindecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14) { return new QuindecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14); } public static Sexdecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, + T15 e15) { return new SexdecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } - - public static Sexdecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15) { + + public static Sexdecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14, T15 e15) { return new SexdecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } public static Septendecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16) { - return new SeptendecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16); - } - - public static Septendecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16) { + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, + T15 e15, T16 e16) { + return new SeptendecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, + e15, e16); + } + + public static Septendecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14, T15 e15, T16 e16) { return new SeptendecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16); } public static Octodecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17) { - return new OctodecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17); + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, + T15 e15, T16 e16, T17 e17) { + return new OctodecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, + e16, e17); } - - public static Octodecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17) { - return new OctodecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17); + + public static Octodecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14, T15 e15, T16 e16, T17 e17) { + return new OctodecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, + e17); } public static Novemdecuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17, T18 e18) { - return new NovemdecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18); + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, + T15 e15, T16 e16, T17 e17, T18 e18) { + return new NovemdecupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, + e16, e17, e18); } - - public static Novemdecuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17, T18 e18) { - return new NovemdecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18); + + public static Novemdecuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18) { + return new NovemdecupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, + e17, e18); } public static Vigintuple of( - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { - return new VigintupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, - e19); + T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, + T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { + return new VigintupleImpl<>(new String[] {}, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, + e16, e17, e18, e19); } - - public static Vigintuple of(String[] labels, - T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, - T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { - return new VigintupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, - e19); + + public static Vigintuple of( + String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, + T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { + return new VigintupleImpl<>(labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, + e18, e19); } @SafeVarargs @@ -232,29 +239,29 @@ public static Tuple ofArray(String[] returnFields, Object... el) { case 10 -> of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9]); case 11 -> of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10]); case 12 -> of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11]); - case 13 -> of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], - el[12]); + case 13 -> + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12]); case 14 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13]); case 15 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13], el[14]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14]); case 16 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13], el[14], el[15]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14], el[15]); case 17 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13], el[14], el[15], el[16]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14], el[15], el[16]); case 18 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13], el[14], el[15], el[16], el[17]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14], el[15], el[16], el[17]); case 19 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], - el[13], el[14], el[15], el[16], el[17], el[18]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14], el[15], el[16], el[17], el[18]); case 20 -> - of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], el[13], - el[14], el[15], el[16], el[17], el[18], el[19]); + of(returnFields, el[0], el[1], el[2], el[3], el[4], el[5], el[6], el[7], el[8], el[9], el[10], el[11], el[12], + el[13], el[14], el[15], el[16], el[17], el[18], el[19]); default -> new TupleInfiniteDegreeImpl(el); }; } @@ -273,124 +280,124 @@ public static Function> toTuple(Function m0, } public static Function> toTuple(Function m0, Function m1, - Function m2) { + Function m2) { return new TripleMapperImpl<>(m0, m1, m2); } public static Function> toTuple(Function m0, Function m1, - Function m2, Function m3) { + Function m2, Function m3) { return new QuadMapperImpl<>(m0, m1, m2, m3); } public static Function> toTuple(Function m0, - Function m1, Function m2, Function m3, Function m4) { + Function m1, Function m2, Function m3, Function m4) { return new QuintupleMapperImpl<>(m0, m1, m2, m3, m4); } public static Function> toTuple(Function m0, - Function m1, Function m2, Function m3, Function m4, Function m5) { + Function m1, Function m2, Function m3, Function m4, Function m5) { return new HextupleMapperImpl<>(m0, m1, m2, m3, m4, m5); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6) { return new SeptupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7) { return new OctupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8) { return new NonupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9) { return new DecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10) { return new UndecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11) { return new DuodecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12) { return new TredecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13) { return new QuattuordecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14) { return new QuindecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15) { return new SexdecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16) { return new SeptendecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17) { return new OctodecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17, Function m18) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17, Function m18) { return new NovemdecupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17, - m18); + m18); } public static Function> toTuple( - Function m0, Function m1, Function m2, Function m3, Function m4, - Function m5, Function m6, Function m7, Function m8, Function m9, - Function m10, Function m11, Function m12, Function m13, Function m14, - Function m15, Function m16, Function m17, Function m18, Function m19) { + Function m0, Function m1, Function m2, Function m3, Function m4, + Function m5, Function m6, Function m7, Function m8, Function m9, + Function m10, Function m11, Function m12, Function m13, Function m14, + Function m15, Function m16, Function m17, Function m18, Function m19) { return new VigintupleMapperImpl<>(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17, - m18, m19); + m18, m19); } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Undecuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Undecuple.java index c933016f..1bf1f948 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Undecuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Undecuple.java @@ -4,51 +4,6 @@ public interface Undecuple extends Tuple { - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - @Override - default int size() { - return 11; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } - static FirstAccessor, E1> getFirstGetter() { return Undecuple::getFirst; } @@ -92,4 +47,49 @@ static TenthAccessor EleventhAccessor, E11> getEleventhGetter() { return Undecuple::getEleventh; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + @Override + default int size() { + return 11; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Vigintuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Vigintuple.java index 00981ae1..ea3fdfad 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Vigintuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/Vigintuple.java @@ -3,79 +3,7 @@ import com.redis.om.spring.tuple.accessor.*; public interface Vigintuple - extends Tuple { - - E1 getFirst(); - - E2 getSecond(); - - E3 getThird(); - - E4 getFourth(); - - E5 getFifth(); - - E6 getSixth(); - - E7 getSeventh(); - - E8 getEighth(); - - E9 getNinth(); - - E10 getTenth(); - - E11 getEleventh(); - - E12 getTwelfth(); - - E13 getThirteenth(); - - E14 getFourteenth(); - - E15 getFifteenth(); - - E16 getSixteenth(); - - E17 getSeventeenth(); - - E18 getEighteenth(); - - E19 getNineteenth(); - - E20 getTwentieth(); - - @Override - default int size() { - return 20; - } - - default Object get(int index) { - return switch (index) { - case 0 -> getFirst(); - case 1 -> getSecond(); - case 2 -> getThird(); - case 3 -> getFourth(); - case 4 -> getFifth(); - case 5 -> getSixth(); - case 6 -> getSeventh(); - case 7 -> getEighth(); - case 8 -> getNinth(); - case 9 -> getTenth(); - case 10 -> getEleventh(); - case 11 -> getTwelfth(); - case 12 -> getThirteenth(); - case 13 -> getFourteenth(); - case 14 -> getFifteenth(); - case 15 -> getSixteenth(); - case 16 -> getSeventeenth(); - case 17 -> getEighteenth(); - case 18 -> getNineteenth(); - case 19 -> getTwentieth(); - default -> throw new IndexOutOfBoundsException( - String.format("Index %d is outside bounds of tuple of degree %s", index, size())); - }; - } + extends Tuple { static FirstAccessor, E1> getFirstGetter() { return Vigintuple::getFirst; @@ -156,4 +84,76 @@ static TwentiethAccessor, E20> getTwentiethGetter() { return Vigintuple::getTwentieth; } + + E1 getFirst(); + + E2 getSecond(); + + E3 getThird(); + + E4 getFourth(); + + E5 getFifth(); + + E6 getSixth(); + + E7 getSeventh(); + + E8 getEighth(); + + E9 getNinth(); + + E10 getTenth(); + + E11 getEleventh(); + + E12 getTwelfth(); + + E13 getThirteenth(); + + E14 getFourteenth(); + + E15 getFifteenth(); + + E16 getSixteenth(); + + E17 getSeventeenth(); + + E18 getEighteenth(); + + E19 getNineteenth(); + + E20 getTwentieth(); + + @Override + default int size() { + return 20; + } + + default Object get(int index) { + return switch (index) { + case 0 -> getFirst(); + case 1 -> getSecond(); + case 2 -> getThird(); + case 3 -> getFourth(); + case 4 -> getFifth(); + case 5 -> getSixth(); + case 6 -> getSeventh(); + case 7 -> getEighth(); + case 8 -> getNinth(); + case 9 -> getTenth(); + case 10 -> getEleventh(); + case 11 -> getTwelfth(); + case 12 -> getThirteenth(); + case 13 -> getFourteenth(); + case 14 -> getFifteenth(); + case 15 -> getSixteenth(); + case 16 -> getSeventeenth(); + case 17 -> getEighteenth(); + case 18 -> getNineteenth(); + case 19 -> getTwentieth(); + default -> throw new IndexOutOfBoundsException( + String.format("Index %d is outside bounds of tuple of degree %s", index, size())); + }; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FifthAccessor.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FifthAccessor.java index 7c878762..0997d740 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FifthAccessor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FifthAccessor.java @@ -3,8 +3,8 @@ @FunctionalInterface public interface FifthAccessor extends TupleAccessor { - @Override - default int index() { - return 4; - } + @Override + default int index() { + return 4; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FourthAccessor.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FourthAccessor.java index ee4a6c0c..72184080 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FourthAccessor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/FourthAccessor.java @@ -3,8 +3,8 @@ @FunctionalInterface public interface FourthAccessor extends TupleAccessor { - @Override - default int index() { - return 3; - } + @Override + default int index() { + return 3; + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/TupleAccessor.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/TupleAccessor.java index 9e4269d1..d0d0bce9 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/TupleAccessor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/accessor/TupleAccessor.java @@ -1,4 +1,3 @@ - package com.redis.om.spring.tuple.accessor; import java.util.function.Function; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/AbstractTuple.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/AbstractTuple.java index 260819d4..6214c9e3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/AbstractTuple.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/AbstractTuple.java @@ -23,7 +23,7 @@ public Object get(int index) { protected int assertIndexBounds(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException( - "index " + index + " is illegal. The degree of this Tuple is " + size() + "."); + "index " + index + " is illegal. The degree of this Tuple is " + size() + "."); } return index; } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DecupleImpl.java index 6e1967ab..c43ae90e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DecupleImpl.java @@ -3,7 +3,7 @@ import com.redis.om.spring.tuple.Decuple; public final class DecupleImpl extends AbstractTuple - implements Decuple { + implements Decuple { public DecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9) { super(DecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DuodecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DuodecupleImpl.java index 2aa6bec8..78b5eee0 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DuodecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/DuodecupleImpl.java @@ -3,9 +3,10 @@ import com.redis.om.spring.tuple.Duodecuple; public final class DuodecupleImpl extends AbstractTuple - implements Duodecuple { + implements Duodecuple { - public DuodecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11) { + public DuodecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11) { super(DuodecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/HextupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/HextupleImpl.java index 632133eb..ea2b8f48 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/HextupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/HextupleImpl.java @@ -3,7 +3,7 @@ import com.redis.om.spring.tuple.Hextuple; public final class HextupleImpl extends AbstractTuple - implements Hextuple { + implements Hextuple { public HextupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) { super(HextupleImpl.class, labels, e0, e1, e2, e3, e4, e5); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NonupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NonupleImpl.java index f0b9c387..b697ead7 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NonupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NonupleImpl.java @@ -3,7 +3,7 @@ import com.redis.om.spring.tuple.Nonuple; public final class NonupleImpl extends AbstractTuple - implements Nonuple { + implements Nonuple { public NonupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8) { super(NonupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NovemdecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NovemdecupleImpl.java index c7a59732..6c53b9d2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NovemdecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/NovemdecupleImpl.java @@ -3,12 +3,13 @@ import com.redis.om.spring.tuple.Novemdecuple; public final class NovemdecupleImpl - extends AbstractTuple - implements Novemdecuple { + extends AbstractTuple + implements Novemdecuple { - public NovemdecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12, T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18) { - super(NovemdecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18); + public NovemdecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, + T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18) { + super(NovemdecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, + e17, e18); } @SuppressWarnings("unchecked") diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctodecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctodecupleImpl.java index 298eef0d..f3f0d085 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctodecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctodecupleImpl.java @@ -3,12 +3,13 @@ import com.redis.om.spring.tuple.Octodecuple; public final class OctodecupleImpl - extends AbstractTuple - implements Octodecuple { + extends AbstractTuple + implements Octodecuple { - public OctodecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12, T13 e13, T14 e14, T15 e15, T16 e16, T17 e17) { - super(OctodecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17); + public OctodecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11, T12 e12, T13 e13, T14 e14, T15 e15, T16 e16, T17 e17) { + super(OctodecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, + e17); } @SuppressWarnings("unchecked") diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctupleImpl.java index d193148a..101ce700 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/OctupleImpl.java @@ -3,7 +3,7 @@ import com.redis.om.spring.tuple.Octuple; public final class OctupleImpl extends AbstractTuple - implements Octuple { + implements Octuple { public OctupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7) { super(OctupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuattuordecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuattuordecupleImpl.java index 0e0e2d4f..231649ed 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuattuordecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuattuordecupleImpl.java @@ -3,10 +3,10 @@ import com.redis.om.spring.tuple.Quattuordecuple; public final class QuattuordecupleImpl extends AbstractTuple - implements Quattuordecuple { + implements Quattuordecuple { - public QuattuordecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12, T13 e13) { + public QuattuordecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, + T10 e10, T11 e11, T12 e12, T13 e13) { super(QuattuordecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuindecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuindecupleImpl.java index cbc34c97..ca293500 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuindecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/QuindecupleImpl.java @@ -3,10 +3,10 @@ import com.redis.om.spring.tuple.Quindecuple; public final class QuindecupleImpl - extends AbstractTuple implements Quindecuple { + extends AbstractTuple implements Quindecuple { - public QuindecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12, T13 e13, T14 e14) { + public QuindecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11, T12 e12, T13 e13, T14 e14) { super(QuindecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptendecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptendecupleImpl.java index 42fc4e53..e6812aae 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptendecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptendecupleImpl.java @@ -2,11 +2,12 @@ import com.redis.om.spring.tuple.Septendecuple; -public final class SeptendecupleImpl extends - AbstractTuple implements Septendecuple { +public final class SeptendecupleImpl + extends AbstractTuple + implements Septendecuple { - public SeptendecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12, T13 e13, T14 e14, T15 e15, T16 e16) { + public SeptendecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, + T10 e10, T11 e11, T12 e12, T13 e13, T14 e14, T15 e15, T16 e16) { super(SeptendecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptupleImpl.java index ebd55ecf..44aa88a2 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SeptupleImpl.java @@ -3,7 +3,7 @@ import com.redis.om.spring.tuple.Septuple; public final class SeptupleImpl extends AbstractTuple - implements Septuple { + implements Septuple { public SeptupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) { super(SeptupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SexdecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SexdecupleImpl.java index 1672ea90..7999de01 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SexdecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/SexdecupleImpl.java @@ -1,13 +1,12 @@ - package com.redis.om.spring.tuple.impl; import com.redis.om.spring.tuple.Sexdecuple; public final class SexdecupleImpl - extends AbstractTuple implements Sexdecuple { + extends AbstractTuple implements Sexdecuple { - public SexdecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, - T13 e13, T14 e14, T15 e15) { + public SexdecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11, T12 e12, T13 e13, T14 e14, T15 e15) { super(SexdecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TredecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TredecupleImpl.java index 4ffcd8e1..e0f3f626 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TredecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TredecupleImpl.java @@ -1,13 +1,12 @@ - package com.redis.om.spring.tuple.impl; import com.redis.om.spring.tuple.Tredecuple; public final class TredecupleImpl extends AbstractTuple - implements Tredecuple { + implements Tredecuple { - public TredecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, - T12 e12) { + public TredecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11, T12 e12) { super(TredecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TripleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TripleImpl.java index 7d2222c0..63a184d6 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TripleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/TripleImpl.java @@ -1,4 +1,3 @@ - package com.redis.om.spring.tuple.impl; import com.redis.om.spring.tuple.Triple; diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/UndecupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/UndecupleImpl.java index e156aaf3..0db210b3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/UndecupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/UndecupleImpl.java @@ -1,10 +1,9 @@ - package com.redis.om.spring.tuple.impl; import com.redis.om.spring.tuple.Undecuple; public final class UndecupleImpl extends AbstractTuple - implements Undecuple { + implements Undecuple { public UndecupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10) { super(UndecupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/VigintupleImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/VigintupleImpl.java index 66a6621a..41398c08 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/VigintupleImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/VigintupleImpl.java @@ -1,16 +1,15 @@ - package com.redis.om.spring.tuple.impl; import com.redis.om.spring.tuple.Vigintuple; public final class VigintupleImpl - extends AbstractTuple - implements Vigintuple { + extends AbstractTuple + implements Vigintuple { - public VigintupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, T11 e11, T12 e12, - T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { - super(VigintupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, - e19); + public VigintupleImpl(String[] labels, T0 e0, T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6, T7 e7, T8 e8, T9 e9, T10 e10, + T11 e11, T12 e12, T13 e13, T14 e14, T15 e15, T16 e16, T17 e17, T18 e18, T19 e19) { + super(VigintupleImpl.class, labels, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, + e18, e19); } @SuppressWarnings("unchecked") diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DecupleMapperImpl.java index 0bf05fcb..52575171 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DecupleMapperImpl.java @@ -7,11 +7,11 @@ import java.util.function.Function; public final class DecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public DecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9) { super(10); set(0, m0); set(1, m1); @@ -28,8 +28,8 @@ public DecupleMapperImpl(Function m0, Function m1, Function @Override public Decuple apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DuodecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DuodecupleMapperImpl.java index a8b1e756..00d2e77d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DuodecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/DuodecupleMapperImpl.java @@ -7,11 +7,11 @@ import java.util.function.Function; public final class DuodecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public DuodecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11) { super(12); set(0, m0); set(1, m1); @@ -30,8 +30,8 @@ public DuodecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/EmptyTupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/EmptyTupleMapperImpl.java index 874b2a76..613a66c4 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/EmptyTupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/EmptyTupleMapperImpl.java @@ -4,19 +4,18 @@ import com.redis.om.spring.tuple.EmptyTuple; import com.redis.om.spring.tuple.Tuples; -public final class EmptyTupleMapperImpl -extends AbstractTupleMapper { +public final class EmptyTupleMapperImpl extends AbstractTupleMapper { - public static final EmptyTupleMapperImpl EMPTY_MAPPER = new EmptyTupleMapperImpl<>(); + public static final EmptyTupleMapperImpl EMPTY_MAPPER = new EmptyTupleMapperImpl<>(); - private EmptyTupleMapperImpl() { - super(0); - } + private EmptyTupleMapperImpl() { + super(0); + } - @Override - public EmptyTuple apply(T t) { - return Tuples.of( + @Override + public EmptyTuple apply(T t) { + return Tuples.of( - ); - } + ); + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/HextupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/HextupleMapperImpl.java index 399a5350..0f52b06b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/HextupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/HextupleMapperImpl.java @@ -7,10 +7,10 @@ import java.util.function.Function; public final class HextupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public HextupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5) { + Function m4, Function m5) { super(6); set(0, m0); set(1, m1); @@ -23,7 +23,7 @@ public HextupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t)); + getFifth().apply(t), getSixth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NonupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NonupleMapperImpl.java index 7f32ebe9..ab550f5b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NonupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NonupleMapperImpl.java @@ -7,10 +7,10 @@ import java.util.function.Function; public final class NonupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public NonupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8) { + Function m4, Function m5, Function m6, Function m7, Function m8) { super(9); set(0, m0); set(1, m1); @@ -26,7 +26,7 @@ public NonupleMapperImpl(Function m0, Function m1, Function @Override public Nonuple apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NovemdecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NovemdecupleMapperImpl.java index f027808f..4f243100 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NovemdecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/NovemdecupleMapperImpl.java @@ -7,13 +7,13 @@ import java.util.function.Function; public final class NovemdecupleMapperImpl - extends - AbstractTupleMapper> { + extends + AbstractTupleMapper> { public NovemdecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14, Function m15, Function m16, Function m17, Function m18) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14, Function m15, Function m16, Function m17, Function m18) { super(19); set(0, m0); set(1, m1); @@ -39,10 +39,10 @@ public NovemdecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), - getEighteenth().apply(t), getNineteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), + getEighteenth().apply(t), getNineteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctodecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctodecupleMapperImpl.java index 2fbbd15b..a81ee606 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctodecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctodecupleMapperImpl.java @@ -7,13 +7,13 @@ import java.util.function.Function; public final class OctodecupleMapperImpl - extends - AbstractTupleMapper> { + extends + AbstractTupleMapper> { public OctodecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14, Function m15, Function m16, Function m17) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14, Function m15, Function m16, Function m17) { super(18); set(0, m0); set(1, m1); @@ -38,10 +38,10 @@ public OctodecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), - getEighteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), + getEighteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctupleMapperImpl.java index 964b7897..cfef3c09 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/OctupleMapperImpl.java @@ -7,10 +7,10 @@ import java.util.function.Function; public final class OctupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public OctupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7) { + Function m4, Function m5, Function m6, Function m7) { super(8); set(0, m0); set(1, m1); @@ -25,7 +25,7 @@ public OctupleMapperImpl(Function m0, Function m1, Function @Override public Octuple apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuattuordecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuattuordecupleMapperImpl.java index 48a73687..c9739eab 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuattuordecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuattuordecupleMapperImpl.java @@ -7,11 +7,11 @@ import java.util.function.Function; public final class QuattuordecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public QuattuordecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13) { super(14); set(0, m0); set(1, m1); @@ -32,9 +32,9 @@ public QuattuordecupleMapperImpl(Function m0, Function m1, Functio @Override public Quattuordecuple apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuindecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuindecupleMapperImpl.java index aad3e1db..5a8dbac3 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuindecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuindecupleMapperImpl.java @@ -7,12 +7,12 @@ import java.util.function.Function; public final class QuindecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public QuindecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14) { super(15); set(0, m0); set(1, m1); @@ -34,9 +34,9 @@ public QuindecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuintupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuintupleMapperImpl.java index fdcff073..7a80c889 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuintupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/QuintupleMapperImpl.java @@ -6,10 +6,11 @@ import java.util.function.Function; -public final class QuintupleMapperImpl extends AbstractTupleMapper> { +public final class QuintupleMapperImpl + extends AbstractTupleMapper> { public QuintupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4) { + Function m4) { super(5); set(0, m0); set(1, m1); @@ -21,7 +22,7 @@ public QuintupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t)); + getFifth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptendecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptendecupleMapperImpl.java index af401ac4..51f25f4a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptendecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptendecupleMapperImpl.java @@ -7,13 +7,13 @@ import java.util.function.Function; public final class SeptendecupleMapperImpl - extends - AbstractTupleMapper> { + extends + AbstractTupleMapper> { public SeptendecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14, Function m15, Function m16) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14, Function m15, Function m16) { super(17); set(0, m0); set(1, m1); @@ -37,9 +37,9 @@ public SeptendecupleMapperImpl(Function m0, Function m1, Function< @Override public Septendecuple apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptupleMapperImpl.java index 3efb3aa4..9cab779e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SeptupleMapperImpl.java @@ -7,10 +7,10 @@ import java.util.function.Function; public final class SeptupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public SeptupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6) { + Function m4, Function m5, Function m6) { super(7); set(0, m0); set(1, m1); @@ -24,7 +24,7 @@ public SeptupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SexdecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SexdecupleMapperImpl.java index 184d3c12..c3749017 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SexdecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SexdecupleMapperImpl.java @@ -7,12 +7,12 @@ import java.util.function.Function; public final class SexdecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public SexdecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14, Function m15) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14, Function m15) { super(16); set(0, m0); set(1, m1); @@ -35,9 +35,9 @@ public SexdecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SingleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SingleMapperImpl.java index 9c161405..f769704d 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SingleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/SingleMapperImpl.java @@ -6,22 +6,19 @@ import java.util.function.Function; -public final class SingleMapperImpl -extends AbstractTupleMapper> { +public final class SingleMapperImpl extends AbstractTupleMapper> { - public SingleMapperImpl(Function m0) { - super(1); - set(0, m0); - } + public SingleMapperImpl(Function m0) { + super(1); + set(0, m0); + } - @Override - public Single apply(T t) { - return Tuples.of( - getFirst().apply(t) - ); - } + @Override + public Single apply(T t) { + return Tuples.of(getFirst().apply(t)); + } - public Function getFirst() { - return getAndCast(0); - } + public Function getFirst() { + return getAndCast(0); + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/TredecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/TredecupleMapperImpl.java index 6015b966..99f5dac0 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/TredecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/TredecupleMapperImpl.java @@ -7,11 +7,11 @@ import java.util.function.Function; public final class TredecupleMapperImpl - extends AbstractTupleMapper> { + extends AbstractTupleMapper> { public TredecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12) { super(13); set(0, m0); set(1, m1); @@ -31,8 +31,8 @@ public TredecupleMapperImpl(Function m0, Function m1, Function apply(T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/UndecupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/UndecupleMapperImpl.java index bd4ee5dd..ff46bb78 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/UndecupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/UndecupleMapperImpl.java @@ -7,92 +7,73 @@ import java.util.function.Function; public final class UndecupleMapperImpl -extends AbstractTupleMapper> { - - public UndecupleMapperImpl( - Function m0, - Function m1, - Function m2, - Function m3, - Function m4, - Function m5, - Function m6, - Function m7, - Function m8, - Function m9, - Function m10) { - super(11); - set(0, m0); - set(1, m1); - set(2, m2); - set(3, m3); - set(4, m4); - set(5, m5); - set(6, m6); - set(7, m7); - set(8, m8); - set(9, m9); - set(10, m10); - } - - @Override - public Undecuple apply(T t) { - return Tuples.of( - getFirst().apply(t), - getSecond().apply(t), - getThird().apply(t), - getFourth().apply(t), - getFifth().apply(t), - getSixth().apply(t), - getSeventh().apply(t), - getEighth().apply(t), - getNinth().apply(t), - getTenth().apply(t), - getEleventh().apply(t) - ); - } - - public Function getFirst() { - return getAndCast(0); - } - - public Function getSecond() { - return getAndCast(1); - } - - public Function getThird() { - return getAndCast(2); - } - - public Function getFourth() { - return getAndCast(3); - } - - public Function getFifth() { - return getAndCast(4); - } - - public Function getSixth() { - return getAndCast(5); - } - - public Function getSeventh() { - return getAndCast(6); - } - - public Function getEighth() { - return getAndCast(7); - } - - public Function getNinth() { - return getAndCast(8); - } - - public Function getTenth() { - return getAndCast(9); - } - - public Function getEleventh() { - return getAndCast(10); - } + extends AbstractTupleMapper> { + + public UndecupleMapperImpl(Function m0, Function m1, Function m2, Function m3, + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10) { + super(11); + set(0, m0); + set(1, m1); + set(2, m2); + set(3, m3); + set(4, m4); + set(5, m5); + set(6, m6); + set(7, m7); + set(8, m8); + set(9, m9); + set(10, m10); + } + + @Override + public Undecuple apply(T t) { + return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t)); + } + + public Function getFirst() { + return getAndCast(0); + } + + public Function getSecond() { + return getAndCast(1); + } + + public Function getThird() { + return getAndCast(2); + } + + public Function getFourth() { + return getAndCast(3); + } + + public Function getFifth() { + return getAndCast(4); + } + + public Function getSixth() { + return getAndCast(5); + } + + public Function getSeventh() { + return getAndCast(6); + } + + public Function getEighth() { + return getAndCast(7); + } + + public Function getNinth() { + return getAndCast(8); + } + + public Function getTenth() { + return getAndCast(9); + } + + public Function getEleventh() { + return getAndCast(10); + } } \ No newline at end of file diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/VigintupleMapperImpl.java b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/VigintupleMapperImpl.java index 4879e31e..59040ae5 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/VigintupleMapperImpl.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/tuple/impl/mapper/VigintupleMapperImpl.java @@ -7,14 +7,14 @@ import java.util.function.Function; public final class VigintupleMapperImpl - extends - AbstractTupleMapper> { + extends + AbstractTupleMapper> { public VigintupleMapperImpl(Function m0, Function m1, Function m2, Function m3, - Function m4, Function m5, Function m6, Function m7, Function m8, - Function m9, Function m10, Function m11, Function m12, Function m13, - Function m14, Function m15, Function m16, Function m17, Function m18, - Function m19) { + Function m4, Function m5, Function m6, Function m7, Function m8, + Function m9, Function m10, Function m11, Function m12, Function m13, + Function m14, Function m15, Function m16, Function m17, Function m18, + Function m19) { super(20); set(0, m0); set(1, m1); @@ -40,12 +40,12 @@ public VigintupleMapperImpl(Function m0, Function m1, Function apply( - T t) { + T t) { return Tuples.of(getFirst().apply(t), getSecond().apply(t), getThird().apply(t), getFourth().apply(t), - getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), - getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), - getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), - getEighteenth().apply(t), getNineteenth().apply(t), getTwentieth().apply(t)); + getFifth().apply(t), getSixth().apply(t), getSeventh().apply(t), getEighth().apply(t), getNinth().apply(t), + getTenth().apply(t), getEleventh().apply(t), getTwelfth().apply(t), getThirteenth().apply(t), + getFourteenth().apply(t), getFifteenth().apply(t), getSixteenth().apply(t), getSeventeenth().apply(t), + getEighteenth().apply(t), getNineteenth().apply(t), getTwentieth().apply(t)); } public Function getFirst() { diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/util/ObjectUtils.java b/redis-om-spring/src/main/java/com/redis/om/spring/util/ObjectUtils.java index 50a98a95..3fd9a37f 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/util/ObjectUtils.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/util/ObjectUtils.java @@ -46,15 +46,42 @@ import static org.springframework.util.ClassUtils.resolvePrimitiveIfNecessary; public class ObjectUtils { + public static final Character REPLACEMENT_CHARACTER = '_'; + static final Set JAVA_LITERAL_WORDS = Set.of("true", "false", "null"); + // Java reserved keywords + static final Set JAVA_RESERVED_WORDS = Collections.unmodifiableSet(Stream.of( + // Unused + "const", "goto", + // The real ones... + "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", + "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", + "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", + "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", + "float", "native", "super", "while").collect(Collectors.toSet())); + static final Set> JAVA_BUILT_IN_CLASSES = Set.of(Boolean.class, Byte.class, Character.class, Double.class, + Float.class, Integer.class, Long.class, Object.class, Short.class, String.class, BigDecimal.class, BigInteger.class, + boolean.class, byte.class, char.class, double.class, float.class, int.class, long.class, short.class); + private static final ExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser(); + private static final Set JAVA_BUILT_IN_CLASS_WORDS = Collections.unmodifiableSet( + JAVA_BUILT_IN_CLASSES.stream().map(Class::getSimpleName).collect(Collectors.toSet())); + private static final Set JAVA_USED_WORDS = Collections.unmodifiableSet( + Stream.of(JAVA_LITERAL_WORDS, JAVA_RESERVED_WORDS, JAVA_BUILT_IN_CLASS_WORDS).flatMap(Collection::stream) + .collect(Collectors.toSet())); + private static final Set JAVA_USED_WORDS_LOWER_CASE = Collections.unmodifiableSet( + JAVA_USED_WORDS.stream().map(String::toLowerCase).collect(Collectors.toSet())); + + private ObjectUtils() { + } + public static String getDistanceAsRedisString(Distance distance) { return String.format("%s %s", distance.getValue(), distance.getUnit()); } public static List getFieldsWithAnnotation(Class clazz, Class annotationClass) { return getDeclaredFieldsTransitively(clazz) // - .stream() // - .filter(f -> f.isAnnotationPresent(annotationClass)) // - .toList(); + .stream() // + .filter(f -> f.isAnnotationPresent(annotationClass)) // + .toList(); } public static GeoUnit getDistanceUnit(Distance distance) { @@ -127,7 +154,8 @@ public static Optional getIdFieldForEntityClass(Class cl) { public static Object getIdFieldForEntity(Object entity) { Optional maybeIdField = getIdFieldForEntityClass(entity.getClass()); - if (maybeIdField.isEmpty()) return null; + if (maybeIdField.isEmpty()) + return null; Field idField = maybeIdField.get(); @@ -263,7 +291,7 @@ public static String shortName(String longName) { } public static boolean isPropertyAnnotatedWith(Class cls, String property, - Class annotationClass) { + Class annotationClass) { Field field; try { field = ReflectionUtils.findField(cls, property); @@ -278,17 +306,17 @@ public static boolean isPropertyAnnotatedWith(Class cls, String property, } public static Object documentToObject(Document document, Class returnedObjectType, - MappingRedisOMConverter mappingConverter) { + MappingRedisOMConverter mappingConverter) { Bucket b = new Bucket(); document.getProperties().forEach(p -> b.put(p.getKey(), (byte[]) p.getValue())); return mappingConverter.read(returnedObjectType, new RedisData(b)); } - public static Object mapToObject(Map properties, Class returnedObjectType, - MappingRedisOMConverter mappingConverter) { + public static Object mapToObject(Map properties, Class returnedObjectType, + MappingRedisOMConverter mappingConverter) { Bucket b = new Bucket(); - properties.forEach((k,v) -> b.put(k, v.toString().getBytes())); + properties.forEach((k, v) -> b.put(k, v.toString().getBytes())); return mappingConverter.read(returnedObjectType, new RedisData(b)); } @@ -353,7 +381,7 @@ public static Set getBeanDefinitionsFor(ApplicationContext ac, C } public static List> getEnableRedisDocumentRepositories( - ApplicationContext ac) { + ApplicationContext ac) { Map annotatedBeans = ac.getBeansWithAnnotation(SpringBootApplication.class); annotatedBeans.putAll(ac.getBeansWithAnnotation(Configuration.class)); List> erdrs = new ArrayList<>(); @@ -369,7 +397,7 @@ public static List> getEnableRedis } public static List> getEnableRedisEnhancedRepositories( - ApplicationContext ac) { + ApplicationContext ac) { Map annotatedBeans = ac.getBeansWithAnnotation(SpringBootApplication.class); annotatedBeans.putAll(ac.getBeansWithAnnotation(Configuration.class)); List> erers = new ArrayList<>(); @@ -521,8 +549,6 @@ public Iterator iterator() { }; } - private static final ExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser(); - public static Object getValueByPath(Object target, String path) { // Remove JSONPath prefix String safeSpelPath = path.replace("$.", ""); @@ -533,8 +559,8 @@ public static Object getValueByPath(Object target, String path) { if (!hasNestedObject) { safeSpelPath = safeSpelPath // - .replace("[*]", "") // - .replace(".", "?."); + .replace("[*]", "") // + .replace(".", "?."); value = SPEL_EXPRESSION_PARSER.parseExpression(safeSpelPath).getValue(target); } else { @@ -542,7 +568,7 @@ public static Object getValueByPath(Object target, String path) { String[] parts = tempParts[1].split("\\.", 2); String leftPath = tempParts[0].replace(".", "?."); String rightPath = parts[1].replace(".", "?.") // - .replace("[*]", ""); + .replace("[*]", ""); Expression leftExp = SPEL_EXPRESSION_PARSER.parseExpression(leftPath); Expression rightExp = SPEL_EXPRESSION_PARSER.parseExpression(rightPath); @@ -601,34 +627,6 @@ public static String replaceIfIllegalJavaIdentifierCharacter(final String word) return sb.toString(); } - static final Set JAVA_LITERAL_WORDS = Set.of("true", "false", "null"); - - // Java reserved keywords - static final Set JAVA_RESERVED_WORDS = Collections.unmodifiableSet(Stream.of( - // Unused - "const", "goto", - // The real ones... - "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", - "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", - "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", - "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", - "const", "float", "native", "super", "while").collect(Collectors.toSet())); - - static final Set> JAVA_BUILT_IN_CLASSES = Set.of(Boolean.class, Byte.class, Character.class, Double.class, - Float.class, Integer.class, Long.class, Object.class, Short.class, String.class, BigDecimal.class, - BigInteger.class, boolean.class, byte.class, char.class, double.class, float.class, int.class, long.class, - short.class); - - private static final Set JAVA_BUILT_IN_CLASS_WORDS = Collections - .unmodifiableSet(JAVA_BUILT_IN_CLASSES.stream().map(Class::getSimpleName).collect(Collectors.toSet())); - - private static final Set JAVA_USED_WORDS = Collections - .unmodifiableSet(Stream.of(JAVA_LITERAL_WORDS, JAVA_RESERVED_WORDS, JAVA_BUILT_IN_CLASS_WORDS) - .flatMap(Collection::stream).collect(Collectors.toSet())); - - private static final Set JAVA_USED_WORDS_LOWER_CASE = Collections - .unmodifiableSet(JAVA_USED_WORDS.stream().map(String::toLowerCase).collect(Collectors.toSet())); - /** * Returns a static field name representation of the specified camel-cased * string. @@ -643,8 +641,7 @@ public static String staticField(final String externalName) { public static String javaNameFromExternal(final String externalName) { requireNonNull(externalName); - return ObjectUtils - .replaceIfIllegalJavaIdentifierCharacter(replaceIfJavaUsedWord(nameFromExternal(externalName))); + return ObjectUtils.replaceIfIllegalJavaIdentifierCharacter(replaceIfJavaUsedWord(nameFromExternal(externalName))); } public static String nameFromExternal(final String externalName) { @@ -655,7 +652,7 @@ public static String nameFromExternal(final String externalName) { * -capital-letters-are-found-consecutively-in-a [A-Z] -> \p{Lu} [^A-Za-z0-9] -> * [^\pL0-90-9] */ result = Stream.of(result.replaceAll("(\\p{Lu}+)", "_$1").split("[^\\pL\\d]")).map(String::toLowerCase) - .map(ObjectUtils::ucfirst).collect(Collectors.joining()); + .map(ObjectUtils::ucfirst).collect(Collectors.joining()); return result; } @@ -700,9 +697,4 @@ public static String getSchemaFieldType(Schema.Field field) { } return ""; // Return null if type is not found or invalid format } - - public static final Character REPLACEMENT_CHARACTER = '_'; - - private ObjectUtils() { - } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/util/SpringContext.java b/redis-om-spring/src/main/java/com/redis/om/spring/util/SpringContext.java index 71e97cde..ee70728b 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/util/SpringContext.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/util/SpringContext.java @@ -21,12 +21,6 @@ public static T getBean(Class beanClass) { return context.getBean(beanClass); } - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - // store ApplicationContext reference to access required beans later on - setContext(context); - } - /** * Private method context setting (better practice for setting a static field in a bean * instance - see comments of this article for more info). @@ -34,4 +28,10 @@ public void setApplicationContext(ApplicationContext context) throws BeansExcept private static synchronized void setContext(ApplicationContext context) { SpringContext.context = context; } + + @Override + public void setApplicationContext(ApplicationContext context) throws BeansException { + // store ApplicationContext reference to access required beans later on + setContext(context); + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/DefaultFeatureExtractor.java b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/DefaultFeatureExtractor.java index b4c5eac7..97b5f95e 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/DefaultFeatureExtractor.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/DefaultFeatureExtractor.java @@ -28,22 +28,21 @@ import static com.redis.om.spring.util.ObjectUtils.longArrayToFloatArray; public class DefaultFeatureExtractor implements FeatureExtractor { + private static final Log logger = LogFactory.getLog(DefaultFeatureExtractor.class); + public final Pipeline imagePipeline; + public final HuggingFaceTokenizer sentenceTokenizer; private final ZooModel imageEmbeddingModel; private final ZooModel faceEmbeddingModel; private final ImageFactory imageFactory; private final ApplicationContext applicationContext; private final ImageFeatureExtractor imageFeatureExtractor; - public final Pipeline imagePipeline; - public final HuggingFaceTokenizer sentenceTokenizer; - - private static final Log logger = LogFactory.getLog(DefaultFeatureExtractor.class); public DefaultFeatureExtractor( // - ApplicationContext applicationContext, // - ZooModel imageEmbeddingModel, // - ZooModel faceEmbeddingModel, // - ImageFactory imageFactory, // - Pipeline imagePipeline, HuggingFaceTokenizer sentenceTokenizer) { + ApplicationContext applicationContext, // + ZooModel imageEmbeddingModel, // + ZooModel faceEmbeddingModel, // + ImageFactory imageFactory, // + Pipeline imagePipeline, HuggingFaceTokenizer sentenceTokenizer) { this.applicationContext = applicationContext; this.imageEmbeddingModel = imageEmbeddingModel; this.faceEmbeddingModel = faceEmbeddingModel; @@ -116,9 +115,11 @@ public void processEntity(Object item) { Resource resource = applicationContext.getResource(fieldValue.toString()); try { if (isDocument) { - accessor.setPropertyValue(vectorize.destination(), getImageEmbeddingsAsFloatArrayFor(resource.getInputStream())); + accessor.setPropertyValue(vectorize.destination(), + getImageEmbeddingsAsFloatArrayFor(resource.getInputStream())); } else { - accessor.setPropertyValue(vectorize.destination(), getImageEmbeddingsAsByteArrayFor(resource.getInputStream())); + accessor.setPropertyValue(vectorize.destination(), + getImageEmbeddingsAsByteArrayFor(resource.getInputStream())); } } catch (IOException e) { logger.warn("Error generating image embedding", e); @@ -131,9 +132,11 @@ public void processEntity(Object item) { Resource resource = applicationContext.getResource(fieldValue.toString()); try { if (isDocument) { - accessor.setPropertyValue(vectorize.destination(), getFacialImageEmbeddingsAsFloatArrayFor(resource.getInputStream())); + accessor.setPropertyValue(vectorize.destination(), + getFacialImageEmbeddingsAsFloatArrayFor(resource.getInputStream())); } else { - accessor.setPropertyValue(vectorize.destination(), getFacialImageEmbeddingsAsByteArrayFor(resource.getInputStream())); + accessor.setPropertyValue(vectorize.destination(), + getFacialImageEmbeddingsAsByteArrayFor(resource.getInputStream())); } } catch (IOException | TranslateException e) { logger.warn("Error generating facial image embedding", e); @@ -141,9 +144,11 @@ public void processEntity(Object item) { } case SENTENCE -> { if (isDocument) { - accessor.setPropertyValue(vectorize.destination(), getSentenceEmbeddingAsFloatArrayFor(fieldValue.toString())); + accessor.setPropertyValue(vectorize.destination(), + getSentenceEmbeddingAsFloatArrayFor(fieldValue.toString())); } else { - accessor.setPropertyValue(vectorize.destination(), getSentenceEmbeddingsAsByteArrayFor(fieldValue.toString())); + accessor.setPropertyValue(vectorize.destination(), + getSentenceEmbeddingsAsByteArrayFor(fieldValue.toString())); } } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceDetectionTranslator.java b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceDetectionTranslator.java index a18b4097..3b7c0c6a 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceDetectionTranslator.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceDetectionTranslator.java @@ -30,176 +30,158 @@ public class FaceDetectionTranslator implements Translator { - private final double confThresh; - private final double nmsThresh; - private final int topK; - private final double[] variance; - private final int[][] scales; - private final int[] steps; - private int width; - private int height; - - public FaceDetectionTranslator( - double confThresh, - double nmsThresh, - double[] variance, - int topK, - int[][] scales, - int[] steps) { - this.confThresh = confThresh; - this.nmsThresh = nmsThresh; - this.variance = variance; - this.topK = topK; - this.scales = scales; - this.steps = steps; + private final double confThresh; + private final double nmsThresh; + private final int topK; + private final double[] variance; + private final int[][] scales; + private final int[] steps; + private int width; + private int height; + + public FaceDetectionTranslator(double confThresh, double nmsThresh, double[] variance, int topK, int[][] scales, + int[] steps) { + this.confThresh = confThresh; + this.nmsThresh = nmsThresh; + this.variance = variance; + this.topK = topK; + this.scales = scales; + this.steps = steps; + } + + /** + * {@inheritDoc} + */ + @Override + public NDList processInput(TranslatorContext ctx, Image input) { + width = input.getWidth(); + height = input.getHeight(); + NDArray array = input.toNDArray(ctx.getNDManager(), Image.Flag.COLOR); + array = array.transpose(2, 0, 1).flip(0); // HWC -> CHW RGB -> BGR + // The network by default takes float32 + if (!array.getDataType().equals(DataType.FLOAT32)) { + array = array.toType(DataType.FLOAT32, false); } - - /** {@inheritDoc} */ - @Override - public NDList processInput(TranslatorContext ctx, Image input) { - width = input.getWidth(); - height = input.getHeight(); - NDArray array = input.toNDArray(ctx.getNDManager(), Image.Flag.COLOR); - array = array.transpose(2, 0, 1).flip(0); // HWC -> CHW RGB -> BGR - // The network by default takes float32 - if (!array.getDataType().equals(DataType.FLOAT32)) { - array = array.toType(DataType.FLOAT32, false); + NDArray mean = ctx.getNDManager().create(new float[] { 104f, 117f, 123f }, new Shape(3, 1, 1)); + array = array.sub(mean); + return new NDList(array); + } + + /** + * {@inheritDoc} + */ + @Override + public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { + NDManager manager = ctx.getNDManager(); + double scaleXY = variance[0]; + double scaleWH = variance[1]; + + NDArray prob = list.get(1).get(":, 1:"); + prob = NDArrays.stack(new NDList(prob.argMax(1).toType(DataType.FLOAT32, false), prob.max(new int[] { 1 }))); + + NDArray boxRecover = boxRecover(manager, width, height, scales, steps); + NDArray boundingBoxes = list.get(0); + NDArray bbWH = boundingBoxes.get(":, 2:").mul(scaleWH).exp().mul(boxRecover.get(":, 2:")); + NDArray bbXY = boundingBoxes.get(":, :2").mul(scaleXY).mul(boxRecover.get(":, 2:")).add(boxRecover.get(":, :2")) + .sub(bbWH.mul(0.5f)); + + boundingBoxes = NDArrays.concat(new NDList(bbXY, bbWH), 1); + + NDArray landms = list.get(2); + landms = decodeLandm(landms, boxRecover, scaleXY); + + // filter the result below the threshold + NDArray cutOff = prob.get(1).gt(confThresh); + boundingBoxes = boundingBoxes.transpose().booleanMask(cutOff, 1).transpose(); + landms = landms.transpose().booleanMask(cutOff, 1).transpose(); + prob = prob.booleanMask(cutOff, 1); + + // start categorical filtering + long[] order = prob.get(1).argSort().get(":" + topK).toLongArray(); + prob = prob.transpose(); + List retNames = new ArrayList<>(); + List retProbs = new ArrayList<>(); + List retBB = new ArrayList<>(); + + Map> recorder = new ConcurrentHashMap<>(); + + for (int i = order.length - 1; i >= 0; i--) { + long currMaxLoc = order[i]; + float[] classProb = prob.get(currMaxLoc).toFloatArray(); + int classId = (int) classProb[0]; + double probability = classProb[1]; + + double[] boxArr = boundingBoxes.get(currMaxLoc).toDoubleArray(); + double[] landmsArr = landms.get(currMaxLoc).toDoubleArray(); + Rectangle rect = new Rectangle(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); + List boxes = recorder.getOrDefault(classId, new ArrayList<>()); + boolean belowIoU = true; + for (BoundingBox box : boxes) { + if (box.getIoU(rect) > nmsThresh) { + belowIoU = false; + break; } - NDArray mean = - ctx.getNDManager().create(new float[] {104f, 117f, 123f}, new Shape(3, 1, 1)); - array = array.sub(mean); - return new NDList(array); - } - - /** {@inheritDoc} */ - @Override - public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { - NDManager manager = ctx.getNDManager(); - double scaleXY = variance[0]; - double scaleWH = variance[1]; - - NDArray prob = list.get(1).get(":, 1:"); - prob = - NDArrays.stack( - new NDList( - prob.argMax(1).toType(DataType.FLOAT32, false), - prob.max(new int[] {1}))); - - NDArray boxRecover = boxRecover(manager, width, height, scales, steps); - NDArray boundingBoxes = list.get(0); - NDArray bbWH = boundingBoxes.get(":, 2:").mul(scaleWH).exp().mul(boxRecover.get(":, 2:")); - NDArray bbXY = - boundingBoxes - .get(":, :2") - .mul(scaleXY) - .mul(boxRecover.get(":, 2:")) - .add(boxRecover.get(":, :2")) - .sub(bbWH.mul(0.5f)); - - boundingBoxes = NDArrays.concat(new NDList(bbXY, bbWH), 1); - - NDArray landms = list.get(2); - landms = decodeLandm(landms, boxRecover, scaleXY); - - // filter the result below the threshold - NDArray cutOff = prob.get(1).gt(confThresh); - boundingBoxes = boundingBoxes.transpose().booleanMask(cutOff, 1).transpose(); - landms = landms.transpose().booleanMask(cutOff, 1).transpose(); - prob = prob.booleanMask(cutOff, 1); - - // start categorical filtering - long[] order = prob.get(1).argSort().get(":" + topK).toLongArray(); - prob = prob.transpose(); - List retNames = new ArrayList<>(); - List retProbs = new ArrayList<>(); - List retBB = new ArrayList<>(); - - Map> recorder = new ConcurrentHashMap<>(); - - for (int i = order.length - 1; i >= 0; i--) { - long currMaxLoc = order[i]; - float[] classProb = prob.get(currMaxLoc).toFloatArray(); - int classId = (int) classProb[0]; - double probability = classProb[1]; - - double[] boxArr = boundingBoxes.get(currMaxLoc).toDoubleArray(); - double[] landmsArr = landms.get(currMaxLoc).toDoubleArray(); - Rectangle rect = new Rectangle(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); - List boxes = recorder.getOrDefault(classId, new ArrayList<>()); - boolean belowIoU = true; - for (BoundingBox box : boxes) { - if (box.getIoU(rect) > nmsThresh) { - belowIoU = false; - break; - } - } - if (belowIoU) { - List keyPoints = new ArrayList<>(); - for (int j = 0; j < 5; j++) { // 5 face landmarks - double x = landmsArr[j * 2]; - double y = landmsArr[j * 2 + 1]; - keyPoints.add(new Point(x * width, y * height)); - } - Landmark landmark = - new Landmark(boxArr[0], boxArr[1], boxArr[2], boxArr[3], keyPoints); - - boxes.add(landmark); - recorder.put(classId, boxes); - String className = "Face"; // classes.get(classId) - retNames.add(className); - retProbs.add(probability); - retBB.add(landmark); - } + } + if (belowIoU) { + List keyPoints = new ArrayList<>(); + for (int j = 0; j < 5; j++) { // 5 face landmarks + double x = landmsArr[j * 2]; + double y = landmsArr[j * 2 + 1]; + keyPoints.add(new Point(x * width, y * height)); } - - return new DetectedObjects(retNames, retProbs, retBB); + Landmark landmark = new Landmark(boxArr[0], boxArr[1], boxArr[2], boxArr[3], keyPoints); + + boxes.add(landmark); + recorder.put(classId, boxes); + String className = "Face"; // classes.get(classId) + retNames.add(className); + retProbs.add(probability); + retBB.add(landmark); + } } - private NDArray boxRecover( - NDManager manager, int width, int height, int[][] scales, int[] steps) { - int[][] aspectRatio = new int[steps.length][2]; - for (int i = 0; i < steps.length; i++) { - int wRatio = (int) Math.ceil((float) width / steps[i]); - int hRatio = (int) Math.ceil((float) height / steps[i]); - aspectRatio[i] = new int[] {hRatio, wRatio}; - } + return new DetectedObjects(retNames, retProbs, retBB); + } - List defaultBoxes = new ArrayList<>(); - - for (int idx = 0; idx < steps.length; idx++) { - int[] scale = scales[idx]; - for (int h = 0; h < aspectRatio[idx][0]; h++) { - for (int w = 0; w < aspectRatio[idx][1]; w++) { - for (int i : scale) { - double skx = i * 1.0 / width; - double sky = i * 1.0 / height; - double cx = (w + 0.5) * steps[idx] / width; - double cy = (h + 0.5) * steps[idx] / height; - defaultBoxes.add(new double[] {cx, cy, skx, sky}); - } - } - } - } + private NDArray boxRecover(NDManager manager, int width, int height, int[][] scales, int[] steps) { + int[][] aspectRatio = new int[steps.length][2]; + for (int i = 0; i < steps.length; i++) { + int wRatio = (int) Math.ceil((float) width / steps[i]); + int hRatio = (int) Math.ceil((float) height / steps[i]); + aspectRatio[i] = new int[] { hRatio, wRatio }; + } - double[][] boxes = new double[defaultBoxes.size()][defaultBoxes.get(0).length]; - for (int i = 0; i < defaultBoxes.size(); i++) { - boxes[i] = defaultBoxes.get(i); + List defaultBoxes = new ArrayList<>(); + + for (int idx = 0; idx < steps.length; idx++) { + int[] scale = scales[idx]; + for (int h = 0; h < aspectRatio[idx][0]; h++) { + for (int w = 0; w < aspectRatio[idx][1]; w++) { + for (int i : scale) { + double skx = i * 1.0 / width; + double sky = i * 1.0 / height; + double cx = (w + 0.5) * steps[idx] / width; + double cy = (h + 0.5) * steps[idx] / height; + defaultBoxes.add(new double[] { cx, cy, skx, sky }); + } } - return manager.create(boxes).clip(0.0, 1.0); + } } - // decode face landmarks, 5 points per face - private NDArray decodeLandm(NDArray pre, NDArray priors, double scaleXY) { - NDArray point1 = - pre.get(":, :2").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); - NDArray point2 = - pre.get(":, 2:4").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); - NDArray point3 = - pre.get(":, 4:6").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); - NDArray point4 = - pre.get(":, 6:8").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); - NDArray point5 = - pre.get(":, 8:10").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); - return NDArrays.concat(new NDList(point1, point2, point3, point4, point5), 1); + double[][] boxes = new double[defaultBoxes.size()][defaultBoxes.get(0).length]; + for (int i = 0; i < defaultBoxes.size(); i++) { + boxes[i] = defaultBoxes.get(i); } + return manager.create(boxes).clip(0.0, 1.0); + } + + // decode face landmarks, 5 points per face + private NDArray decodeLandm(NDArray pre, NDArray priors, double scaleXY) { + NDArray point1 = pre.get(":, :2").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); + NDArray point2 = pre.get(":, 2:4").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); + NDArray point3 = pre.get(":, 4:6").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); + NDArray point4 = pre.get(":, 6:8").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); + NDArray point5 = pre.get(":, 8:10").mul(scaleXY).mul(priors.get(":, 2:")).add(priors.get(":, :2")); + return NDArrays.concat(new NDList(point1, point2, point3, point4, point5), 1); + } } diff --git a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceFeatureTranslator.java b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceFeatureTranslator.java index eca685f2..e719c238 100644 --- a/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceFeatureTranslator.java +++ b/redis-om-spring/src/main/java/com/redis/om/spring/vectorize/face/FaceFeatureTranslator.java @@ -11,38 +11,37 @@ public class FaceFeatureTranslator implements Translator { - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public NDList processInput(TranslatorContext ctx, Image input) { NDArray array = input.toNDArray(ctx.getNDManager(), Image.Flag.COLOR); Pipeline pipeline = new Pipeline(); pipeline - // .add(new Resize(160)) - .add(new ToTensor()) - .add( - new Normalize( - new float[] {127.5f / 255.0f, 127.5f / 255.0f, 127.5f / 255.0f}, - new float[] { - 128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f - })); + // .add(new Resize(160)) + .add(new ToTensor()).add(new Normalize(new float[] { 127.5f / 255.0f, 127.5f / 255.0f, 127.5f / 255.0f }, + new float[] { 128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f })); return pipeline.transform(new NDList(array)); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public float[] processOutput(TranslatorContext ctx, NDList list) { - NDList result = new NDList(); - long numOutputs = list.singletonOrThrow().getShape().get(0); - for (int i = 0; i < numOutputs; i++) { - result.add(list.singletonOrThrow().get(i)); + try (NDList result = new NDList()) { + long numOutputs = list.singletonOrThrow().getShape().get(0); + for (int i = 0; i < numOutputs; i++) { + result.add(list.singletonOrThrow().get(i)); + } + float[][] embeddings = result.stream().map(NDArray::toFloatArray).toArray(float[][]::new); + float[] feature = new float[embeddings.length]; + for (int i = 0; i < embeddings.length; i++) { + feature[i] = embeddings[i][0]; + } + return feature; } - float[][] embeddings = - result.stream().map(NDArray::toFloatArray).toArray(float[][]::new); - float[] feature = new float[embeddings.length]; - for (int i = 0; i < embeddings.length; i++) { - feature[i] = embeddings[i][0]; - } - return feature; } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentSentinelTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentSentinelTest.java index e2c97755..08a2634e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentSentinelTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentSentinelTest.java @@ -18,31 +18,25 @@ import java.io.IOException; +@SuppressWarnings("resource") @Testcontainers(disabledWithoutDocker = true) @DirtiesContext @SpringBootTest( // classes = AbstractBaseDocumentSentinelTest.Config.class, // properties = { "spring.main.allow-bean-definition-overriding=true" } // ) -@TestPropertySource(properties = {"spring.config.location=classpath:vss_on.yaml"}) +@TestPropertySource(properties = { "spring.config.location=classpath:vss_on.yaml" }) public abstract class AbstractBaseDocumentSentinelTest { - @SpringBootApplication - @Configuration - @EnableRedisDocumentRepositories(basePackages = {"com.redis.om.spring.annotations.document.fixtures", "com.redis.om.spring.repository"}) - static class Config extends SentinelConfig { - } - + @Container + public static final DockerComposeContainer SENTINEL; protected static final int REDIS_PORT = 6379; protected static final int SENTINEL_PORT = 26379; protected static String dockerComposeFile = "sentinel/docker/docker-compose.yml"; - @Container - public static final DockerComposeContainer SENTINEL; - static { try { - SENTINEL = new DockerComposeContainer<>(new ClassPathResource(dockerComposeFile).getFile()) - .withExposedService("redis-master_1", REDIS_PORT, Wait.forListeningPort()) + SENTINEL = new DockerComposeContainer<>(new ClassPathResource(dockerComposeFile).getFile()).withExposedService( + "redis-master_1", REDIS_PORT, Wait.forListeningPort()) .withExposedService("redis-sentinel_1", SENTINEL_PORT, Wait.forListeningPort()); SENTINEL.start(); } catch (IOException e) { @@ -58,8 +52,15 @@ static void properties(DynamicPropertyRegistry registry) { registry.add("spring.redis.sentinel.master", () -> "mymaster"); registry.add("spring.redis.sentinel.nodes", - () -> SENTINEL.getServiceHost("redis-sentinel_1", SENTINEL_PORT) - + ":" + - SENTINEL.getServicePort("redis-sentinel_1", SENTINEL_PORT)); + () -> SENTINEL.getServiceHost("redis-sentinel_1", SENTINEL_PORT) + ":" + SENTINEL.getServicePort( + "redis-sentinel_1", SENTINEL_PORT)); + } + + @SpringBootApplication + @Configuration + @EnableRedisDocumentRepositories( + basePackages = { "com.redis.om.spring.annotations.document.fixtures", "com.redis.om.spring.repository" } + ) + static class Config extends SentinelConfig { } } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentTest.java index d891d493..cb45f959 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseDocumentTest.java @@ -11,14 +11,16 @@ @Testcontainers @DirtiesContext @SpringBootTest( // - classes = AbstractBaseDocumentTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) -@TestPropertySource(properties = {"spring.config.location=classpath:vss_on.yaml"}) + classes = AbstractBaseDocumentTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) +@TestPropertySource(properties = { "spring.config.location=classpath:vss_on.yaml" }) public abstract class AbstractBaseDocumentTest extends AbstractBaseOMTest { @SpringBootApplication @Configuration - @EnableRedisDocumentRepositories(basePackages = {"com.redis.om.spring.annotations.document.fixtures", "com.redis.om.spring.repository"}) + @EnableRedisDocumentRepositories( + basePackages = { "com.redis.om.spring.annotations.document.fixtures", "com.redis.om.spring.repository" } + ) static class Config extends TestConfig { } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseEnhancedRedisTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseEnhancedRedisTest.java index 3e204589..eae7c95e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseEnhancedRedisTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseEnhancedRedisTest.java @@ -7,14 +7,16 @@ import org.springframework.test.context.TestPropertySource; @SpringBootTest( // - classes = AbstractBaseEnhancedRedisTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) -@TestPropertySource(properties = {"spring.config.location=classpath:vss_on.yaml"}) + classes = AbstractBaseEnhancedRedisTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) +@TestPropertySource(properties = { "spring.config.location=classpath:vss_on.yaml" }) public abstract class AbstractBaseEnhancedRedisTest extends AbstractBaseOMTest { @SpringBootApplication @Configuration - @EnableRedisEnhancedRepositories(basePackages = { "com.redis.om.spring.annotations.hash.fixtures", "com.redis.om.spring.repository" }) + @EnableRedisEnhancedRepositories( + basePackages = { "com.redis.om.spring.annotations.hash.fixtures", "com.redis.om.spring.repository" } + ) static class Config extends TestConfig { } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseOMTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseOMTest.java index dade46e3..f1f680e9 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseOMTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/AbstractBaseOMTest.java @@ -15,7 +15,8 @@ import static com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME; -@SuppressWarnings("SpellCheckingInspection") @Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings({ "SpellCheckingInspection", "resource" }) +@Testcontainers(disabledWithoutDocker = true) @DirtiesContext public abstract class AbstractBaseOMTest { @Container @@ -38,6 +39,12 @@ public abstract class AbstractBaseOMTest { @Autowired protected RediSearchIndexer indexer; + protected Comparator closeToComparator = new Comparator() { + @Override + public int compare(Double o1, Double o2) { + return Math.abs(o1.doubleValue() - o2.doubleValue()) < 0.001 ? 0 : -1; + } + }; @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { @@ -50,11 +57,4 @@ protected void flushSearchIndexFor(Class entityClass) { indexer.createIndexFor(entityClass); } - protected Comparator closeToComparator = new Comparator() { - @Override - public int compare(Double o1, Double o2) { - return Math.abs(o1.doubleValue() - o2.doubleValue()) < 0.001 ? 0 : -1; - } - }; - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/RedisEnhancedKeyValueAdapterTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/RedisEnhancedKeyValueAdapterTest.java index cbe49e11..cde6d9e8 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/RedisEnhancedKeyValueAdapterTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/RedisEnhancedKeyValueAdapterTest.java @@ -19,18 +19,22 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings("SpellCheckingInspection") class RedisEnhancedKeyValueAdapterTest extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class RedisEnhancedKeyValueAdapterTest extends AbstractBaseEnhancedRedisTest { @Autowired @Qualifier("redisCustomKeyValueTemplate") CustomRedisKeyValueTemplate kvTemplate; - - @Autowired StringRedisTemplate template; - + + @Autowired + StringRedisTemplate template; + RedisEnhancedKeyValueAdapter adapter; @Autowired CompanyRepository repository; + Company redis; + Company microsoft; @Test void testPutRedisData() { @@ -38,41 +42,38 @@ void testPutRedisData() { rdo.setId("abc"); rdo.setKeyspace("redisdata"); kvTemplate.getAdapter().put("abc", rdo, "redisdata"); - + Object firstName = template.opsForHash().get("redisdata:abc", "firstname"); assertThat(firstName).hasToString("rand"); } - - Company redis; - Company microsoft; @BeforeEach void createData() { adapter = (RedisEnhancedKeyValueAdapter) kvTemplate.getAdapter(); repository.deleteAll(); redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); } @Test void testGetAllOf() { Iterable companies = adapter.getAllOf("com.redis.om.spring.annotations.hash.fixtures.Company", - Company.class); + Company.class); assertAll( // - () -> assertThat(repository.count()).isEqualTo(2), - () -> assertThat(companies).hasSize(2) // + () -> assertThat(repository.count()).isEqualTo(2), () -> assertThat(companies).hasSize(2) // ); } - + @Test void testGetAllOfWithRowsSet() { assertEquals(2, repository.count()); Iterable companies = adapter.getAllOf("com.redis.om.spring.annotations.hash.fixtures.Company", - Company.class, 0, 1); + Company.class, 0, 1); assertAll( // - () -> assertThat(companies).hasSize(1) // + () -> assertThat(companies).hasSize(1) // ); } @@ -82,9 +83,9 @@ void testGetAllIds() { assertEquals(2, repository.count()); List keys = adapter.getAllIds(keyspace, Company.class); assertAll( // - () -> assertThat(keys).hasSize(2), // - () -> assertThat(keys).contains(redis.getId()), // - () -> assertThat(keys).contains(microsoft.getId()) // + () -> assertThat(keys).hasSize(2), // + () -> assertThat(keys).contains(redis.getId()), // + () -> assertThat(keys).contains(microsoft.getId()) // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/RedisJSONKeyValueAdapterTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/RedisJSONKeyValueAdapterTest.java index 906c3e64..95a93a42 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/RedisJSONKeyValueAdapterTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/RedisJSONKeyValueAdapterTest.java @@ -31,11 +31,11 @@ void createData() { repository.deleteAll(); redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag")))); microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), - "research@microsoft.com"); + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -45,9 +45,9 @@ void createData() { void testGetAllOf() { assertEquals(2, repository.count()); Iterable companies = adapter.getAllOf("com.redis.om.spring.annotations.document.fixtures.Company", - Company.class); + Company.class); assertAll( // - () -> assertThat(companies).hasSize(2) // + () -> assertThat(companies).hasSize(2) // ); } @@ -55,9 +55,9 @@ void testGetAllOf() { void testGetAllOfWithRowsSet() { assertEquals(2, repository.count()); Iterable companies = adapter.getAllOf("com.redis.om.spring.annotations.document.fixtures.Company", - Company.class, 0, 1); + Company.class, 0, 1); assertAll( // - () -> assertThat(companies).hasSize(1) // + () -> assertThat(companies).hasSize(1) // ); } @@ -67,9 +67,9 @@ void testGetAllKeys() { assertEquals(2, repository.count()); List keys = adapter.getAllKeys(keyspace, Company.class); assertAll( // - () -> assertThat(keys).hasSize(2), // - () -> assertThat(keys).contains(String.format("%s:%s", keyspace, redis.getId())), // - () -> assertThat(keys).contains(String.format("%s:%s", keyspace, microsoft.getId())) // + () -> assertThat(keys).hasSize(2), // + () -> assertThat(keys).contains(String.format("%s:%s", keyspace, redis.getId())), // + () -> assertThat(keys).contains(String.format("%s:%s", keyspace, microsoft.getId())) // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/TestConfig.java b/redis-om-spring/src/test/java/com/redis/om/spring/TestConfig.java index fe79d4f0..fd2c5e59 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/TestConfig.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/TestConfig.java @@ -31,8 +31,8 @@ public JedisConnectionFactory jedisConnectionFactory() { final int timeout = 10000; final JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder() - .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout)).usePooling() - .poolConfig(poolConfig).build(); + .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout)).usePooling() + .poolConfig(poolConfig).build(); return new JedisConnectionFactory(conf, jedisClientConfiguration); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/Doc.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/Doc.java index 3e9b477a..dc7bc998 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/Doc.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/Doc.java @@ -8,7 +8,7 @@ @NoArgsConstructor @RequiredArgsConstructor(staticName = "of") @AllArgsConstructor(access = AccessLevel.PROTECTED) -@Document +@Document public class Doc { @Id private String id; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoriesAutoDiscoveryTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoriesAutoDiscoveryTest.java index 326a1b79..343e15a5 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoriesAutoDiscoveryTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoriesAutoDiscoveryTest.java @@ -13,16 +13,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest( // - classes = DocRepositoriesAutoDiscoveryTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) + classes = DocRepositoriesAutoDiscoveryTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) class DocRepositoriesAutoDiscoveryTest extends AbstractBaseOMTest { - @SpringBootApplication - @Configuration - @EnableRedisDocumentRepositories() - static class Config extends TestConfig { - } - @Autowired DocRepository repository; @@ -42,4 +36,10 @@ void testBasePackageClassesAreFound() { assertEquals(0, repository.count()); } + @SpringBootApplication + @Configuration + @EnableRedisDocumentRepositories() + static class Config extends TestConfig { + } + } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoryBasePackageClassesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoryBasePackageClassesTest.java index 296f987c..7b316547 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoryBasePackageClassesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/DocRepositoryBasePackageClassesTest.java @@ -18,23 +18,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest( // - classes = DocRepositoryBasePackageClassesTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) + classes = DocRepositoryBasePackageClassesTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) class DocRepositoryBasePackageClassesTest extends AbstractBaseOMTest { - @SpringBootApplication - @Configuration - @EnableRedisDocumentRepositories(basePackageClasses = {Company.class, CompanyRepository.class}) - static class Config extends TestConfig { - } - @Autowired CompanyRepository repository; - + @Test void testBasePackageClassesAreFound() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); assertEquals(1, repository.count()); @@ -48,4 +42,10 @@ void testBasePackageClassesAreFound() { assertEquals(0, repository.count()); } + @SpringBootApplication + @Configuration + @EnableRedisDocumentRepositories(basePackageClasses = { Company.class, CompanyRepository.class }) + static class Config extends TestConfig { + } + } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoriesAutoDiscoveryTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoriesAutoDiscoveryTest.java index d72e95b2..ac89505f 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoriesAutoDiscoveryTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoriesAutoDiscoveryTest.java @@ -15,17 +15,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest( // - classes = HashRepositoriesAutoDiscoveryTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) -@TestPropertySource(properties = {"spring.config.location=classpath:vss_on.yaml"}) + classes = HashRepositoriesAutoDiscoveryTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) +@TestPropertySource(properties = { "spring.config.location=classpath:vss_on.yaml" }) class HashRepositoriesAutoDiscoveryTest extends AbstractBaseOMTest { - @SpringBootApplication - @Configuration - @EnableRedisEnhancedRepositories() - static class Config extends TestConfig { - } - @Autowired AHashRepository repository; @@ -45,4 +39,10 @@ void testBasePackageClassesAreFound() { assertEquals(0, repository.count()); } + @SpringBootApplication + @Configuration + @EnableRedisEnhancedRepositories() + static class Config extends TestConfig { + } + } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoryBasePackageClassesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoryBasePackageClassesTest.java index 868e307e..a88143e8 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoryBasePackageClassesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/HashRepositoryBasePackageClassesTest.java @@ -19,24 +19,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest( // - classes = HashRepositoryBasePackageClassesTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) -@TestPropertySource(properties = {"spring.config.location=classpath:vss_on.yaml"}) + classes = HashRepositoryBasePackageClassesTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) +@TestPropertySource(properties = { "spring.config.location=classpath:vss_on.yaml" }) class HashRepositoryBasePackageClassesTest extends AbstractBaseOMTest { - @SpringBootApplication - @Configuration - @EnableRedisEnhancedRepositories(basePackageClasses = {Company.class, CompanyRepository.class}) - static class Config extends TestConfig { - } - @Autowired CompanyRepository repository; - + @Test void testBasePackageClassesAreFound() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); assertEquals(1, repository.count()); @@ -50,4 +44,10 @@ void testBasePackageClassesAreFound() { assertEquals(0, repository.count()); } + @SpringBootApplication + @Configuration + @EnableRedisEnhancedRepositories(basePackageClasses = { Company.class, CompanyRepository.class }) + static class Config extends TestConfig { + } + } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteDeletionTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteDeletionTest.java index 0a42ee96..74e173ba 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteDeletionTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteDeletionTest.java @@ -32,14 +32,14 @@ class AutoCompleteDeletionTest extends AbstractBaseDocumentTest { void loadAirports() { repository.deleteAll(); repository.saveAll(List.of( // - Airport.of("Huntsville International Airport", "HSV", "AL"), // - Airport.of("Mobile", "MOB", "AL"), // - Airport.of("Montgomery", "MGM", "AL"), // - Airport.of("Anchorage International Airport", "ANC", "AK"), // - Airport.of("Fairbanks International Airport", "FAI", "AK"), // - Airport.of("Juneau International Airport", "JNU", "AK"), // - Airport.of("Flagstaff", "FLG", "AZ"), // - Airport.of("Phoenix, Phoenix Sky Harbor International Airport", "PHX", "AZ") // + Airport.of("Huntsville International Airport", "HSV", "AL"), // + Airport.of("Mobile", "MOB", "AL"), // + Airport.of("Montgomery", "MGM", "AL"), // + Airport.of("Anchorage International Airport", "ANC", "AK"), // + Airport.of("Fairbanks International Airport", "FAI", "AK"), // + Airport.of("Juneau International Airport", "JNU", "AK"), // + Airport.of("Flagstaff", "FLG", "AZ"), // + Airport.of("Phoenix, Phoenix Sky Harbor International Airport", "PHX", "AZ") // )); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteTest.java index 9fa516e5..4421b9f4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/AutoCompleteTest.java @@ -36,11 +36,11 @@ class AutoCompleteTest extends AbstractBaseDocumentTest { void loadAirports(@Value("classpath:/data/airport_codes.csv") File dataFile) throws IOException { if (repository.count() != 190) { List data = Files // - .readLines(dataFile, StandardCharsets.UTF_8) // - .stream() // - .map(l -> l.split(",")) // - .map(ar -> Airport.of(ar[0], ar[1], ar[2])) // - .collect(Collectors.toList()); + .readLines(dataFile, StandardCharsets.UTF_8) // + .stream() // + .map(l -> l.split(",")) // + .map(ar -> Airport.of(ar[0], ar[1], ar[2])) // + .collect(Collectors.toList()); repository.saveAll(data); } } @@ -64,8 +64,8 @@ void testGetAutocompleteSuggestionsWithLimit() { List suggestions = repository.autoCompleteName("col", AutoCompleteOptions.get().limit(2)); List suggestionsString = suggestions.stream().map(Suggestion::getValue).collect(Collectors.toList()); assertAll( // - () -> assertThat(suggestionsString).size().isEqualTo(2), // - () -> assertThat(suggestionsString).containsAll(List.of("Columbia", "Columbus")) // + () -> assertThat(suggestionsString).size().isEqualTo(2), // + () -> assertThat(suggestionsString).containsAll(List.of("Columbia", "Columbus")) // ); } @@ -90,7 +90,7 @@ void testGetAutocompleteSuggestionsWithScores() { assertThat(suggestionsString).containsAll(List.of("Columbia", "Columbus", "Colorado Springs")); assertThat(scores).usingComparatorForType(new DoubleComparator(0.1), Double.class) - .containsAll(List.of(0.41, 0.41, 0.27)); + .containsAll(List.of(0.41, 0.41, 0.27)); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/RedisHashAutocompleteTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/RedisHashAutocompleteTest.java index d596c0b9..2d1f0edc 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/RedisHashAutocompleteTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/autocompletable/RedisHashAutocompleteTest.java @@ -13,7 +13,8 @@ import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("SpellCheckingInspection") class RedisHashAutocompleteTest extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class RedisHashAutocompleteTest extends AbstractBaseEnhancedRedisTest { @Autowired PersonRepository repository; @@ -33,7 +34,7 @@ void loadPersons() { Person kaitlyn = Person.of("Kaitlyn Michael", "kaitlyn@redis.com", "kaitlyn"); Person josefin = Person.of("Josefin Sjoeberg", "josefin.sjoeberg@redis.com", "josefin"); List persons = List.of(guyr, guyk, simon, justin, steve, kyleo, kyleb, andrew, alex, lance, rachel, kaitlyn, - josefin); + josefin); repository.saveAll(persons); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/bloom/BloomTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/bloom/BloomTest.java index 52feb38c..edacfc2e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/bloom/BloomTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/bloom/BloomTest.java @@ -12,11 +12,12 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("SpellCheckingInspection") class BloomTest extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class BloomTest extends AbstractBaseEnhancedRedisTest { @Autowired PersonRepository repository; - + @BeforeEach void loadPersons() { Person guyr = Person.of("Guy Royse", "guy.royse@redis.com", "guy"); @@ -33,7 +34,7 @@ void loadPersons() { Person kaitlyn = Person.of("Kaitlyn Michael", "kaitlyn@redis.com", "kaitlyn"); Person josefin = Person.of("Josefin Sjoeberg", "josefin.sjoeberg@redis.com", "josefin"); List persons = List.of(guyr, guyk, simon, justin, steve, kyleo, kyleb, andrew, alex, lance, rachel, kaitlyn, - josefin); + josefin); repository.saveAll(persons); } @@ -49,7 +50,7 @@ void testDynamicBloomRepositoryMethod() { assertTrue(repository.existsByEmail("kyle.owen@redis.com")); assertFalse(repository.existsByEmail("bsb@redis.com")); } - + @Test void testDynamicBloomRepositoryMethodForDefaultNamedFilter() { assertTrue(repository.existsByNickname("floridaman")); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/cuckoo/CuckooTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/cuckoo/CuckooTest.java index 9f2e13e3..cbf4bb99 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/cuckoo/CuckooTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/cuckoo/CuckooTest.java @@ -16,7 +16,7 @@ class CuckooTest extends AbstractBaseEnhancedRedisTest { @Autowired Person2Repository repository; - + @BeforeEach void loadPersons() { Person2 guyr = Person2.of("Guy Royse", "guy.royse@redis.com", "guy"); @@ -32,8 +32,8 @@ void loadPersons() { Person2 rachel = Person2.of("Rachel Elledge", "rachel@redis.com", "rachel"); Person2 kaitlyn = Person2.of("Kaitlyn Michael", "kaitlyn@redis.com", "kaitlyn"); Person2 josefin = Person2.of("Josefin Sjoeberg", "josefin.sjoeberg@redis.com", "josefin"); - List persons = List.of(guyr, guyk, simon, justin, steve, kyleo, kyleb, andrew, alex, lance, rachel, kaitlyn, - josefin); + List persons = List.of(guyr, guyk, simon, justin, steve, kyleo, kyleb, andrew, alex, lance, rachel, + kaitlyn, josefin); repository.saveAll(persons); } @@ -43,7 +43,7 @@ void testDynamicBloomRepositoryMethod() { assertTrue(repository.existsByEmail("kyle.owen@redis.com")); assertFalse(repository.existsByEmail("bsb@redis.com")); } - + @Test void testDynamicBloomRepositoryMethodForDefaultNamedFilter() { assertTrue(repository.existsByNickname("floridaman")); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/AggregationAnnotationTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/AggregationAnnotationTest.java index 11fc5122..391b0e3a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/AggregationAnnotationTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/AggregationAnnotationTest.java @@ -2,6 +2,7 @@ import com.redis.om.spring.AbstractBaseDocumentTest; import com.redis.om.spring.annotations.document.fixtures.GameRepository; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -13,19 +14,23 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -@SuppressWarnings("SpellCheckingInspection") class AggregationAnnotationTest extends AbstractBaseDocumentTest { - @Autowired GameRepository repository; +@SuppressWarnings("SpellCheckingInspection") +class AggregationAnnotationTest extends AbstractBaseDocumentTest { + @Autowired + GameRepository repository; - @BeforeEach void beforeEach() throws IOException { + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (repository.count() == 0) { repository.bulkLoad("src/test/resources/data/games.json"); } } - @Test void testCountAggregation() { + @Test + void testCountAggregation() { String[][] expectedData = { // - { "", "1498" }, { "Mad Catz", "43" }, { "Generic", "40" }, { "SteelSeries", "37" }, { "Logitech", "35" } // + { "", "1498" }, { "Mad Catz", "43" }, { "Generic", "40" }, { "SteelSeries", "37" }, { "Logitech", "35" } // }; var result = repository.countByBrand(PageRequest.of(0, 5)); @@ -36,18 +41,19 @@ IntStream.range(0, expectedData.length - 1).forEach(i -> { var row = resultAsList.get(i); assertThat(row).isNotNull()// - .isNotEmpty() // - .contains(entry("brand", expectedData[i][0])) // - .contains(entry("count", expectedData[i][1])) // - .hasSize(2); + .isNotEmpty() // + .contains(entry("brand", expectedData[i][0])) // + .contains(entry("count", expectedData[i][1])) // + .hasSize(2); }); } - @Test void testMinPrice() { + @Test + void testMinPrice() { String[][] expectedData = { // - { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, { "Goliton", "15.69" }, - { "Lenmar", "15.41" }, { "Oceantree(TM)", "12.29" }, { "Oceantree", "11.39" }, { "oooo", "10.11" }, - { "Case Logic", "9.99" }, { "Neewer", "9.71" } // + { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, { "Goliton", "15.69" }, + { "Lenmar", "15.41" }, { "Oceantree(TM)", "12.29" }, { "Oceantree", "11.39" }, { "oooo", "10.11" }, + { "Case Logic", "9.99" }, { "Neewer", "9.71" } // }; var result = repository.minPricesContainingSony(); assertThat(result.getTotalResults()).isEqualTo(27); @@ -59,11 +65,12 @@ }); } - @Test void testMaxPrice() { + @Test + void testMaxPrice() { String[][] expectedData = { // - { "Sony", "695.8" }, { null, "303.59" }, { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, - { "Playstation", "33.6" }, { "Neewer", "15.95" }, { "Goliton", "15.69" }, { "Lenmar", "15.41" }, - { "Oceantree", "12.45" } // + { "Sony", "695.8" }, { null, "303.59" }, { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, + { "Playstation", "33.6" }, { "Neewer", "15.95" }, { "Goliton", "15.69" }, { "Lenmar", "15.41" }, + { "Oceantree", "12.45" } // }; var result = repository.maxPricesContainingSony(); assertThat(result.getTotalResults()).isEqualTo(27); @@ -76,9 +83,10 @@ }); } - @Test void testCountDistinctByBrandHarcodedLimit() { + @Test + void testCountDistinctByBrandHarcodedLimit() { String[][] expectedData = { // - { null, "1466" }, { "Generic", "39" }, { "SteelSeries", "37" }, { "Mad Catz", "36" }, { "Logitech", "34" } // + { null, "1466" }, { "Generic", "39" }, { "SteelSeries", "37" }, { "Mad Catz", "36" }, { "Logitech", "34" } // }; var result = repository.top5countDistinctByBrand(); @@ -92,41 +100,44 @@ }); } - @Test void testQuantiles() { + @Test + void testQuantiles() { String[][] expectedData = { // - { "q50", "19.22" }, { "q90", "95.91" }, { "q95", "144.96" }, { "__generated_aliasavgprice", "29.7105941255" }, - { "rowcount", "1498" } // + { "q50", "19.22" }, { "q90", "95.91" }, { "q95", "144.96" }, { "__generated_aliasavgprice", "29.7105941255" }, + { "rowcount", "1498" } // }; var result = repository.priceQuantiles(); assertThat(result.getTotalResults()).isEqualTo(293); var row = result.getRow(0); - IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); + IntStream.range(0, expectedData.length - 1) + .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); } - @Test void testPriceStdDev() { + @Test + void testPriceStdDev() { String[][][] expectedData = { // - { { "brand", null }, { "stddev(price)", "58.0682859441" }, { "avgPrice", "29.7105941255" }, - { "q50Price", "19.22" }, { "rowcount", "1498" } }, // - { { "brand", "Mad Catz" }, { "stddev(price)", "63.3626941047" }, { "avgPrice", "92.4065116279" }, - { "q50Price", "84.99" }, { "rowcount", "43" } }, // - { { "brand", "Generic" }, { "stddev(price)", "13.0528444292" }, { "avgPrice", "12.439" }, - { "q50Price", "6.69" }, { "rowcount", "40" } }, // - { { "brand", "SteelSeries" }, { "stddev(price)", "44.5684434629" }, { "avgPrice", "50.0302702703" }, - { "q50Price", "39.69" }, { "rowcount", "37" } }, // - { { "brand", "Logitech" }, { "stddev(price)", "48.016387201" }, { "avgPrice", "66.5488571429" }, - { "q50Price", "55" }, { "rowcount", "35" } }, // - { { "brand", "Razer" }, { "stddev(price)", "49.0284634692" }, { "avgPrice", "98.4069230769" }, - { "q50Price", "80.49" }, { "rowcount", "26" } }, // - { { "brand", "" }, { "stddev(price)", "11.6611915524" }, { "avgPrice", "13.711" }, { "q50Price", "10" }, - { "rowcount", "20" } }, // - { { "brand", "ROCCAT" }, { "stddev(price)", "71.1336876222" }, { "avgPrice", "86.231" }, - { "q50Price", "58.72" }, { "rowcount", "20" } }, // - { { "brand", "Sony" }, { "stddev(price)", "195.848045202" }, { "avgPrice", "109.536428571" }, - { "q50Price", "44.95" }, { "rowcount", "14" } }, // - { { "brand", "Nintendo" }, { "stddev(price)", "71.1987671314" }, { "avgPrice", "53.2792307692" }, - { "q50Price", "17.99" }, { "rowcount", "13" } } // + { { "brand", null }, { "stddev(price)", "58.0682859441" }, { "avgPrice", "29.7105941255" }, + { "q50Price", "19.22" }, { "rowcount", "1498" } }, // + { { "brand", "Mad Catz" }, { "stddev(price)", "63.3626941047" }, { "avgPrice", "92.4065116279" }, + { "q50Price", "84.99" }, { "rowcount", "43" } }, // + { { "brand", "Generic" }, { "stddev(price)", "13.0528444292" }, { "avgPrice", "12.439" }, { "q50Price", "6.69" }, + { "rowcount", "40" } }, // + { { "brand", "SteelSeries" }, { "stddev(price)", "44.5684434629" }, { "avgPrice", "50.0302702703" }, + { "q50Price", "39.69" }, { "rowcount", "37" } }, // + { { "brand", "Logitech" }, { "stddev(price)", "48.016387201" }, { "avgPrice", "66.5488571429" }, + { "q50Price", "55" }, { "rowcount", "35" } }, // + { { "brand", "Razer" }, { "stddev(price)", "49.0284634692" }, { "avgPrice", "98.4069230769" }, + { "q50Price", "80.49" }, { "rowcount", "26" } }, // + { { "brand", "" }, { "stddev(price)", "11.6611915524" }, { "avgPrice", "13.711" }, { "q50Price", "10" }, + { "rowcount", "20" } }, // + { { "brand", "ROCCAT" }, { "stddev(price)", "71.1336876222" }, { "avgPrice", "86.231" }, { "q50Price", "58.72" }, + { "rowcount", "20" } }, // + { { "brand", "Sony" }, { "stddev(price)", "195.848045202" }, { "avgPrice", "109.536428571" }, + { "q50Price", "44.95" }, { "rowcount", "14" } }, // + { { "brand", "Nintendo" }, { "stddev(price)", "71.1987671314" }, { "avgPrice", "53.2792307692" }, + { "q50Price", "17.99" }, { "rowcount", "13" } } // }; var result = repository.priceStdDev(); @@ -142,84 +153,90 @@ }); } - @Test void testParseTime() { + @Test + void testParseTime() { String[][] expectedData = { // - { "brand", "" }, { "count", "20" }, { "dt", "2018-01-31T16:45:44Z" }, { "parsed_dt", "1517417144" } // + { "brand", "" }, { "count", "20" }, { "dt", "2018-01-31T16:45:44Z" }, { "parsed_dt", "1517417144" } // }; var result = repository.parseTime(); assertThat(result.getTotalResults()).isEqualTo(293); var row = result.getRow(0); - IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); + IntStream.range(0, expectedData.length - 1) + .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); } - @Test void testRandomSample() { + @Test + void testRandomSample() { var result = repository.randomSample(); assertThat(result.getTotalResults()).isEqualTo(293); result.getResults().forEach(row -> { assertThat(row).isNotNull()// - .isNotEmpty() // - .containsKey("sample") // - .hasSize(3); + .isNotEmpty() // + .containsKey("sample") // + .hasSize(3); - assertThat(row.get("sample")).asList().hasSizeBetween(1, 10); + assertThat(row.get("sample")).asInstanceOf(InstanceOfAssertFactories.LIST).hasSizeBetween(1, 10); }); } - @Test void testTimeFunctions() { + @Test + void testTimeFunctions() { String[][] expectedData = { // - { "dt", "1517417144" }, { "timefmt", "2018-01-31T16:45:44Z" }, { "day", "1517356800" }, - { "hour", "1517414400" }, { "minute", "1517417100" }, { "month", "1514764800" }, { "dayofweek", "3" }, - { "dayofmonth", "31" }, // - { "dayofyear", "30" }, { "year", "2018" } // + { "dt", "1517417144" }, { "timefmt", "2018-01-31T16:45:44Z" }, { "day", "1517356800" }, { "hour", "1517414400" }, + { "minute", "1517417100" }, { "month", "1514764800" }, { "dayofweek", "3" }, { "dayofmonth", "31" }, // + { "dayofyear", "30" }, { "year", "2018" } // }; var result = repository.timeFunctions(); assertThat(result.getTotalResults()).isEqualTo(1); var row = result.getRow(0); - IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); + IntStream.range(0, expectedData.length - 1) + .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1])); } - @Test void testStringFormat() { + @Test + void testStringFormat() { String[][][] expectedData = { // - { { "title", "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg" }, { "titleBrand", - "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg|Hellermann Tyton|Mark|4.95" } }, // - { { "title", - "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader" }, - { "titleBrand", - "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader|(null)|Mark|51.79" } }, - // - { { "title", - "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology" }, - { "titleBrand", - "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology|(null)|Mark|19.66" } }, - // - { { "title", "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC" }, - { "titleBrand", "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC|Mad Catz|Mark|193.26" } }, // - { { "title", "iConcepts THE SHOCK MASTER For Use With PC" }, - { "titleBrand", "iConcepts THE SHOCK MASTER For Use With PC|(null)|Mark|9.99" } }, // - { { "title", "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel" }, - { "titleBrand", "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel|Mad Catz|Mark|47.02" } }, // - { { "title", - "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)" }, - { "titleBrand", - "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)|(null)|Mark|34.98" } }, - // - { { "title", - "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc" }, - { "titleBrand", - "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc|iiMash®|Mark|35.98" } }, - // - { { "title", "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE" }, { "titleBrand", - "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE|Meco|Mark|3.99" } }, // - { { "title", - "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device" }, - { "titleBrand", - "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device|(null)|Mark|14.99" } } - // + { { "title", "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg" }, + { "titleBrand", "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg|Hellermann Tyton|Mark|4.95" } }, + // + { { "title", + "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader" }, + { "titleBrand", + "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader|(null)|Mark|51.79" } }, + // + { { "title", + "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology" }, + { "titleBrand", + "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology|(null)|Mark|19.66" } }, + // + { { "title", "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC" }, + { "titleBrand", "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC|Mad Catz|Mark|193.26" } }, // + { { "title", "iConcepts THE SHOCK MASTER For Use With PC" }, + { "titleBrand", "iConcepts THE SHOCK MASTER For Use With PC|(null)|Mark|9.99" } }, // + { { "title", "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel" }, + { "titleBrand", "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel|Mad Catz|Mark|47.02" } }, // + { { "title", + "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)" }, + { "titleBrand", + "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)|(null)|Mark|34.98" } }, + // + { { "title", + "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc" }, + { "titleBrand", + "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc|iiMash®|Mark|35.98" } }, + // + { { "title", "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE" }, { "titleBrand", + "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE|Meco|Mark|3.99" } }, // + { { "title", + "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device" }, + { "titleBrand", + "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device|(null)|Mark|14.99" } } + // }; var result = repository.stringFormat(); @@ -235,13 +252,14 @@ }); } - @Test void testSumPrice() { + @Test + void testSumPrice() { String[][][] expectedData = { // - { { "brand", null }, { "count", "1498" }, { "sum(price)", "44506.47" } }, // - { { "brand", "Mad Catz" }, { "count", "43" }, { "sum(price)", "3973.48" } }, // - { { "brand", "Razer" }, { "count", "26" }, { "sum(price)", "2558.58" } }, // - { { "brand", "Logitech" }, { "count", "35" }, { "sum(price)", "2329.21" } }, // - { { "brand", "SteelSeries" }, { "count", "37" }, { "sum(price)", "1851.12" } }, // + { { "brand", null }, { "count", "1498" }, { "sum(price)", "44506.47" } }, // + { { "brand", "Mad Catz" }, { "count", "43" }, { "sum(price)", "3973.48" } }, // + { { "brand", "Razer" }, { "count", "26" }, { "sum(price)", "2558.58" } }, // + { { "brand", "Logitech" }, { "count", "35" }, { "sum(price)", "2329.21" } }, // + { { "brand", "SteelSeries" }, { "count", "37" }, { "sum(price)", "1851.12" } }, // }; var result = repository.sumPrice(); @@ -257,7 +275,8 @@ }); } - @Test void testFilters() { + @Test + void testFilters() { var result = repository.filters(); assertThat(result.getTotalResults()).isEqualTo(293); @@ -267,29 +286,31 @@ }); } - @Test void testToList() { + @Test + void testToList() { var result = repository.toList(); assertThat(result.getTotalResults()).isEqualTo(293); IntStream.range(0, result.getResults().size() - 1).forEach(i -> { var row = result.getRow(i); var prices = result.getResults().get(i).get("prices"); - assertThat(prices).asList().hasSize(Math.toIntExact(row.getLong("count"))); + assertThat(prices).asInstanceOf(InstanceOfAssertFactories.LIST).hasSize(Math.toIntExact(row.getLong("count"))); }); } - @Test void testSortByMany() { + @Test + void testSortByMany() { String[][][] expectedData = { // - { { "brand", "Myiico" }, { "price", "0" } }, // - { { "brand", "Crystal Dynamics" }, { "price" } }, // - { { "brand", "yooZoo" }, { "price", "0" } }, // - { { "brand", "Century Accessory" }, { "price", "1" } }, // - { { "brand", "sumoto" }, { "price", "1" } }, // - { { "brand", "eGames" }, { "price", "1" } }, // - { { "brand", "Veecome" }, { "price", "1" } }, // - { { "brand", "Wimex" }, { "price", "1" } }, // - { { "brand", "gospel-online" }, { "price", "1" } }, // - { { "brand", "ETHAHE" }, { "price", "1" } }, // + { { "brand", "Myiico" }, { "price", "0" } }, // + { { "brand", "Crystal Dynamics" }, { "price" } }, // + { { "brand", "yooZoo" }, { "price", "0" } }, // + { { "brand", "Century Accessory" }, { "price", "1" } }, // + { { "brand", "sumoto" }, { "price", "1" } }, // + { { "brand", "eGames" }, { "price", "1" } }, // + { { "brand", "Veecome" }, { "price", "1" } }, // + { { "brand", "Wimex" }, { "price", "1" } }, // + { { "brand", "gospel-online" }, { "price", "1" } }, // + { { "brand", "ETHAHE" }, { "price", "1" } }, // }; var result = repository.sortByMany(); @@ -297,53 +318,68 @@ IntStream.range(0, expectedData.length - 1).forEach(i -> { var row = result.getRow(i); - IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); + IntStream.range(0, expectedData[i].length - 1) + .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); }); } - @Test void testLoadWithSort() { + @Test + void testLoadWithSort() { String[][][] expectedData = { // - { { "title", "Logitech MOMO Racing - Wheel and pedals set - 6 button(s) - PC, MAC - black" }, { "price", "759.12" } }, // - { { "title", "Sony PSP Slim & Lite 2000 Console" }, { "price", "695.8" } }, // + { { "title", "Logitech MOMO Racing - Wheel and pedals set - 6 button(s) - PC, MAC - black" }, + { "price", "759.12" } }, // + { { "title", "Sony PSP Slim & Lite 2000 Console" }, { "price", "695.8" } }, // }; var result = repository.loadWithSort(); assertThat(result.getTotalResults()).isEqualTo(2265); IntStream.range(0, expectedData.length - 1).forEach(i -> { var row = result.getRow(i); - IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); + IntStream.range(0, expectedData[i].length - 1) + .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); }); } - @Test void testLoadWithDocId() { + @Test + void testLoadWithDocId() { String[][][] expectedData = { // - { { "__key", "games:B00006JJIC" }, { "price", "759.12" } }, // - { { "__key", "games:B000F6W1AG" }, { "price", "695.8" } }, // - { { "__key", "games:B00002JXBD" }, { "price", "599.99" } }, // - { { "__key", "games:B00006IZIL" }, { "price", "759.12" } }, // + { { "__key", "games:B00006JJIC" }, { "price", "759.12" } }, // + { { "__key", "games:B000F6W1AG" }, { "price", "695.8" } }, // + { { "__key", "games:B00002JXBD" }, { "price", "599.99" } }, // + { { "__key", "games:B00006IZIL" }, { "price", "759.12" } }, // }; var result = repository.loadWithDocId(); assertThat(result.getTotalResults()).isEqualTo(2265); IntStream.range(0, expectedData.length - 1).forEach(i -> { var row = result.getRow(i); - IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); + IntStream.range(0, expectedData[i].length - 1) + .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1])); }); } - @Test void testFirstValue() { + @Test + void testFirstValue() { String[][][] expectedData = { // - { { "brand", "sony" }, { "top_item", "sony psp slim & lite 2000 console" }, { "top_price", "695.8" }, {"bottom_item", "sony dlchd20p high speed hdmi cable for playstation 3"}, { "bottom_price", "5.88" } }, // - { { "brand", "matias" }, { "top_item", "matias halfkeyboard usb" }, { "top_price", "559.99" }, {"bottom_item", "matias halfkeyboard usb"}, { "bottom_price", "559.99" } }, // - { { "brand", "beyerdynamic" }, { "top_item", "beyerdynamic mmx300 pc gaming premium digital headset with microphone" }, { "top_price", "359.74" }, {"bottom_item", "beyerdynamic headzone pc gaming digital surround sound system with mmx300 digital headset with microphone"}, { "bottom_price", "0" } }, // - { { "brand", "mad catz" }, { "top_item", "mad catz s.t.r.i.k.e.7 gaming keyboard" }, { "top_price", "295.95" }, {"bottom_item", "madcatz mov4545 xbox replacement breakaway cable"}, { "bottom_price", "3.49" } }, // + { { "brand", "sony" }, { "top_item", "sony psp slim & lite 2000 console" }, { "top_price", "695.8" }, + { "bottom_item", "sony dlchd20p high speed hdmi cable for playstation 3" }, { "bottom_price", "5.88" } }, // + { { "brand", "matias" }, { "top_item", "matias halfkeyboard usb" }, { "top_price", "559.99" }, + { "bottom_item", "matias halfkeyboard usb" }, { "bottom_price", "559.99" } }, // + { { "brand", "beyerdynamic" }, + { "top_item", "beyerdynamic mmx300 pc gaming premium digital headset with microphone" }, + { "top_price", "359.74" }, { "bottom_item", + "beyerdynamic headzone pc gaming digital surround sound system with mmx300 digital headset with microphone" }, + { "bottom_price", "0" } }, // + { { "brand", "mad catz" }, { "top_item", "mad catz s.t.r.i.k.e.7 gaming keyboard" }, { "top_price", "295.95" }, + { "bottom_item", "madcatz mov4545 xbox replacement breakaway cable" }, { "bottom_price", "3.49" } }, // }; var result = repository.firstValue(); IntStream.range(0, expectedData.length - 1).forEach(i -> { var row = result.getRow(i); - IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualToIgnoringCase(expectedData[i][j][1])); + IntStream.range(0, expectedData[i].length - 1) + .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualToIgnoringCase(expectedData[i][j][1])); }); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/BasicRedisDocumentMappingTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/BasicRedisDocumentMappingTest.java index 324f6926..cf70a6fb 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/BasicRedisDocumentMappingTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/BasicRedisDocumentMappingTest.java @@ -67,24 +67,30 @@ void cleanUp() { flushSearchIndexFor(DocWithSets.class); if (deepNestRepository.count() == 0) { - DeepNest dn1 = DeepNest.of("dn-1", NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", NestLevel2.of("nl-2-1", "Here's looking at you, kid."))); - DeepNest dn2 = DeepNest.of("dn-2", NestLevel1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", NestLevel2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); - DeepNest dn3 = DeepNest.of("dn-3", NestLevel1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", NestLevel2.of("nl-2-3", "I'm Spartacus!"))); + DeepNest dn1 = DeepNest.of("dn-1", + NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", + NestLevel2.of("nl-2-1", "Here's looking at you, kid."))); + DeepNest dn2 = DeepNest.of("dn-2", + NestLevel1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", + NestLevel2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); + DeepNest dn3 = DeepNest.of("dn-3", + NestLevel1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", + NestLevel2.of("nl-2-3", "I'm Spartacus!"))); deepNestRepository.saveAll(List.of(dn1, dn2, dn3)); } jedis = new JedisPooled(Objects.requireNonNull(jedisConnectionFactory.getPoolConfig()), - jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort()); + jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort()); } @Test void testBasicCrudOperations() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -114,9 +120,9 @@ void testBasicCrudOperations() { @Test void testDeleteByIdWithExplicitRootPath() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), - "research@microsoft.com")); + "research@microsoft.com")); assertEquals(2, repository.count()); @@ -128,24 +134,25 @@ void testDeleteByIdWithExplicitRootPath() { @Test void testFindAllById() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); assertEquals(2, repository.count()); Iterable companies = repository.findAllById(List.of(redis.getId(), microsoft.getId())); assertAll( // - () -> assertThat(companies).hasSize(2), // - () -> assertThat(companies).containsExactly(redis, microsoft) // + () -> assertThat(companies).hasSize(2), // + () -> assertThat(companies).containsExactly(redis, microsoft) // ); } @Test void testUpdateSingleField() { Company redisInc = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); repository.updateField(redisInc, Company$.NAME, "Redis"); Optional maybeRedis = repository.findById(redisInc.getId()); @@ -162,42 +169,46 @@ void testUpdateLocalDateTimeField() { someDocumentRepository.updateField(docWithDateTime, SomeDocument$.DOCUMENT_CREATION_DATE, now.minusDays(5)); - assertThat(someDocumentRepository.findById(docWithDateTime.getId()).get().getDocumentCreationDate()).isEqualToIgnoringNanos(now.minusDays(5)); + assertThat( + someDocumentRepository.findById(docWithDateTime.getId()).get().getDocumentCreationDate()).isEqualToIgnoringNanos( + now.minusDays(5)); } @Test void testAuditAnnotations() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); assertAll( // - // created dates should not be null - () -> assertNotNull(redis.getCreatedDate()), // - () -> assertNotNull(microsoft.getCreatedDate()), // + // created dates should not be null + () -> assertNotNull(redis.getCreatedDate()), // + () -> assertNotNull(microsoft.getCreatedDate()), // - // created dates should be null upon creation - () -> assertNull(redis.getLastModifiedDate()), // - () -> assertNull(microsoft.getLastModifiedDate()) // + // created dates should be null upon creation + () -> assertNull(redis.getLastModifiedDate()), // + () -> assertNull(microsoft.getLastModifiedDate()) // ); repository.save(redis); repository.save(microsoft); assertAll( // - // last modified dates should not be null after a second save - () -> assertNotNull(redis.getLastModifiedDate()), // - () -> assertNotNull(microsoft.getLastModifiedDate()) // + // last modified dates should not be null after a second save + () -> assertNotNull(redis.getLastModifiedDate()), // + () -> assertNotNull(microsoft.getLastModifiedDate()) // ); } @Test void testGetFieldsByIds() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); Iterable ids = List.of(redis.getId(), microsoft.getId()); Iterable companyNames = repository.getFieldsByIds(ids, Company$.NAME); @@ -207,9 +218,10 @@ void testGetFieldsByIds() { @Test void testDynamicBloomRepositoryMethod() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); assertTrue(repository.existsByEmail(redis.getEmail())); assertTrue(repository.existsByEmail(microsoft.getEmail())); @@ -220,12 +232,13 @@ void testDynamicBloomRepositoryMethod() { void testGetNestedFields() { Set redisEmployees = Sets.newHashSet(Employee.of("Guy Royse"), Employee.of("Simon Prickett")); Company redisInc = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redisInc.setEmployees(redisEmployees); Set msEmployees = Sets.newHashSet(Employee.of("Kevin Scott")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); microsoft.setEmployees(msEmployees); repository.saveAll(List.of(redisInc, microsoft)); @@ -265,9 +278,10 @@ void testFindByMany() { @Test void testTagEscapeChars() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); assertEquals(2, repository.count()); @@ -306,7 +320,7 @@ void testMaxQueryReturnDefaultsToPropMaxSearchResults() { final List bunchOfCompanies = new ArrayList<>(); IntStream.range(1, 100).forEach(i -> { Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "company" + i + "@inc.com"); + "company" + i + "@inc.com"); if (i % 2 == 0) c.setPubliclyListed(true); bunchOfCompanies.add(c); @@ -317,27 +331,28 @@ void testMaxQueryReturnDefaultsToPropMaxSearchResults() { // noinspection ResultOfMethodCallIgnored assertAll( // - () -> assertThat(publiclyListed).hasSize(49), // - () -> assertThat(publiclyListed).allSatisfy(Company::isPubliclyListed) // + () -> assertThat(publiclyListed).hasSize(49), // + () -> assertThat(publiclyListed).allSatisfy(Company::isPubliclyListed) // ); } @Test void testFindByTagsIn() { Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Set employees = Sets.newHashSet(Employee.of("Brian Sam-Bodden"), Employee.of("Guy Royse"), - Employee.of("Justin Castilla")); + Employee.of("Justin Castilla")); redis.setEmployees(employees); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); microsoft.setTags(Set.of("innovative", "reliable", "os", "ai")); Company tesla = repository.save( - Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); + Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); tesla.setTags(Set.of("innovative", "futuristic", "ai")); repository.saveAll(List.of(redis, microsoft, tesla)); @@ -354,9 +369,9 @@ void testFindByTagsIn() { @Test void testAuditAnnotationsOnSaveAll() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), - "research@microsoft.com"); + "research@microsoft.com"); repository.saveAll(List.of(redis, microsoft)); @@ -369,12 +384,12 @@ void testAuditAnnotationsOnSaveAll() { Iterable companies = repository.findAllById(List.of(redis.getId(), microsoft.getId())); assertAll( // - () -> assertThat(companies).hasSize(2), // - () -> assertThat(companies).containsExactly(redis, microsoft), // - () -> assertThat(redis.getCreatedDate()).isNotNull(), // - () -> assertThat(redis.getLastModifiedDate()).isNull(), // - () -> assertThat(microsoft.getCreatedDate()).isNotNull(), // - () -> assertThat(microsoft.getLastModifiedDate()).isNotNull()); + () -> assertThat(companies).hasSize(2), // + () -> assertThat(companies).containsExactly(redis, microsoft), // + () -> assertThat(redis.getCreatedDate()).isNotNull(), // + () -> assertThat(redis.getLastModifiedDate()).isNull(), // + () -> assertThat(microsoft.getCreatedDate()).isNotNull(), // + () -> assertThat(microsoft.getLastModifiedDate()).isNotNull()); } @Test @@ -505,11 +520,11 @@ void testSearchContainingAllInSetOfLocations() { @Test void testFindByTagsInNestedField() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -521,21 +536,20 @@ void testFindByTagsInNestedField() { List shouldBeBoth = repository.findByMetaList_tagValues(Set.of("CommonTag")); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // - () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", - "Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // + () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", "Microsoft") // ); } @Test void testFindByStringValueInNestedField() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -546,19 +560,19 @@ void testFindByStringValueInNestedField() { List shouldBeOnlyMS = repository.findByMetaList_stringValue("MS"); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @Test void testFindByNumericValueInNestedField() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -569,19 +583,19 @@ void testFindByNumericValueInNestedField() { List shouldBeOnlyMS = repository.findByMetaList_numberValue(50); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @Test void testFindByTagValueStartingWith() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -592,19 +606,19 @@ void testFindByTagValueStartingWith() { List shouldBeOnlyMS = repository.findByEmailStartingWith("res"); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @Test void testFindByTagValueEndingWith() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); repository.saveAll(List.of(redis, microsoft)); @@ -615,30 +629,28 @@ void testFindByTagValueEndingWith() { List shouldBeOnlyMS = repository.findByEmailEndingWith("t.com"); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @Test void testOrderByInMethodName() { repository.saveAll( - List.of( - Company.of("aaa", 2000, LocalDate.of(2020, 5, 1), new Point(-122.066540, 37.377690), "aaa@aaa.com"), - Company.of("bbb", 2000, LocalDate.of(2021, 6, 2), new Point(-122.066540, 37.377690), "bbb@bbb.com"), - Company.of("ccc", 2000, LocalDate.of(2022, 7, 3), new Point(-122.066540, 37.377690), "ccc@ccc.com") - )); + List.of(Company.of("aaa", 2000, LocalDate.of(2020, 5, 1), new Point(-122.066540, 37.377690), "aaa@aaa.com"), + Company.of("bbb", 2000, LocalDate.of(2021, 6, 2), new Point(-122.066540, 37.377690), "bbb@bbb.com"), + Company.of("ccc", 2000, LocalDate.of(2022, 7, 3), new Point(-122.066540, 37.377690), "ccc@ccc.com"))); List byNameAsc = repository.findByYearFoundedOrderByNameAsc(2000); List byNameDesc = repository.findByYearFoundedOrderByNameDesc(2000); assertAll( // - () -> assertThat(byNameAsc).extracting("name").containsExactly("aaa", "bbb", "ccc"), - () -> assertThat(byNameDesc).extracting("name").containsExactly("ccc", "bbb", "aaa") - ); + () -> assertThat(byNameAsc).extracting("name").containsExactly("aaa", "bbb", "ccc"), + () -> assertThat(byNameDesc).extracting("name").containsExactly("ccc", "bbb", "aaa")); } - @Test void testEnumsAreIndexed() { + @Test + void testEnumsAreIndexed() { DocWithEnum doc1 = DocWithEnum.of(MyJavaEnum.VALUE_1, MyJavaEnum.VALUE_1); DocWithEnum doc2 = DocWithEnum.of(MyJavaEnum.VALUE_2, MyJavaEnum.VALUE_2); DocWithEnum doc3 = DocWithEnum.of(MyJavaEnum.VALUE_3, MyJavaEnum.VALUE_3); @@ -650,9 +662,9 @@ void testOrderByInMethodName() { List onlyVal3 = docWithEnumRepository.findByEnumProp(MyJavaEnum.VALUE_3); assertAll( // - () -> assertThat(onlyVal1).containsExactly(doc1), // - () -> assertThat(onlyVal2).containsExactly(doc2), // - () -> assertThat(onlyVal3).containsExactly(doc3) // + () -> assertThat(onlyVal1).containsExactly(doc1), // + () -> assertThat(onlyVal2).containsExactly(doc2), // + () -> assertThat(onlyVal3).containsExactly(doc3) // ); } @@ -665,9 +677,9 @@ void testUpdateDeepNestedField() { Optional dn1After = deepNestRepository.findFirstByNameIs("dn-1"); assertAll( // - () -> assertThat(dn1.get().getName()).isNotEqualTo("dos-uno"), // - () -> assertTrue(dn1After.isPresent()), // - () -> assertEquals("dos-uno", dn1After.get().getNestLevel1().getNestLevel2().getName()) // + () -> assertThat(dn1.get().getName()).isNotEqualTo("dos-uno"), // + () -> assertTrue(dn1After.isPresent()), // + () -> assertEquals("dos-uno", dn1After.get().getNestLevel1().getNestLevel2().getName()) // ); } @@ -708,8 +720,7 @@ void testBasicPaginationWithSorting() { assertEquals(24, result.getTotalElements()); assertEquals(10, result.getContent().size()); - List companyNames = result.get().map(Company::getName).collect( - Collectors.toList()); + List companyNames = result.get().map(Company::getName).collect(Collectors.toList()); assertThat(Ordering.natural().isOrdered(companyNames)).isTrue(); } @@ -725,8 +736,7 @@ void testFindAllWithSorting() { Iterable result = repository.findAll(Sort.by("name").ascending()); - List companyNames = StreamSupport.stream(result.spliterator(), false) - .map(Company::getName) + List companyNames = StreamSupport.stream(result.spliterator(), false).map(Company::getName) .collect(Collectors.toList()); assertThat(Ordering.natural().isOrdered(companyNames)).isTrue(); } @@ -743,9 +753,7 @@ void testFindAllWithSortingById() { Iterable result = repository.findAll(Sort.by("id").ascending()); - List ids = StreamSupport.stream(result.spliterator(), false) - .map(Company::getId) - .toList(); + List ids = StreamSupport.stream(result.spliterator(), false).map(Company::getId).toList(); assertThat(Ordering.natural().isOrdered(ids)).isTrue(); } @@ -759,11 +767,10 @@ void testFindAllWithSortingByIdUsingMetamodel() { }); repository.saveAll(bunchOfCompanies); - Iterable result = repository.findAll(com.redis.om.spring.repository.query.Sort.by(Company$.ID).ascending()); + Iterable result = repository.findAll( + com.redis.om.spring.repository.query.Sort.by(Company$.ID).ascending()); - List ids = StreamSupport.stream(result.spliterator(), false) - .map(Company::getId) - .toList(); + List ids = StreamSupport.stream(result.spliterator(), false).map(Company::getId).toList(); assertThat(Ordering.natural().isOrdered(ids)).isTrue(); } @@ -783,19 +790,14 @@ void testFreeFormTextSearchOrderIssue() { CustomIndexDoc microsoft1 = customIndexDocRepository.save(CustomIndexDoc.of("Microsoft", "wwwabcnet")); CustomIndexDoc microsoft2 = customIndexDocRepository.save(CustomIndexDoc.of("Microsoft", "wwwxyzcom")); - var withFreeTextFirst = es.of(CustomIndexDoc.class) - .filter("*co*") - .filter(CustomIndexDoc$.FIRST.eq("Microsoft")) - .collect(Collectors.toList()); + var withFreeTextFirst = es.of(CustomIndexDoc.class).filter("*co*").filter(CustomIndexDoc$.FIRST.eq("Microsoft")) + .collect(Collectors.toList()); - var withFreeTextLast = es.of(CustomIndexDoc.class) - .filter(CustomIndexDoc$.FIRST.eq("Microsoft")) - .filter("*co*") - .collect(Collectors.toList()); + var withFreeTextLast = es.of(CustomIndexDoc.class).filter(CustomIndexDoc$.FIRST.eq("Microsoft")).filter("*co*") + .collect(Collectors.toList()); assertAll( // - () -> assertThat(withFreeTextLast).containsExactly(microsoft2), - () -> assertThat(withFreeTextFirst).containsExactly(microsoft2) - ); + () -> assertThat(withFreeTextLast).containsExactly(microsoft2), + () -> assertThat(withFreeTextFirst).containsExactly(microsoft2)); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ComplexDocumentSearchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ComplexDocumentSearchTest.java index 02129e92..3b788eac 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ComplexDocumentSearchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ComplexDocumentSearchTest.java @@ -25,7 +25,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings("SpellCheckingInspection") class ComplexDocumentSearchTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class ComplexDocumentSearchTest extends AbstractBaseDocumentTest { Permit permit1; Permit permit2; Permit permit3; @@ -68,38 +69,36 @@ void setup() { Address address1 = Address.of("Lisbon", "25 de Abril"); Order order1 = Order.of("O11", 1.5); Order order2 = Order.of("O12", 5.6); - Attribute attribute11 = Attribute.of("size","S", Lists.newArrayList(order1)); - Attribute attribute12 = Attribute.of("size","M", Lists.newArrayList(order2)); + Attribute attribute11 = Attribute.of("size", "S", Lists.newArrayList(order1)); + Attribute attribute12 = Attribute.of("size", "M", Lists.newArrayList(order2)); List attrList1 = Lists.newArrayList(attribute11, attribute12); permit1 = Permit.of( // - address1, // - "To construct a single detached house with a front covered veranda.", // - "single detached house", // - Set.of("demolition", "reconstruction"), // - 42000L, // - new Point(38.7635877,-9.2018309), // - List.of("started", "in_progress", "approved"), // - attrList1 - ); + address1, // + "To construct a single detached house with a front covered veranda.", // + "single detached house", // + Set.of("demolition", "reconstruction"), // + 42000L, // + new Point(38.7635877, -9.2018309), // + List.of("started", "in_progress", "approved"), // + attrList1); permit1.setPermitTimestamp(LocalDateTime.of(2022, 8, 1, 10, 0)); // # Document 2 Address address2 = Address.of("Porto", "Av. da Liberdade"); Order order21 = Order.of("O21", 1.2); Order order22 = Order.of("O22", 5.6); - Attribute attribute21 = Attribute.of("color","red", Lists.newArrayList(order21)); - Attribute attribute22 = Attribute.of("color","blue", Lists.newArrayList(order22)); + Attribute attribute21 = Attribute.of("color", "red", Lists.newArrayList(order21)); + Attribute attribute22 = Attribute.of("color", "blue", Lists.newArrayList(order22)); List attrList2 = Lists.newArrayList(attribute21, attribute22); permit2 = Permit.of( // - address2, // - "To construct a loft", // - "apartment", // - Set.of("construction"), // - 53000L, // - new Point(38.7205373,-9.148091), // - List.of("started", "in_progress", "rejected"), // - attrList2 - ); + address2, // + "To construct a loft", // + "apartment", // + Set.of("construction"), // + 53000L, // + new Point(38.7205373, -9.148091), // + List.of("started", "in_progress", "rejected"), // + attrList2); permit2.setPermitTimestamp(LocalDateTime.of(2022, 8, 2, 0, 0)); // # Document 3 @@ -108,39 +107,46 @@ void setup() { Order order32 = Order.of("DEF", 1.3); Order order33 = Order.of("GHJ", 1.6); Order order34 = Order.of("VBN", 1.0); - Attribute attribute31 = Attribute.of("brand","A", Lists.newArrayList(order31, order33)); - Attribute attribute32 = Attribute.of("brand","B", Lists.newArrayList(order32, order34)); + Attribute attribute31 = Attribute.of("brand", "A", Lists.newArrayList(order31, order33)); + Attribute attribute32 = Attribute.of("brand", "B", Lists.newArrayList(order32, order34)); List attrList3 = Lists.newArrayList(attribute31, attribute32); permit3 = Permit.of( // - address3, // - "New house build", // - "house", // - Set.of("construction", "design"), // - 260000L, // - new Point(37.0990749,-8.6868258), // - List.of("started", "in_progress", "postponed"), // - attrList3 - ); + address3, // + "New house build", // + "house", // + Set.of("construction", "design"), // + 260000L, // + new Point(37.0990749, -8.6868258), // + List.of("started", "in_progress", "postponed"), // + attrList3); permit3.setPermitTimestamp(LocalDateTime.of(2022, 8, 25, 0, 0)); repository.saveAll(List.of(permit1, permit2, permit3)); // complex deep nested - Complex complex1 = Complex.of("complex1", List.of(HasAList.of(List.of("Nudiustertian", "Comeuppance", "Yarborough")), HasAList.of(List.of("Sialoquent", "Pauciloquent", "Bloviate")))); - Complex complex2 = Complex.of("complex2", List.of(HasAList.of(List.of("Quire", "Zoanthropy", "Flibbertigibbet")), HasAList.of(List.of("Taradiddle", "Malarkey", "Comeuppance")))); - Complex complex3 = Complex.of("complex3", List.of(HasAList.of(List.of("Pandiculation", "Taradiddle", "Ratoon")), HasAList.of(List.of("Yarborough", "Wabbit", "Erinaceous")))); + Complex complex1 = Complex.of("complex1", + List.of(HasAList.of(List.of("Nudiustertian", "Comeuppance", "Yarborough")), + HasAList.of(List.of("Sialoquent", "Pauciloquent", "Bloviate")))); + Complex complex2 = Complex.of("complex2", List.of(HasAList.of(List.of("Quire", "Zoanthropy", "Flibbertigibbet")), + HasAList.of(List.of("Taradiddle", "Malarkey", "Comeuppance")))); + Complex complex3 = Complex.of("complex3", List.of(HasAList.of(List.of("Pandiculation", "Taradiddle", "Ratoon")), + HasAList.of(List.of("Yarborough", "Wabbit", "Erinaceous")))); complexRepository.saveAll(List.of(complex1, complex2, complex3)); // complex deep nested with uuids - WithNestedListOfUUIDs withNestedListOfUUIDs1 = WithNestedListOfUUIDs.of("withNestedListOfUUIDs1", List.of(uuid1, uuid2, uuid3)); - WithNestedListOfUUIDs withNestedListOfUUIDs2 = WithNestedListOfUUIDs.of("withNestedListOfUUIDs2", List.of(uuid4, uuid5, uuid6)); + WithNestedListOfUUIDs withNestedListOfUUIDs1 = WithNestedListOfUUIDs.of("withNestedListOfUUIDs1", + List.of(uuid1, uuid2, uuid3)); + WithNestedListOfUUIDs withNestedListOfUUIDs2 = WithNestedListOfUUIDs.of("withNestedListOfUUIDs2", + List.of(uuid4, uuid5, uuid6)); withNestedListOfUUIDsRepository.saveAll(List.of(withNestedListOfUUIDs1, withNestedListOfUUIDs2)); // complex deep nested with ulids - WithNestedListOfUlids withNestedListOfUlids1 = WithNestedListOfUlids.of("withNestedListOfUlids1", List.of(ulid1, ulid2, ulid3)); - WithNestedListOfUlids withNestedListOfUlids2 = WithNestedListOfUlids.of("withNestedListOfUlids2", List.of(ulid4, ulid5, ulid6)); + WithNestedListOfUlids withNestedListOfUlids1 = WithNestedListOfUlids.of("withNestedListOfUlids1", + List.of(ulid1, ulid2, ulid3)); + WithNestedListOfUlids withNestedListOfUlids2 = WithNestedListOfUlids.of("withNestedListOfUlids2", + List.of(ulid4, ulid5, ulid6)); withNestedListOfUlidsRepository.saveAll(List.of(withNestedListOfUlids1, withNestedListOfUlids2)); @@ -163,23 +169,23 @@ void testFullTextSearch() { @Test void testByBuildingType() { String type = "detached"; - Iterable permits = repository.findByBuildingType(type); + Iterable permits = repository.findByBuildingType(type); assertThat(permits).containsExactly(permit1); } @Test void testByCity() { - Iterable permits = repository.findByAddress_City("Lisbon"); + Iterable permits = repository.findByAddress_City("Lisbon"); assertThat(permits).containsExactly(permit1); - permits = repository.findByAddress_City("Porto"); + permits = repository.findByAddress_City("Porto"); assertThat(permits).containsExactly(permit2); } @Test void testByTags() { - Set wts = Set.of("design","construction"); - Iterable permits = repository.findByWorkType(wts); + Set wts = Set.of("design", "construction"); + Iterable permits = repository.findByWorkType(wts); assertThat(permits).containsExactlyInAnyOrder(permit2, permit3); } @@ -189,15 +195,14 @@ void testByTagsWithNullParams() { List attrs = List.of(); Address address4 = Address.of("Coimbra", "R. Serra 14"); Permit permit4 = Permit.of( // - address4, // - "Historical Renovation", // - "church", // - Set.of(), // - 260000L, // - new Point(37.0990749,-8.6868258), // - List.of(), // - attrs - ); + address4, // + "Historical Renovation", // + "church", // + Set.of(), // + 260000L, // + new Point(37.0990749, -8.6868258), // + List.of(), // + attrs); repository.save(permit4); @@ -205,11 +210,10 @@ void testByTagsWithNullParams() { assertThat(permits).isEmpty(); } - @Test void testByAllTags() { - Set wts = Set.of("design","construction"); - Iterable permits = repository.findByWorkTypeContainingAll(wts); + Set wts = Set.of("design", "construction"); + Iterable permits = repository.findByWorkTypeContainingAll(wts); assertThat(permits).containsExactly(permit3); } @@ -254,7 +258,7 @@ void testFullTextSearchExplicitEscapeSearchTerm() { void testFullTextSearchExplicitEscapeSearchTermPrefixSearch() { String q = "To construct*"; Iterable permits = repository.search(q); - assertThat(permits).containsExactly(permit1,permit2); + assertThat(permits).containsExactly(permit1, permit2); } /** @@ -268,7 +272,7 @@ void testFullTextSearchWithSortByNumericFieldDesc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(2); - assertThat(result.getContent()).containsExactly(permit2,permit1); + assertThat(result.getContent()).containsExactly(permit2, permit1); } /** @@ -282,7 +286,7 @@ void testFullTextSearchWithSortByNumericFieldAsc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(2); - assertThat(result.getContent()).containsExactly(permit1,permit2); + assertThat(result.getContent()).containsExactly(permit1, permit2); } /** @@ -324,7 +328,7 @@ void testFullTextSearchWithSortByDateFieldDesc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(3); - assertThat(result.getContent()).containsExactly(permit3,permit2,permit1); + assertThat(result.getContent()).containsExactly(permit3, permit2, permit1); } /** @@ -338,7 +342,7 @@ void testFullTextSearchWithSortByDateFieldAsc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(3); - assertThat(result.getContent()).containsExactly(permit1,permit2,permit3); + assertThat(result.getContent()).containsExactly(permit1, permit2, permit3); } /** @@ -352,7 +356,7 @@ void testFullTextSearchWithSortByNestedTextTagFieldDesc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(3); - assertThat(result.getContent()).containsExactly(permit2,permit1,permit3); + assertThat(result.getContent()).containsExactly(permit2, permit1, permit3); } /** @@ -366,41 +370,39 @@ void testFullTextSearchWithSortByNestedTextTagAsc() { assertThat(result.getTotalPages()).isEqualTo(1); assertThat(result.getTotalElements()).isEqualTo(3); - assertThat(result.getContent()).containsExactly(permit3,permit1,permit2); + assertThat(result.getContent()).containsExactly(permit3, permit1, permit2); } @Test void testListInsideAListTagSearch() { - List withYarborough = es.of(Complex.class) - .filter(Complex$.MY_LIST.INNER_LIST.in("Yarborough")) - .collect(Collectors.toList()); + List withYarborough = es.of(Complex.class).filter(Complex$.MY_LIST.INNER_LIST.in("Yarborough")) + .collect(Collectors.toList()); assertAll( // - () -> assertThat(withYarborough.size()).isEqualTo(2), // - () -> assertThat(withYarborough).extracting("id").containsExactlyInAnyOrder("complex1", "complex3") // + () -> assertThat(withYarborough.size()).isEqualTo(2), // + () -> assertThat(withYarborough).extracting("id").containsExactlyInAnyOrder("complex1", "complex3") // ); - List withComeuppance = es.of(Complex.class) - .filter(Complex$.MY_LIST.INNER_LIST.in("Comeuppance")) - .collect(Collectors.toList()); + List withComeuppance = es.of(Complex.class).filter(Complex$.MY_LIST.INNER_LIST.in("Comeuppance")) + .collect(Collectors.toList()); assertAll( // - () -> assertThat(withComeuppance.size()).isEqualTo(2), // - () -> assertThat(withComeuppance).extracting("id").containsExactlyInAnyOrder("complex1", "complex2") // + () -> assertThat(withComeuppance.size()).isEqualTo(2), // + () -> assertThat(withComeuppance).extracting("id").containsExactlyInAnyOrder("complex1", "complex2") // ); - List withTaradiddle = es.of(Complex.class) - .filter(Complex$.MY_LIST.INNER_LIST.in("Taradiddle")) - .collect(Collectors.toList()); + List withTaradiddle = es.of(Complex.class).filter(Complex$.MY_LIST.INNER_LIST.in("Taradiddle")) + .collect(Collectors.toList()); assertAll( // - () -> assertThat(withTaradiddle.size()).isEqualTo(2), // - () -> assertThat(withTaradiddle).extracting("id").containsExactlyInAnyOrder("complex2", "complex3") // + () -> assertThat(withTaradiddle.size()).isEqualTo(2), // + () -> assertThat(withTaradiddle).extracting("id").containsExactlyInAnyOrder("complex2", "complex3") // ); } // UUID Tests - @Test void testFindByNestedListOfUUIDsValuesIn() { + @Test + void testFindByNestedListOfUUIDsValuesIn() { SearchStream stream1 = es.of(WithNestedListOfUUIDs.class); List results1 = stream1 // @@ -426,7 +428,8 @@ void testListInsideAListTagSearch() { assertThat(ids3).contains("withNestedListOfUUIDs1", "withNestedListOfUUIDs2"); } - @Test void testFindByNestedListOfUUIDsValuesNotEq() { + @Test + void testFindByNestedListOfUUIDsValuesNotEq() { SearchStream stream1 = es.of(WithNestedListOfUUIDs.class); List results1 = stream1 // @@ -454,7 +457,8 @@ void testListInsideAListTagSearch() { // ULIDs Tests - @Test void testFindByNestedListOfUlidsValuesIn() { + @Test + void testFindByNestedListOfUlidsValuesIn() { SearchStream stream1 = es.of(WithNestedListOfUlids.class); List results1 = stream1 // @@ -480,7 +484,8 @@ void testListInsideAListTagSearch() { assertThat(ids3).contains("withNestedListOfUlids1", "withNestedListOfUlids2"); } - @Test void testFindByNestedListOfUlidsValuesNotEq() { + @Test + void testFindByNestedListOfUlidsValuesNotEq() { SearchStream stream1 = es.of(WithNestedListOfUlids.class); List results1 = stream1 // diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentLanguageTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentLanguageTest.java index 60715b32..6af4d802 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentLanguageTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentLanguageTest.java @@ -20,31 +20,31 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings("SpellCheckingInspection") class DocumentLanguageTest extends AbstractBaseDocumentTest { - @Autowired - private Gson gson; +@SuppressWarnings("SpellCheckingInspection") +class DocumentLanguageTest extends AbstractBaseDocumentTest { private static final String QUIJOTE = // - "En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo " + // - "que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor."; + "En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo " + // + "que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor."; private static final String SOLEDAD = // - "Muchos años después, frente al pelotón de fusilamiento, el coronel Aureliano Buendía había" + // - " de recordar aquella tarde remota en que su padre lo llevó a conocer el hielo."; - + "Muchos años después, frente al pelotón de fusilamiento, el coronel Aureliano Buendía había" + // + " de recordar aquella tarde remota en que su padre lo llevó a conocer el hielo."; private static final Map MULTILINGUAL_SENTENCES = new HashMap<>(); + static { MULTILINGUAL_SENTENCES.put(SearchLanguage.GERMAN, "Das Leben ist kein Ponyhof mit deinem Doppelgänger"); MULTILINGUAL_SENTENCES.put(SearchLanguage.ENGLISH, "The rain in Spain stays mainly in the plains"); MULTILINGUAL_SENTENCES.put(SearchLanguage.CATALAN, - "RediSearch és un mòdul de Redis disponible en fonts que permet fer consultes, indexació secundària i cerca de text complet per a Redis."); + "RediSearch és un mòdul de Redis disponible en fonts que permet fer consultes, indexació secundària i cerca de text complet per a Redis."); MULTILINGUAL_SENTENCES.put(SearchLanguage.FRENCH, "Qui court deux lievres a la fois, n’en prend aucun"); MULTILINGUAL_SENTENCES.put(SearchLanguage.HINDI, "अँगरेजी अँगरेजों अँगरेज़"); } @Autowired SpanishDocRepository spanishDocRepository; - @Autowired MultiLingualDocRepository multiLingualDocRepository; + @Autowired + private Gson gson; @BeforeEach void createDocs() { @@ -55,19 +55,22 @@ void createDocs() { SpanishDoc soledad = SpanishDoc.of("Cien Años de Soledad", SOLEDAD); spanishDocRepository.saveAll(List.of(quijote, soledad)); - MULTILINGUAL_SENTENCES.forEach((language, sentence) -> multiLingualDocRepository.save(MultiLingualDoc.of(language.getValue(), sentence))); + MULTILINGUAL_SENTENCES.forEach( + (language, sentence) -> multiLingualDocRepository.save(MultiLingualDoc.of(language.getValue(), sentence))); } @Test void testLanguage() { SearchResult result = spanishDocRepository.findByBody("fusil"); assertThat(result.getTotalResults()).isEqualTo(1); - SpanishDoc doc = gson.fromJson(SafeEncoder.encode((byte[]) result.getDocuments().get(0).get("$")), SpanishDoc.class); + SpanishDoc doc = gson.fromJson(SafeEncoder.encode((byte[]) result.getDocuments().get(0).get("$")), + SpanishDoc.class); assertThat(doc.getTitle()).isEqualTo("Cien Años de Soledad"); SearchResult result2 = spanishDocRepository.findByBody("manchas"); assertThat(result2.getTotalResults()).isEqualTo(1); - SpanishDoc doc2 = gson.fromJson(SafeEncoder.encode((byte[]) result2.getDocuments().get(0).get("$")), SpanishDoc.class); + SpanishDoc doc2 = gson.fromJson(SafeEncoder.encode((byte[]) result2.getDocuments().get(0).get("$")), + SpanishDoc.class); assertThat(doc2.getTitle()).isEqualTo("Don Quijote"); } @@ -77,16 +80,16 @@ void testLanguageStemmerSearches() { SearchResult doppelEn = multiLingualDocRepository.findByBody("main plain", SearchLanguage.ENGLISH); assertAll( // - () -> assertThat(doppelGe.getTotalResults()).isEqualTo(1), // - () -> assertThat(doppelEn.getTotalResults()).isEqualTo(1), // - () -> { - MultiLingualDoc geDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) doppelGe.getDocuments().get(0).get("$")), - MultiLingualDoc.class); - assertThat(geDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.GERMAN)); - MultiLingualDoc enDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) doppelEn.getDocuments().get(0).get("$")), - MultiLingualDoc.class); - assertThat(enDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.ENGLISH)); - } // + () -> assertThat(doppelGe.getTotalResults()).isEqualTo(1), // + () -> assertThat(doppelEn.getTotalResults()).isEqualTo(1), // + () -> { + MultiLingualDoc geDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) doppelGe.getDocuments().get(0).get("$")), + MultiLingualDoc.class); + assertThat(geDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.GERMAN)); + MultiLingualDoc enDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) doppelEn.getDocuments().get(0).get("$")), + MultiLingualDoc.class); + assertThat(enDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.ENGLISH)); + } // ); } @@ -96,16 +99,16 @@ void testLanguageStemmerSearches2() { SearchResult searchCat = multiLingualDocRepository.findByBody("permet fer consultes", SearchLanguage.CATALAN); assertAll( // - () -> assertThat(searchHi.getTotalResults()).isEqualTo(1), // - () -> assertThat(searchCat.getTotalResults()).isEqualTo(1), // - () -> { - MultiLingualDoc hiDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) searchHi.getDocuments().get(0).get("$")), - MultiLingualDoc.class); - MultiLingualDoc catDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) searchCat.getDocuments().get(0).get("$")), - MultiLingualDoc.class); - assertThat(hiDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.HINDI)); - assertThat(catDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.CATALAN)); - } // + () -> assertThat(searchHi.getTotalResults()).isEqualTo(1), // + () -> assertThat(searchCat.getTotalResults()).isEqualTo(1), // + () -> { + MultiLingualDoc hiDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) searchHi.getDocuments().get(0).get("$")), + MultiLingualDoc.class); + MultiLingualDoc catDoc1 = gson.fromJson(SafeEncoder.encode((byte[]) searchCat.getDocuments().get(0).get("$")), + MultiLingualDoc.class); + assertThat(hiDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.HINDI)); + assertThat(catDoc1.getBody()).isEqualTo(MULTILINGUAL_SENTENCES.get(SearchLanguage.CATALAN)); + } // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentTTLTests.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentTTLTests.java index f204122f..4687762e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentTTLTests.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/DocumentTTLTests.java @@ -13,33 +13,33 @@ import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("SpellCheckingInspection") class DocumentTTLTests extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class DocumentTTLTests extends AbstractBaseDocumentTest { + private final CountDownLatch waiter = new CountDownLatch(1); @Autowired ExpiringPersonWithDefaultRepository withDefaultrepository; - @Autowired ExpiringPersonRepository withTTLAnnotationRepository; - @Autowired ExpiringPersonDifferentTimeUnitRepository withTTLwTimeUnitAnnotationRepository; - + @BeforeEach void cleanUp() { withDefaultrepository.deleteAll(); withTTLAnnotationRepository.deleteAll(); withTTLwTimeUnitAnnotationRepository.deleteAll(); } - + @Test void testClassLevelDefaultTTL() { ExpiringPersonWithDefault gordon = ExpiringPersonWithDefault.of("Gordon Welchman"); withDefaultrepository.save(gordon); - + Long expire = withDefaultrepository.getExpiration(gordon.getId()); - + assertThat(expire).isEqualTo(5L); } - + @Test void testTimeToLiveAnnotation() { ExpiringPerson mWoodger = ExpiringPerson.of("Mike Woodger", 15L); @@ -49,7 +49,7 @@ void testTimeToLiveAnnotation() { assertThat(expire).isEqualTo(15L); } - + @Test void testTimeToLiveAnnotationWithDifferentTimeUnit() { ExpiringPersonDifferentTimeUnit jWilkinson = ExpiringPersonDifferentTimeUnit.of("Jim Wilkinson", 7L); @@ -57,7 +57,7 @@ void testTimeToLiveAnnotationWithDifferentTimeUnit() { Long expire = withTTLwTimeUnitAnnotationRepository.getExpiration(jWilkinson.getId()); - assertThat(expire).isEqualTo(7L*24*60*60); + assertThat(expire).isEqualTo(7L * 24 * 60 * 60); } @Test @@ -102,12 +102,10 @@ void testTimeToLiveAnnotationWithDifferentTimeUnitOnSaveAll() { Long jWilkinsonExpiration = withTTLwTimeUnitAnnotationRepository.getExpiration(jWilkinson.getId()); Long sDummontExpiration = withTTLwTimeUnitAnnotationRepository.getExpiration(sDummont.getId()); - assertThat(jWilkinsonExpiration).isEqualTo(7L*24*60*60); - assertThat(sDummontExpiration).isEqualTo(7L*24*60*60); + assertThat(jWilkinsonExpiration).isEqualTo(7L * 24 * 60 * 60); + assertThat(sDummontExpiration).isEqualTo(7L * 24 * 60 * 60); } - - private final CountDownLatch waiter = new CountDownLatch(1); - + @Test void testExpiredEntitiesAreNotFound() throws InterruptedException { ExpiringPerson kZuse = ExpiringPerson.of("Konrad Zuse", 1L); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/EnumeratedTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/EnumeratedTest.java index 9520e010..7b57f222 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/EnumeratedTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/EnumeratedTest.java @@ -29,21 +29,9 @@ class EnumeratedTest extends AbstractBaseDocumentTest { @BeforeEach void loadTestData() { - var java = Developer.builder() - .id("1") - .typeOrdinal(DeveloperType.JAVA) - .state(DeveloperState.REST) - .build(); - var cpp = Developer.builder() - .id("2") - .typeOrdinal(DeveloperType.CPP) - .state(DeveloperState.WORK) - .build(); - var python = Developer.builder() - .id("3") - .typeOrdinal(DeveloperType.PYTHON) - .state(DeveloperState.WORK) - .build(); + var java = Developer.builder().id("1").typeOrdinal(DeveloperType.JAVA).state(DeveloperState.REST).build(); + var cpp = Developer.builder().id("2").typeOrdinal(DeveloperType.CPP).state(DeveloperState.WORK).build(); + var python = Developer.builder().id("3").typeOrdinal(DeveloperType.PYTHON).state(DeveloperState.WORK).build(); developerRepository.saveAll(List.of(java, cpp, python)); } @@ -54,10 +42,9 @@ void testSaveEnumAsNumber() { var search = redisModulesClient.clientForSearch(); Gson gson = new Gson(); - var data = search.ftSearch("com.redis.om.spring.annotations.document.fixtures.DeveloperIdx") - .getDocuments().stream() - .map(el -> gson.fromJson((String) el.get("$"), DeveloperNative.class)) - .collect(Collectors.toMap(DeveloperNative::getId, Function.identity())); + var data = search.ftSearch("com.redis.om.spring.annotations.document.fixtures.DeveloperIdx").getDocuments().stream() + .map(el -> gson.fromJson((String) el.get("$"), DeveloperNative.class)) + .collect(Collectors.toMap(DeveloperNative::getId, Function.identity())); assertThat(data.get("1").getOrdinal()).isEqualTo(DeveloperType.JAVA.ordinal()); assertThat(data.get("2").getOrdinal()).isEqualTo(DeveloperType.CPP.ordinal()); @@ -82,5 +69,4 @@ private static class DeveloperNative { private String state; } - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitPrefixesDocumentTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitPrefixesDocumentTest.java index 8be1a7b0..3c1584e4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitPrefixesDocumentTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitPrefixesDocumentTest.java @@ -68,7 +68,8 @@ void testKeyGenerationWithCustomPrefixWithColon() { } } - @Test void testFindByIdForCustomPrefixWithColon() { + @Test + void testFindByIdForCustomPrefixWithColon() { Optional maybePanama = docWithColonInPrefixRepository.findById("Panama"); assertThat(maybePanama).isPresent(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitelyIndexedIdFieldsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitelyIndexedIdFieldsTest.java index a93ffb2f..ed6c4b85 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitelyIndexedIdFieldsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ExplicitelyIndexedIdFieldsTest.java @@ -26,32 +26,37 @@ class ExplicitelyIndexedIdFieldsTest extends AbstractBaseDocumentTest { @BeforeEach void cleanUp() { - docWithIndexedIdRepository.saveAll(List.of(DocWithIndexedId.of("DWII01", "DWII01"), DocWithIndexedId.of("DWII02", "DWII02"))); - docWithSearchableIdRepository.saveAll(List.of(DocWithSearchableId.of("DWSI01", "DWSI01"), DocWithSearchableId.of("DWSI02", "DWSI02"))); - docWithTagIndexedIdRepository.saveAll(List.of(DocWithTagIndexedId.of("DWTII01", "DWTII01"), DocWithTagIndexedId.of("DWTII02", "DWTII02"))); + docWithIndexedIdRepository.saveAll( + List.of(DocWithIndexedId.of("DWII01", "DWII01"), DocWithIndexedId.of("DWII02", "DWII02"))); + docWithSearchableIdRepository.saveAll( + List.of(DocWithSearchableId.of("DWSI01", "DWSI01"), DocWithSearchableId.of("DWSI02", "DWSI02"))); + docWithTagIndexedIdRepository.saveAll( + List.of(DocWithTagIndexedId.of("DWTII01", "DWTII01"), DocWithTagIndexedId.of("DWTII02", "DWTII02"))); } - @Test void testFindById() { + @Test + void testFindById() { Optional maybeDWII01 = docWithIndexedIdRepository.findById("DWII01"); Optional maybeDWSI01 = docWithSearchableIdRepository.findById("DWSI01"); Optional maybeDWTII01 = docWithTagIndexedIdRepository.findById("DWTII01"); assertAll( // - () -> assertThat(maybeDWII01).isPresent(), // - () -> assertThat(maybeDWSI01).isPresent(), // - () -> assertThat(maybeDWTII01).isPresent() // + () -> assertThat(maybeDWII01).isPresent(), // + () -> assertThat(maybeDWSI01).isPresent(), // + () -> assertThat(maybeDWTII01).isPresent() // ); } - @Test void testFindAll() { + @Test + void testFindAll() { var allDWII = docWithIndexedIdRepository.findAll(); var allDWSI = docWithSearchableIdRepository.findAll(); var allDWTII = docWithTagIndexedIdRepository.findAll(); assertAll( // - () -> assertThat(allDWII).hasSize(2), // - () -> assertThat(allDWSI).hasSize(2), // - () -> assertThat(allDWTII).hasSize(2) // + () -> assertThat(allDWII).hasSize(2), // + () -> assertThat(allDWSI).hasSize(2), // + () -> assertThat(allDWTII).hasSize(2) // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IdTests.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IdTests.java index ee86437a..79664584 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IdTests.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IdTests.java @@ -41,7 +41,6 @@ void cleanUp() { movieRepository.saveAll(Set.of(movie1, movie2, movie3)); } - @Test void testLongPrimivitiveIdIndexGeneration() { SearchStream stream = entityStream.of(Movie.class); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IndexFilterTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IndexFilterTest.java index 2579cd89..f12f4ad4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IndexFilterTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/IndexFilterTest.java @@ -45,7 +45,6 @@ void testFindAllShouldReturnOnlyCoupes() { assertAll( // () -> assertThat(vehicles.size()).isEqualTo(3), // () -> assertThat(vehicles).extracting("model").containsExactlyInAnyOrder("Beetle", "911 S 2.4", "Thunderbird"), // - () -> assertThat(vehicles).allMatch(v -> v.getVehicleType().equals(VehicleType.COUPE)) - ); + () -> assertThat(vehicles).allMatch(v -> v.getVehicleType().equals(VehicleType.COUPE))); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/NonStandardDocumentSearchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/NonStandardDocumentSearchTest.java index 188720ec..51abd280 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/NonStandardDocumentSearchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/NonStandardDocumentSearchTest.java @@ -16,13 +16,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class NonStandardDocumentSearchTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class NonStandardDocumentSearchTest extends AbstractBaseDocumentTest { @Autowired CustomRepository repository; - @Autowired CompanyWithLongIdRepository companyRepo; + @Autowired + CompanyWithLongIdRepository companyRepo; - @Autowired StringRedisTemplate template; + @Autowired + StringRedisTemplate template; private long id1; private long id2; @@ -30,7 +33,8 @@ @BeforeEach void loadTestData() { Custom c1 = Custom.of("foofoo"); - var nl1 = NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", NestLevel2.of("nl-2-1", "Here's looking at you, kid.")); + var nl1 = NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", + NestLevel2.of("nl-2-1", "Here's looking at you, kid.")); c1.setNest_level1(nl1); Custom c2 = Custom.of("barbar"); Custom c3 = Custom.of("bazbaz"); @@ -83,7 +87,7 @@ void testDeleteAll() { repository.deleteAll(); assertThat(repository.count()).isZero(); } - + @Test void testUpdateSingleField() { Optional maybeC1 = repository.findById(id1); @@ -93,7 +97,7 @@ void testUpdateSingleField() { Optional maybeC1After = repository.findById(id1); assertAll( // - () -> assertTrue(maybeC1After.isPresent()), () -> assertEquals("fufoo", maybeC1After.get().getName()) // + () -> assertTrue(maybeC1After.isPresent()), () -> assertEquals("fufoo", maybeC1After.get().getName()) // ); } @@ -106,19 +110,19 @@ void testUpdateDeepNestedNonJavaCompliantNamedField() { Optional dn1After = repository.findById(id1); assertAll( // - () -> assertThat(dn1.get().getName()).isNotEqualTo("dos-uno"), // - () -> assertTrue(dn1After.isPresent()), // - () -> assertEquals("dos-uno", dn1After.get().getNest_level1().getNestLevel2().getName()) // + () -> assertThat(dn1.get().getName()).isNotEqualTo("dos-uno"), // + () -> assertTrue(dn1After.isPresent()), // + () -> assertEquals("dos-uno", dn1After.get().getNest_level1().getNestLevel2().getName()) // ); } @Test void testSaveAllWithNonStringKey() { - CompanyWithLongId redis = CompanyWithLongId.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + CompanyWithLongId redis = CompanyWithLongId.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), + new Point(-122.066540, 37.377690), "stack@redis.com"); CompanyWithLongId microsoft = CompanyWithLongId.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + new Point(-122.124500, 47.640160), "research@microsoft.com"); companyRepo.saveAll(List.of(redis, microsoft)); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/OptimisticLockingTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/OptimisticLockingTest.java index 2338cc65..463ccd0a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/OptimisticLockingTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/OptimisticLockingTest.java @@ -66,7 +66,7 @@ void updateForOutdatedEntityShouldFail() { repository.save(versionedEntity); assertThatThrownBy(() -> repository.save(new VersionedEntity(42, 5, "f"))).isInstanceOf( - OptimisticLockingFailureException.class); + OptimisticLockingFailureException.class); } @Test @@ -88,7 +88,7 @@ void deleteForOutdatedEntityShouldFail() { repository.save(new VersionedEntity(45)); assertThatThrownBy(() -> repository.delete(new VersionedEntity(45))).isInstanceOf( - OptimisticLockingFailureException.class); + OptimisticLockingFailureException.class); Optional maybeLoaded = repository.findById(45L); assertThat(maybeLoaded).isPresent(); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentCustomFallbackKeySpaceTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentCustomFallbackKeySpaceTest.java index 9698dab5..6cedaa47 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentCustomFallbackKeySpaceTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentCustomFallbackKeySpaceTest.java @@ -35,33 +35,17 @@ @Testcontainers @DirtiesContext @SpringBootTest( // - classes = RedisDocumentCustomFallbackKeySpaceTest.Config.class, // - properties = { "spring.main.allow-bean-definition-overriding=true" } // -) class RedisDocumentCustomFallbackKeySpaceTest extends AbstractBaseOMTest { - - @SpringBootApplication - @Configuration - @EnableRedisDocumentRepositories(basePackages = "com.redis.om.spring.annotations.document.fixtures") - static class Config extends TestConfig { - @Bean - @Primary - public RedisMappingContext keyValueMappingContext() { - RedisMappingContext mappingContext = new RedisMappingContext(); - mappingContext.setKeySpaceResolver(type -> "CUSTOM_KEYSPACE" + ":" + type.getSimpleName()); - return mappingContext; - } - } - + classes = RedisDocumentCustomFallbackKeySpaceTest.Config.class, // + properties = { "spring.main.allow-bean-definition-overriding=true" } // + ) +class RedisDocumentCustomFallbackKeySpaceTest extends AbstractBaseOMTest { @Autowired MyDocRepository myDocRepository; - @Autowired RedisTemplate template; - @Autowired RedisModulesOperations modulesOperations; - String myDoc1Id; @BeforeEach @@ -86,17 +70,18 @@ void cleanUp() { @Test void testSearchIndex() { - SearchOperations searchOps = modulesOperations.opsForSearch("com.redis.om.spring.annotations.document.fixtures.MyDocIdx"); + SearchOperations searchOps = modulesOperations.opsForSearch( + "com.redis.om.spring.annotations.document.fixtures.MyDocIdx"); var info = searchOps.getInfo(); var definition = info.get("index_definition"); assertInstanceOf(List.class, definition); - var prefixes = ((List)definition).get(((List)definition).indexOf("prefixes") + 1); + var prefixes = ((List) definition).get(((List) definition).indexOf("prefixes") + 1); assertNotNull(prefixes); assertInstanceOf(List.class, prefixes); - assertEquals("CUSTOM_KEYSPACE:MyDoc:", ((List)prefixes).get(0)); + assertEquals("CUSTOM_KEYSPACE:MyDoc:", ((List) prefixes).get(0)); } @Test @@ -137,4 +122,17 @@ void testBasicCrudOperations() { assertFalse(maybeDoc1.isPresent()); } + + @SpringBootApplication + @Configuration + @EnableRedisDocumentRepositories(basePackages = "com.redis.om.spring.annotations.document.fixtures") + static class Config extends TestConfig { + @Bean + @Primary + public RedisMappingContext keyValueMappingContext() { + RedisMappingContext mappingContext = new RedisMappingContext(); + mappingContext.setKeySpaceResolver(type -> "CUSTOM_KEYSPACE" + ":" + type.getSimpleName()); + return mappingContext; + } + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentQueryByExampleTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentQueryByExampleTest.java index 699271c9..e061cd43 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentQueryByExampleTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentQueryByExampleTest.java @@ -61,12 +61,12 @@ void loadTestData() { companyRepository.deleteAll(); Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setTags(Set.of("RedisTag", "CommonTag")); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); - Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com"); + Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com"); microsoft.setTags(Set.of("MsTag", "CommonTag")); microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag", "CommonTag")))); @@ -180,9 +180,8 @@ void testFindAllByExampleByIdWithExampleMatcher() { @Test void testFindAllByWithPageableAndSortAsc() { - Pageable pageRequest = PageRequest.of(0, 2, - Sort.by("title").ascending()); - Page content = repository.findAll(pageRequest); + Pageable pageRequest = PageRequest.of(0, 2, Sort.by("title").ascending()); + Page content = repository.findAll(pageRequest); assertThat(content.getSize()).isEqualTo(2); assertThat(content.getContent().get(0).getTitle()).isEqualTo("bonjour le monde"); @@ -190,9 +189,8 @@ void testFindAllByWithPageableAndSortAsc() { @Test void testFindAllByWithPageableAndSortDec() { - Pageable pageRequest = PageRequest.of(0, 2, - Sort.by("title").descending()); - Page content = repository.findAll(pageRequest); + Pageable pageRequest = PageRequest.of(0, 2, Sort.by("title").descending()); + Page content = repository.findAll(pageRequest); assertThat(content.getSize()).isEqualTo(2); assertThat(content.getContent().get(0).getTitle()).isEqualTo("ola mundo"); @@ -262,8 +260,7 @@ void testFindAllByExampleWithTextPropertyStartingWith() { MyDoc template = new MyDoc(); template.setTitle("hello"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.STARTING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.STARTING); Example example = Example.of(template, matcher); @@ -277,8 +274,7 @@ void testFindAllByExampleWithTextPropertyEndingWith() { MyDoc template = new MyDoc(); template.setTitle("ndo"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.ENDING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.ENDING); Example example = Example.of(template, matcher); @@ -292,8 +288,7 @@ void testFindAllByExampleWithTextPropertyContaining() { MyDoc template = new MyDoc(); template.setTitle("llo"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.CONTAINING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING); Example example = Example.of(template, matcher); @@ -335,8 +330,8 @@ void testFindAllByExampleWithStringValueExampleInNestedField() { Iterable shouldBeOnlyMS = companyRepository.findAll(msExample); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @@ -360,8 +355,8 @@ void testFindAllByExampleWithNumericValueExampleInNestedField() { Iterable shouldBeOnlyMS = companyRepository.findAll(msExample); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") // ); } @@ -384,10 +379,9 @@ void testFindAllByExampleWithTags() { Iterable shouldBeBoth = companyRepository.findAll(bothExample); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // - () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", - "Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // + () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", "Microsoft") // ); } @@ -416,10 +410,9 @@ void testFindAllByExampleWithTagsInNestedField() { Iterable shouldBeBoth = companyRepository.findAll(bothExample); assertAll( // - () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // - () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // - () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", - "Microsoft") // + () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), // + () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), // + () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", "Microsoft") // ); } @@ -428,8 +421,7 @@ void testFindByShouldReturnFirstResult() { MyDoc template = new MyDoc(); template.setTitle("llo"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.CONTAINING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING); Example example = Example.of(template, matcher); @@ -449,19 +441,17 @@ void testFindByShouldReturnOneResult() { MyDoc moreThanOneMatchTemplate = new MyDoc(); moreThanOneMatchTemplate.setTitle("llo"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.CONTAINING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING); assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy( - () -> repository.findBy(Example.of(moreThanOneMatchTemplate, matcher), FluentQuery.FetchableFluentQuery::one)); + () -> repository.findBy(Example.of(moreThanOneMatchTemplate, matcher), FluentQuery.FetchableFluentQuery::one)); } @Test void testFindByShouldReturnAll() { MyDoc template = new MyDoc(); template.setTitle("llo"); - ExampleMatcher matcher = ExampleMatcher.matching() - .withStringMatcher(StringMatcher.CONTAINING); + ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING); List result = repository.findBy(Example.of(template, matcher), FluentQuery.FetchableFluentQuery::all); @@ -473,15 +463,15 @@ void testFindByShouldApplySortAll() { Company probe = new Company(); List result = companyRepository.findBy( // - Example.of(probe), // - it -> it.sortBy(Sort.by("name")).all() // + Example.of(probe), // + it -> it.sortBy(Sort.by("name")).all() // ); assertThat(result).map(Company::getName).containsExactly("Microsoft", "RedisInc"); result = companyRepository.findBy( // - Example.of(probe), // - it -> it.sortBy(Sort.by(Sort.Direction.DESC, "name")).all() // + Example.of(probe), // + it -> it.sortBy(Sort.by(Sort.Direction.DESC, "name")).all() // ); assertThat(result).map(Company::getName).containsExactly("RedisInc", "Microsoft"); } @@ -492,13 +482,14 @@ void findByShouldApplyPagination() { template.setLocation(new Point(-122.066540, 37.377690)); Page firstPage = repository.findBy(Example.of(template), - it -> it.page(PageRequest.of(0, 2, Sort.by("name")))); + it -> it.page(PageRequest.of(0, 2, Sort.by("name")))); assertThat(firstPage.getTotalElements()).isEqualTo(3); assertThat(firstPage.getContent().size()).isEqualTo(2); - assertThat(firstPage.getContent().stream().toList()).map(MyDoc::getTitle).containsExactly("hello mundo", "ola mundo"); + assertThat(firstPage.getContent().stream().toList()).map(MyDoc::getTitle) + .containsExactly("hello mundo", "ola mundo"); Page secondPage = repository.findBy(Example.of(template), - it -> it.page(PageRequest.of(1, 2, Sort.by("name")))); + it -> it.page(PageRequest.of(1, 2, Sort.by("name")))); assertThat(secondPage.getTotalElements()).isEqualTo(3); assertThat(secondPage.getContent().size()).isEqualTo(1); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentSearchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentSearchTest.java index 0cad11ca..93bd3f4d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentSearchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentSearchTest.java @@ -27,14 +27,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class RedisDocumentSearchTest extends AbstractBaseDocumentTest { - @Autowired - MyDocRepository repository; - - @Autowired StringRedisTemplate template; - +@SuppressWarnings("SpellCheckingInspection") +class RedisDocumentSearchTest extends AbstractBaseDocumentTest { private static String id1; private static String id2; + @Autowired + MyDocRepository repository; + @Autowired + StringRedisTemplate template; @BeforeEach void loadTestData() { @@ -90,10 +90,9 @@ void testQueryAnnotation01() { SearchResult result = repository.getFirstTag(); assertAll( // - () -> assertThat(result.getTotalResults()).isEqualTo(2), - () -> assertThat(result.getDocuments().get(0).getScore()).isEqualTo(1.0), - () -> assertThat(result.getDocuments().get(0).getString("first_tag")).isIn("news", "article") - ); + () -> assertThat(result.getTotalResults()).isEqualTo(2), + () -> assertThat(result.getDocuments().get(0).getScore()).isEqualTo(1.0), + () -> assertThat(result.getDocuments().get(0).getString("first_tag")).isIn("news", "article")); } /** @@ -112,9 +111,7 @@ void testQueryAnnotation02() { assertEquals(1, ((Collection) results).size()); MyDoc doc = results.iterator().next(); assertAll( // - () -> assertThat(doc.getTitle()).isEqualTo("hello world"), - () -> assertThat(doc.getTag()).contains("news") - ); + () -> assertThat(doc.getTitle()).isEqualTo("hello world"), () -> assertThat(doc.getTag()).contains("news")); } /** @@ -134,9 +131,7 @@ void testAggregationAnnotation01() { Row row = result.getRow(0); assertAll( // - () -> assertThat(row).isNotNull(), - () -> assertThat(row.getString("tag2")).isIn("news", "article") - ); + () -> assertThat(row).isNotNull(), () -> assertThat(row.getString("tag2")).isIn("news", "article")); } @Test @@ -146,11 +141,9 @@ void testBasicPagination() { Page result = repository.findAllByTitleStartingWith("hel", pageRequest); assertAll( // - () -> assertEquals(2, result.getTotalPages()), - () -> assertEquals(2, result.getTotalElements()), - () -> assertEquals(1, result.getContent().size()), - () -> assertEquals("hello world", result.getContent().get(0).getTitle()) - ); + () -> assertEquals(2, result.getTotalPages()), () -> assertEquals(2, result.getTotalElements()), + () -> assertEquals(1, result.getContent().size()), + () -> assertEquals("hello world", result.getContent().get(0).getTitle())); } @Test @@ -248,8 +241,8 @@ void testFindByFieldWithExplicitGeoIndexedAnnotation() { MyDoc doc = iter.next(); assertEquals("hello mundo", doc.getTitle()); - @SuppressWarnings("unused") - NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, iter::next); + @SuppressWarnings("unused") NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, + iter::next); } @Test @@ -261,8 +254,8 @@ void testFindByFieldWithIndexedGeoAnnotation() { MyDoc doc = iter.next(); assertEquals("hello mundo", doc.getTitle()); - @SuppressWarnings("unused") - NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, iter::next); + @SuppressWarnings("unused") NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, + iter::next); } @Test @@ -291,71 +284,71 @@ void testDeleteByIdWithPath() { @Test void testQueryAnnotationWithReturnFieldsAndLimitAndOffset() { Point point = new Point(-122.066540, 37.377690); - repository.saveAll(List.of( - MyDoc.of("predisposition", point, point, 4), // - MyDoc.of("predestination", point, point, 8), // - MyDoc.of("prepublication", point, point, 15), // - MyDoc.of("predestinarian", point, point, 16), // - MyDoc.of("preadolescence", point, point, 23), // - MyDoc.of("premillenarian", point, point, 42), // - MyDoc.of("precipitinogen", point, point, 4), // - MyDoc.of("precipitations", point, point, 8), // - MyDoc.of("precociousness", point, point, 15), // - MyDoc.of("precombustions", point, point, 16), // - MyDoc.of("preconditioned", point, point, 23), // - MyDoc.of("preconceptions", point, point, 42), // - MyDoc.of("precipitancies", point, point, 4), // - MyDoc.of("preciousnesses", point, point, 8), // - MyDoc.of("precentorships", point, point, 15), // - MyDoc.of("preceptorships", point, point, 16) // + repository.saveAll(List.of(MyDoc.of("predisposition", point, point, 4), // + MyDoc.of("predestination", point, point, 8), // + MyDoc.of("prepublication", point, point, 15), // + MyDoc.of("predestinarian", point, point, 16), // + MyDoc.of("preadolescence", point, point, 23), // + MyDoc.of("premillenarian", point, point, 42), // + MyDoc.of("precipitinogen", point, point, 4), // + MyDoc.of("precipitations", point, point, 8), // + MyDoc.of("precociousness", point, point, 15), // + MyDoc.of("precombustions", point, point, 16), // + MyDoc.of("preconditioned", point, point, 23), // + MyDoc.of("preconceptions", point, point, 42), // + MyDoc.of("precipitancies", point, point, 4), // + MyDoc.of("preciousnesses", point, point, 8), // + MyDoc.of("precentorships", point, point, 15), // + MyDoc.of("preceptorships", point, point, 16) // )); SearchResult result = repository.customFindAllByTitleStartingWithReturnFieldsAndLimit("pre"); assertEquals(16, result.getTotalResults()); assertThat(result.getTotalResults()).isEqualTo(16); - List titles = result.getDocuments().stream().map(d -> SafeEncoder.encode((byte[])d.get("title"))).map(Object::toString).toList(); + List titles = result.getDocuments().stream().map(d -> SafeEncoder.encode((byte[]) d.get("title"))) + .map(Object::toString).toList(); assertThat(titles).containsExactly("precentorships", "preceptorships", "preciousnesses", "precipitancies", - "precipitations", "precipitinogen", "precociousness", "precombustions", "preconceptions", "preconditioned", - "predestinarian", "predestination"); + "precipitations", "precipitinogen", "precociousness", "precombustions", "preconceptions", "preconditioned", + "predestinarian", "predestination"); } @Test void testEndingWithSearches() { Point point = new Point(-122.066540, 37.377690); - repository.saveAll(List.of( - MyDoc.of("predisposition", point, point, 4), // - MyDoc.of("predisposition", point, point, 8), // - MyDoc.of("prepublication", point, point, 15), // - MyDoc.of("predestinarian", point, point, 16), // - MyDoc.of("preadolescence", point, point, 23), // - MyDoc.of("premillenarian", point, point, 42), // - MyDoc.of("precipitinogen", point, point, 4), // - MyDoc.of("precipitations", point, point, 8), // - MyDoc.of("precociousness", point, point, 15), // - MyDoc.of("precombustions", point, point, 16), // - MyDoc.of("preconditioned", point, point, 23), // - MyDoc.of("preconceptions", point, point, 42), // - MyDoc.of("precipitancies", point, point, 4), // - MyDoc.of("preciousnesses", point, point, 8), // - MyDoc.of("precentorships", point, point, 15), // - MyDoc.of("preceptorships", point, point, 16) // + repository.saveAll(List.of(MyDoc.of("predisposition", point, point, 4), // + MyDoc.of("predisposition", point, point, 8), // + MyDoc.of("prepublication", point, point, 15), // + MyDoc.of("predestinarian", point, point, 16), // + MyDoc.of("preadolescence", point, point, 23), // + MyDoc.of("premillenarian", point, point, 42), // + MyDoc.of("precipitinogen", point, point, 4), // + MyDoc.of("precipitations", point, point, 8), // + MyDoc.of("precociousness", point, point, 15), // + MyDoc.of("precombustions", point, point, 16), // + MyDoc.of("preconditioned", point, point, 23), // + MyDoc.of("preconceptions", point, point, 42), // + MyDoc.of("precipitancies", point, point, 4), // + MyDoc.of("preciousnesses", point, point, 8), // + MyDoc.of("precentorships", point, point, 15), // + MyDoc.of("preceptorships", point, point, 16) // )); List endsWithTion = repository.findAllByTitleEndingWith("tion"); List endsWithTions = repository.findAllByTitleEndingWith("tions"); assertAll( // - () -> assertThat(endsWithTion).extracting("title").containsExactlyInAnyOrder("predisposition", "predisposition", "prepublication"), - () -> assertThat(endsWithTions).extracting("title").containsExactlyInAnyOrder("precipitations", "precombustions", "preconceptions") - ); + () -> assertThat(endsWithTion).extracting("title") + .containsExactlyInAnyOrder("predisposition", "predisposition", "prepublication"), + () -> assertThat(endsWithTions).extracting("title") + .containsExactlyInAnyOrder("precipitations", "precombustions", "preconceptions")); } @Test void testQueryDoubleConditionWhileOneParam() { Point point1 = new Point(-12.100, 4.640); - MyDoc doc1 = MyDoc.of( id1, point1, point1, 1); + MyDoc doc1 = MyDoc.of(id1, point1, point1, 1); repository.save(doc1); List result = repository.searchByIdOrTitle(id1); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentWithAliasTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentWithAliasTest.java index a7e90bbd..c64acd47 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentWithAliasTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RedisDocumentWithAliasTest.java @@ -24,17 +24,16 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("SpellCheckingInspection") class RedisDocumentWithAliasTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class RedisDocumentWithAliasTest extends AbstractBaseDocumentTest { @Autowired WithAliasRepository repository; @Autowired RedisModulesOperations modulesOperations; - - private String id1; - @Autowired EntityStream entityStream; + private String id1; @BeforeEach void loadTestData() { @@ -79,26 +78,23 @@ void testBasicCrudOperations() { void testGetByAliasedProperty() { SearchStream stream = entityStream.of(WithAlias.class); List docs = stream // - .filter(WithAlias$.TEXT.eq("Epa chamo")) // - .collect(Collectors.toList()); + .filter(WithAlias$.TEXT.eq("Epa chamo")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(docs).hasSize(1), - () -> assertThat(docs).extracting("text").containsOnly("Epa chamo") - ); + () -> assertThat(docs).hasSize(1), () -> assertThat(docs).extracting("text").containsOnly("Epa chamo")); } @Test void testGetByTagAliasedProperty() { SearchStream stream = entityStream.of(WithAlias.class); List docs = stream // - .filter(WithAlias$.TAGS.in("articulo", "article")) // - .collect(Collectors.toList()); + .filter(WithAlias$.TAGS.in("articulo", "article")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(docs).hasSize(2), - () -> assertThat(docs).extracting("text").containsOnly("Epa chamo", "Oye man") - ); + () -> assertThat(docs).hasSize(2), + () -> assertThat(docs).extracting("text").containsOnly("Epa chamo", "Oye man")); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ReferenceTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ReferenceTest.java index 4f48225b..c846584a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ReferenceTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/ReferenceTest.java @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; -@TestPropertySource(properties = {"spring.config.location=classpath:application.yaml"}) +@TestPropertySource(properties = { "spring.config.location=classpath:application.yaml" }) class ReferenceTest extends AbstractBaseDocumentTest { @Autowired CityRepository cityRepository; @@ -56,15 +56,15 @@ void prepare() { statesRepository.save(States.of("East Of Mississippi", Set.of(oh, ga))); var cities = Set.of( // - City.of("San Francisco", ca), City.of("San Jose", ca), // - City.of("Los Angeles", ca), City.of("Scottsdale", az), // - City.of("Phoenix", az), City.of("Flagstaff", az), // - City.of("Columbus", oh), City.of("Cleveland", oh), // - City.of("Cincinnati", oh), City.of("Houston", tx), // - City.of("Dallas", tx), City.of("Austin", tx), // - City.of("Seattle", wa), City.of("Spokane", wa), // - City.of("Tacoma", wa), City.of("Atlanta", ga), // - City.of("Savannah", ga), City.of("Augusta", ga) // + City.of("San Francisco", ca), City.of("San Jose", ca), // + City.of("Los Angeles", ca), City.of("Scottsdale", az), // + City.of("Phoenix", az), City.of("Flagstaff", az), // + City.of("Columbus", oh), City.of("Cleveland", oh), // + City.of("Cincinnati", oh), City.of("Houston", tx), // + City.of("Dallas", tx), City.of("Austin", tx), // + City.of("Seattle", wa), City.of("Spokane", wa), // + City.of("Tacoma", wa), City.of("Atlanta", ga), // + City.of("Savannah", ga), City.of("Augusta", ga) // ); cityRepository.saveAll(cities); @@ -115,9 +115,9 @@ void testMultilevelReferences() { @Test void testMultilevelReferencesWithEntityStreams() { List cities = entityStream // - .of(City.class) // - .filter(City$.ID.eq("Scottsdale")) // - .collect(Collectors.toList()); + .of(City.class) // + .filter(City$.ID.eq("Scottsdale")) // + .collect(Collectors.toList()); assertThat(cities).hasSize(1); @@ -140,16 +140,15 @@ void testReferencedClassCanBeDeserializedWithFullPayload() { @Test void testReferencedClassCanBeDeserializedWithFullPayloadWithEntityStreams() { List countries = entityStream // - .of(Country.class) // - .filter(Country$.ID.eq("USA")) // - .collect(Collectors.toList()); + .of(Country.class) // + .filter(Country$.ID.eq("USA")) // + .collect(Collectors.toList()); assertThat(countries).hasSize(1); Country usa = countries.get(0); assertThat(usa.getId()).isEqualTo("USA"); } - @Test void testReferencedClassWithReferencesCanBeDeserializedWithFullPayload() { var maybeArizona = stateRepository.findById("AZ"); @@ -161,9 +160,9 @@ void testReferencedClassWithReferencesCanBeDeserializedWithFullPayload() { @Test void testReferencedClassWithReferencesCanBeDeserializedWithFullPayloadWithEntityStreams() { List states = entityStream // - .of(State.class) // - .filter(State$.ID.eq("AZ")) // - .collect(Collectors.toList()); + .of(State.class) // + .filter(State$.ID.eq("AZ")) // + .collect(Collectors.toList()); assertThat(states).hasSize(1); State arizona = states.get(0); @@ -202,9 +201,9 @@ void testReferenceCollectionDeserializationWithEntityStreams() { var ga = maybeGa.get(); List states = entityStream // - .of(States.class) // - .filter(States$.ID.eq("East\\ Of\\ Mississippi")) // - .collect(Collectors.toList()); + .of(States.class) // + .filter(States$.ID.eq("East\\ Of\\ Mississippi")) // + .collect(Collectors.toList()); assertThat(states).hasSize(1); States eom = states.get(0); @@ -231,9 +230,9 @@ void testFindEntitiesByReferenceEq() { var cincinnati = maybeCincinnati.get(); List ohioCities = entityStream // - .of(City.class) // - .filter(City$.STATE.eq(oh)) // - .collect(Collectors.toList()); + .of(City.class) // + .filter(City$.STATE.eq(oh)) // + .collect(Collectors.toList()); assertThat(ohioCities).hasSize(3); assertThat(ohioCities).containsExactlyInAnyOrder(cincinnati, cleveland, columbus); @@ -256,9 +255,9 @@ void testFindEntitiesByReferenceNotEq() { var cincinnati = maybeCincinnati.get(); List ohioCities = entityStream // - .of(City.class) // - .filter(City$.STATE.notEq(oh)) // - .collect(Collectors.toList()); + .of(City.class) // + .filter(City$.STATE.notEq(oh)) // + .collect(Collectors.toList()); assertThat(ohioCities).hasSize(15); assertThat(ohioCities).doesNotContain(cincinnati, cleveland, columbus); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RepositoryIssuesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RepositoryIssuesTest.java index 71b65b9f..a41d0e4c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RepositoryIssuesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/RepositoryIssuesTest.java @@ -33,16 +33,14 @@ void cleanUp() { skuCacheRepository.deleteAll(); List skuCaches = new ArrayList<>(); for (int i = 0; i < 10; i++) { - skuCaches.add( - new SKU((long) i, "A" + i + i + i + i + i, "SKU " + i)); + skuCaches.add(new SKU((long) i, "A" + i + i + i + i + i, "SKU " + i)); } skuCacheRepository.saveAll(skuCaches); studentRepository.deleteAll(); List students = new ArrayList<>(); for (int i = 0; i < 10; i++) { - students.add( - Student.of((long) i, "Student" + i, LocalDateTime.now())); + students.add(Student.of((long) i, "Student" + i, LocalDateTime.now())); } studentRepository.saveAll(students); } @@ -60,18 +58,18 @@ void testFindAllByText() { List result = skuCacheRepository.findAllBySkuNameIn(Set.of("SKU 1", "SKU 2")); assertAll( // - () -> assertThat(result).hasSize(2), - () -> assertThat(result).extracting("skuName").containsExactlyInAnyOrder("SKU 1", "SKU 2") // + () -> assertThat(result).hasSize(2), + () -> assertThat(result).extracting("skuName").containsExactlyInAnyOrder("SKU 1", "SKU 2") // ); } @Test void testFindAllByTag() { - List result = skuCacheRepository.findAllBySkuNumberIn(Set.of("A11111","A00000")); + List result = skuCacheRepository.findAllBySkuNumberIn(Set.of("A11111", "A00000")); assertAll( // - () -> assertThat(result).hasSize(2), - () -> assertThat(result).extracting("skuNumber").containsExactlyInAnyOrder("A11111","A00000") // + () -> assertThat(result).hasSize(2), + () -> assertThat(result).extracting("skuNumber").containsExactlyInAnyOrder("A11111", "A00000") // ); } @@ -80,8 +78,7 @@ void testFindOneBy() { SKU result = skuCacheRepository.findOneBySkuNumber("A11111").orElseThrow(); assertAll( // - () -> assertThat(result).isNotNull(), - () -> assertThat(result.getSkuNumber()).isEqualTo("A11111") // + () -> assertThat(result).isNotNull(), () -> assertThat(result.getSkuNumber()).isEqualTo("A11111") // ); } @@ -90,8 +87,8 @@ void testFindByPropertyWithAliasWithHyphens() { List result = studentRepository.findByUserName("Student2"); assertAll( // - () -> assertThat(result).hasSize(1), - () -> assertThat(result).extracting("userName").containsExactly("Student2") // + () -> assertThat(result).hasSize(1), () -> assertThat(result).extracting("userName").containsExactly("Student2") + // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Airport.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Airport.java index 56d744a2..2707a046 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Airport.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Airport.java @@ -13,10 +13,13 @@ public class Airport { @Id private String id; - @AutoComplete @NonNull + @AutoComplete + @NonNull private String name; - @AutoCompletePayload("name") @NonNull + @AutoCompletePayload("name") + @NonNull private String code; - @AutoCompletePayload("name") @NonNull + @AutoCompletePayload("name") + @NonNull private String state; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/AirportsRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/AirportsRepository.java index 3468f72b..6183ea42 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/AirportsRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/AirportsRepository.java @@ -6,7 +6,8 @@ import java.util.List; -@SuppressWarnings("unused") public interface AirportsRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface AirportsRepository extends RedisDocumentRepository { List autoCompleteName(String query); List autoCompleteName(String query, AutoCompleteOptions options); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/BadDocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/BadDocRepository.java index 54f27f6e..e67b7cfd 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/BadDocRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/BadDocRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface BadDocRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface BadDocRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CityRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CityRepository.java index 476c7799..e1b0da3d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CityRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CityRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -public interface CityRepository extends RedisDocumentRepository { +public interface CityRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CompanyRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CompanyRepository.java index 32acd59f..ace4200a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CompanyRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CompanyRepository.java @@ -45,6 +45,7 @@ public interface CompanyRepository extends RedisDocumentRepository findByYearFoundedOrderByNameAsc(int year); + List findByYearFoundedOrderByNameDesc(int year); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ComplexRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ComplexRepository.java index 018a291e..350150b4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ComplexRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ComplexRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -public interface ComplexRepository extends RedisDocumentRepository { +public interface ComplexRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CountryRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CountryRepository.java index 2c700693..37923316 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CountryRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CountryRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -public interface CountryRepository extends RedisDocumentRepository { +public interface CountryRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Custom.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Custom.java index a1cb5f05..2d196aba 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Custom.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Custom.java @@ -18,7 +18,7 @@ public class Custom { @NonNull @Searchable(sortable = true) private String name; - + @Indexed private boolean taken; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomIndexDocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomIndexDocRepository.java index 6745b491..28531263 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomIndexDocRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomIndexDocRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface CustomIndexDocRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface CustomIndexDocRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomRepository.java index fdba225e..df608654 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/CustomRepository.java @@ -4,6 +4,7 @@ import java.util.List; -@SuppressWarnings("unused") public interface CustomRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface CustomRepository extends RedisDocumentRepository { List searchByName(String name); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestNonIndexedRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestNonIndexedRepository.java index 83dad833..bb7e11d1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestNonIndexedRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestNonIndexedRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DeepNestNonIndexedRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DeepNestNonIndexedRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestRepository.java index 06463833..c757f12f 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeepNestRepository.java @@ -4,6 +4,7 @@ import java.util.Optional; -@SuppressWarnings("unused") public interface DeepNestRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DeepNestRepository extends RedisDocumentRepository { Optional findFirstByNameIs(String name); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperState.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperState.java index 555b6ca5..35168005 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperState.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperState.java @@ -1,5 +1,6 @@ package com.redis.om.spring.annotations.document.fixtures; public enum DeveloperState { - WORK, REST + WORK, + REST } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperType.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperType.java index 49178707..e1e11be0 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperType.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DeveloperType.java @@ -1,5 +1,7 @@ package com.redis.om.spring.annotations.document.fixtures; public enum DeveloperType { - JAVA, CPP, PYTHON + JAVA, + CPP, + PYTHON } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Direccion.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Direccion.java index 81bcbfd3..04371e1c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Direccion.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Direccion.java @@ -6,7 +6,8 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; -@SuppressWarnings("SpellCheckingInspection") @Data +@SuppressWarnings("SpellCheckingInspection") +@Data @RequiredArgsConstructor(staticName = "of") public class Direccion { @NonNull diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc2Repository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc2Repository.java index 30319b05..44445219 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc2Repository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc2Repository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface Doc2Repository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface Doc2Repository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc3Repository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc3Repository.java index 27d75242..6dd6f936 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc3Repository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Doc3Repository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface Doc3Repository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface Doc3Repository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocRepository.java index e062df66..cf34215a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBoolean.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBoolean.java index 7035bb6e..976eaa6c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBoolean.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBoolean.java @@ -11,18 +11,14 @@ @NoArgsConstructor(force = true) @Document public class DocWithBoolean { - @Id - private String id; - - @NonNull - @Indexed - public Boolean indexedBoolean; - - @NonNull - public Boolean nonIndexedBoolean; - - @Indexed - public boolean indexedPrimitiveBoolean; - - public boolean nonIndexedPrimitiveBoolean; + @NonNull + @Indexed + public Boolean indexedBoolean; + @NonNull + public Boolean nonIndexedBoolean; + @Indexed + public boolean indexedPrimitiveBoolean; + public boolean nonIndexedPrimitiveBoolean; + @Id + private String id; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBooleanRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBooleanRepository.java index 34fd9cb2..fbc40b09 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBooleanRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithBooleanRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocWithBooleanRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithBooleanRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithColonInPrefixRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithColonInPrefixRepository.java index c5a727b6..f8fb2837 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithColonInPrefixRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithColonInPrefixRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -public interface DocWithColonInPrefixRepository extends RedisDocumentRepository { +public interface DocWithColonInPrefixRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameId.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameId.java index 3e5e4c51..504330c4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameId.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameId.java @@ -4,7 +4,8 @@ import lombok.Data; import org.springframework.data.annotation.Id; -@SuppressWarnings("SpellCheckingInspection") @Data +@SuppressWarnings("SpellCheckingInspection") +@Data @Document public class DocWithCustomNameId { @Id diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameIdRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameIdRepository.java index 965f6093..6a7cc3cf 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameIdRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithCustomNameIdRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocWithCustomNameIdRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithCustomNameIdRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDate.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDate.java index f8c4b583..49bc7340 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDate.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDate.java @@ -15,11 +15,11 @@ @NoArgsConstructor(force = true) @Document public class DocWithDate { - @Id - @NonNull - private String id; + @Id + @NonNull + private String id; - @Indexed - @NonNull - private Date date; + @Indexed + @NonNull + private Date date; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDateRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDateRepository.java index 66fdf29a..1fa2c2e3 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDateRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithDateRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocWithDateRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithDateRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithEnumRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithEnumRepository.java index 0b3f2205..434e8ec9 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithEnumRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithEnumRepository.java @@ -4,6 +4,7 @@ import java.util.List; -@SuppressWarnings("unused") public interface DocWithEnumRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithEnumRepository extends RedisDocumentRepository { List findByEnumProp(MyJavaEnum value); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidId.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidId.java index 588fe814..1699b642 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidId.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidId.java @@ -5,7 +5,8 @@ import lombok.Data; import org.springframework.data.annotation.Id; -@SuppressWarnings("SpellCheckingInspection") @Data +@SuppressWarnings("SpellCheckingInspection") +@Data @Document public class DocWithExplicitUlidId { @Id diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidIdRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidIdRepository.java index 24b2b2cc..3cf79371 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidIdRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithExplicitUlidIdRepository.java @@ -3,5 +3,6 @@ import com.github.f4b6a3.ulid.Ulid; import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings({ "unused", "SpellCheckingInspection" }) public interface DocWithExplicitUlidIdRepository extends RedisDocumentRepository { +@SuppressWarnings({ "unused", "SpellCheckingInspection" }) +public interface DocWithExplicitUlidIdRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithIntegerIdRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithIntegerIdRepository.java index cc9c2a86..06b23848 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithIntegerIdRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithIntegerIdRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocWithIntegerIdRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithIntegerIdRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithLongRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithLongRepository.java index a14cec71..1f19ed0e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithLongRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithLongRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface DocWithLongRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface DocWithLongRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithSetsRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithSetsRepository.java index 55b9818a..ca41e043 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithSetsRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithSetsRepository.java @@ -6,11 +6,15 @@ import java.util.Set; -@SuppressWarnings("ALL") public interface DocWithSetsRepository extends RedisDocumentRepository { +@SuppressWarnings("ALL") +public interface DocWithSetsRepository extends RedisDocumentRepository { Iterable findByTheNumbersContaining(Set ints); + Iterable findByTheNumbersContainingAll(Set ints); Iterable findByTheLocationsNear(Point point, Distance distance); + Iterable findByTheLocationsContaining(Set points); + Iterable findByTheLocationsContainingAll(Set points); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithoutId.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithoutId.java index 91dfe8b4..f872556d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithoutId.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocWithoutId.java @@ -10,7 +10,7 @@ @Document public class DocWithoutId { private String id; - + @Indexed private List tags; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjection.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjection.java index 6d030c49..49fdca3c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjection.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjection.java @@ -3,8 +3,9 @@ import org.springframework.beans.factory.annotation.Value; public interface DocumentProjection { - String getName(); - @Value("#{target.name + ' ' + target.test}") - String getSpelTest(); + String getName(); + + @Value("#{target.name + ' ' + target.test}") + String getSpelTest(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionPojo.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionPojo.java index 2be46da3..4b793e54 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionPojo.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionPojo.java @@ -10,15 +10,15 @@ @Data public class DocumentProjectionPojo { - @Id - private String id; + @Id + private String id; - private String name; + private String name; - private String test; + private String test; - public DocumentProjectionPojo() { - this.id = UUID.randomUUID().toString(); - } + public DocumentProjectionPojo() { + this.id = UUID.randomUUID().toString(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionRepository.java index fb24ede4..00857ff2 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/DocumentProjectionRepository.java @@ -8,7 +8,9 @@ import java.util.Optional; public interface DocumentProjectionRepository extends RedisDocumentRepository { - Optional findByName(String name); - Collection findAllByName(String name); - Page findAllByName(String name, Pageable pageable); + Optional findByName(String name); + + Collection findAllByName(String name); + + Page findAllByName(String name, Pageable pageable); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPerson.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPerson.java index 30fdb0b7..1763a9fd 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPerson.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPerson.java @@ -14,10 +14,13 @@ @RequiredArgsConstructor(staticName = "of") @Document(timeToLive = 5) public class ExpiringPerson { - @Id String id; - @NonNull @Indexed + @Id + String id; + @NonNull + @Indexed String name; - + @NonNull - @TimeToLive Long ttl; + @TimeToLive + Long ttl; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnit.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnit.java index 37765f2d..c927bd77 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnit.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnit.java @@ -15,10 +15,12 @@ @RequiredArgsConstructor(staticName = "of") @Document(timeToLive = 5) public class ExpiringPersonDifferentTimeUnit { - @Id String id; + @Id + String id; @NonNull String name; - + @NonNull - @TimeToLive(unit = TimeUnit.DAYS) Long ttl; + @TimeToLive(unit = TimeUnit.DAYS) + Long ttl; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnitRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnitRepository.java index 0166bcc4..47c9b18c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnitRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonDifferentTimeUnitRepository.java @@ -2,5 +2,7 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface ExpiringPersonDifferentTimeUnitRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonDifferentTimeUnitRepository + extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonRepository.java index 7896ee9c..770c0fdc 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonRepository.java @@ -4,6 +4,7 @@ import java.util.Optional; -@SuppressWarnings("unused") public interface ExpiringPersonRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonRepository extends RedisDocumentRepository { Optional findOneByName(String name); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefault.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefault.java index 188c1f64..c9ff73c6 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefault.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefault.java @@ -12,7 +12,8 @@ @RequiredArgsConstructor(staticName = "of") @Document(timeToLive = 5) public class ExpiringPersonWithDefault { - @Id String id; + @Id + String id; @NonNull String name; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefaultRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefaultRepository.java index 32bf4cf7..7318d6a1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefaultRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ExpiringPersonWithDefaultRepository.java @@ -2,5 +2,7 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface ExpiringPersonWithDefaultRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonWithDefaultRepository + extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FilmRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FilmRepository.java index 0b510bc9..f89e4941 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FilmRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FilmRepository.java @@ -6,6 +6,8 @@ public interface FilmRepository extends RedisDocumentRepository { List search(String text); + List searchByTitle(String title); + List searchByTitleAndLengthLessThanEqual(String title, Integer length); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FruitRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FruitRepository.java index 8656a7f9..349baa26 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FruitRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/FruitRepository.java @@ -5,13 +5,17 @@ import java.util.List; - @Repository public interface FruitRepository extends RedisDocumentRepository { Long deleteByName(String name); + List removeByColor(String color); + List deleteByColor(String color); + Long removeByName(String name); + long deleteByNameOrColor(String apple, String green); + long deleteByColorIsNull(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/GameRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/GameRepository.java index fed9ff0b..c3ff6fbb 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/GameRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/GameRepository.java @@ -9,7 +9,8 @@ import java.util.Map; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataRepositoryMethodReturnTypeInspection" }) public interface GameRepository extends RedisDocumentRepository { +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataRepositoryMethodReturnTypeInspection" }) +public interface GameRepository extends RedisDocumentRepository { /** *
    * FT.AGGREGATE "com.redis.om.spring.annotations.document.fixtures.GameIdx" '*'
@@ -20,16 +21,17 @@
    * 
*/ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count", direction = Direction.DESC), // - } - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count", direction = Direction.DESC), // + } + ) + // Page> countByBrand(Pageable pageable); /** @@ -42,20 +44,20 @@ * */ @Aggregation( // - value = "sony", // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MIN, args={"@price"}, alias="minPrice") - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@minPrice", direction = Direction.DESC), // - } - ) // + value = "sony", // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MIN, args = { "@price" }, alias = "minPrice") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@minPrice", direction = Direction.DESC), // + } + ) + // AggregationResult minPricesContainingSony(); /** @@ -68,20 +70,20 @@ * */ @Aggregation( // - value = "sony", // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MAX, args={"@price"}, alias="maxPrice") - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@maxPrice", direction = Direction.DESC), // - } - ) // + value = "sony", // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MAX, args = { "@price" }, alias = "maxPrice") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@maxPrice", direction = Direction.DESC), // + } + ) + // AggregationResult maxPricesContainingSony(); /** @@ -95,20 +97,23 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT_DISTINCT, args={"@title"}, alias="count_distinct(title)"), // - @Reducer(func = ReducerFunction.COUNT) // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count_distinct(title)", direction = Direction.DESC), // - }, - limit = 5 - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer( + func = ReducerFunction.COUNT_DISTINCT, args = { "@title" }, + alias = "count_distinct(title)" + ), // + @Reducer(func = ReducerFunction.COUNT) // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count_distinct(title)", direction = Direction.DESC), // + }, limit = 5 + ) + // AggregationResult top5countDistinctByBrand(); /** @@ -124,23 +129,23 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.50"}, alias="q50"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.90"}, alias="q90"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.95"}, alias="q95"), // - @Reducer(func = ReducerFunction.AVG, args={"@price"}), // - @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@rowcount", direction = Direction.DESC), // - }, - sortByMax = 1 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.50" }, alias = "q50"), // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.90" }, alias = "q90"), // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.95" }, alias = "q95"), // + @Reducer(func = ReducerFunction.AVG, args = { "@price" }), // + @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@rowcount", direction = Direction.DESC), // + }, sortByMax = 1 // + ) + // AggregationResult priceQuantiles(); /** @@ -156,22 +161,24 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.STDDEV, args={"@price"}, alias="stddev(price)"), // - @Reducer(func = ReducerFunction.AVG, args={"@price"}, alias = "avgPrice"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.50"}, alias="q50Price"), // - @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@rowcount", direction = Direction.DESC), // - }, - limit = 10 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.STDDEV, args = { "@price" }, alias = "stddev(price)"), // + @Reducer(func = ReducerFunction.AVG, args = { "@price" }, alias = "avgPrice"), // + @Reducer( + func = ReducerFunction.QUANTILE, args = { "@price", "0.50" }, alias = "q50Price" + ), // + @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@rowcount", direction = Direction.DESC), // + }, limit = 10 // + ) + // AggregationResult priceStdDev(); /** @@ -185,18 +192,19 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // - ) // - }, // - apply = { // - @Apply(expression = "timefmt(1517417144)", alias = "dt"), // - @Apply(expression = "parsetime(@dt, \"%FT%TZ\")", alias = "parsed_dt"), // - }, // - limit = 1 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + apply = { // + @Apply(expression = "timefmt(1517417144)", alias = "dt"), // + @Apply(expression = "parsetime(@dt, \"%FT%TZ\")", alias = "parsed_dt"), // + }, // + limit = 1 // + ) + // AggregationResult parseTime(); /** @@ -209,20 +217,22 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT, alias = "num"), // - @Reducer(func = ReducerFunction.RANDOM_SAMPLE, args={"@price", "10"}, alias = "sample") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@num", direction = Direction.DESC), // - }, - sortByMax = 10 - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT, alias = "num"), // + @Reducer( + func = ReducerFunction.RANDOM_SAMPLE, args = { "@price", "10" }, alias = "sample" + ) // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@num", direction = Direction.DESC), // + }, sortByMax = 10 + ) + // AggregationResult randomSample(); /** @@ -242,20 +252,19 @@ * */ @Aggregation( // - apply = { - @Apply(expression = "1517417144", alias = "dt"), // - @Apply(expression = "timefmt(@dt)", alias = "timefmt"), // - @Apply(expression = "day(@dt)", alias = "day"), // - @Apply(expression = "hour(@dt)", alias = "hour"), // - @Apply(expression = "minute(@dt)", alias = "minute"), // - @Apply(expression = "month(@dt)", alias = "month"), // - @Apply(expression = "dayofweek(@dt)", alias = "dayofweek"), // - @Apply(expression = "dayofmonth(@dt)", alias = "dayofmonth"), // - @Apply(expression = "dayofyear(@dt)", alias = "dayofyear"), // - @Apply(expression = "year(@dt)", alias = "year"), // - }, - limit = 1 - ) // + apply = { @Apply(expression = "1517417144", alias = "dt"), // + @Apply(expression = "timefmt(@dt)", alias = "timefmt"), // + @Apply(expression = "day(@dt)", alias = "day"), // + @Apply(expression = "hour(@dt)", alias = "hour"), // + @Apply(expression = "minute(@dt)", alias = "minute"), // + @Apply(expression = "month(@dt)", alias = "month"), // + @Apply(expression = "dayofweek(@dt)", alias = "dayofweek"), // + @Apply(expression = "dayofmonth(@dt)", alias = "dayofmonth"), // + @Apply(expression = "dayofyear(@dt)", alias = "dayofyear"), // + @Apply(expression = "year(@dt)", alias = "year"), // + }, limit = 1 + ) + // AggregationResult timeFunctions(); /** @@ -268,20 +277,21 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@title", "@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MAX, args={"@price"}, alias = "price") // - } // - ) // - }, // - apply = { - @Apply(expression = "format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", alias = "titleBrand"), // - }, - limit = 10 - ) // + groupBy = { // + @GroupBy( // + properties = { "@title", "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MAX, args = { "@price" }, alias = "price") // + } // + ) // + }, // + apply = { @Apply( + expression = "format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", alias = "titleBrand" + ), // + }, limit = 10 + ) + // AggregationResult stringFormat(); /** @@ -295,20 +305,20 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT, alias="count"), // - @Reducer(func = ReducerFunction.SUM, args={"@price"}, alias = "sum(price)") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@sum(price)", direction = Direction.DESC), // - }, - limit = 5 // - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT, alias = "count"), // + @Reducer(func = ReducerFunction.SUM, args = { "@price" }, alias = "sum(price)") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@sum(price)", direction = Direction.DESC), // + }, limit = 5 // + ) + // AggregationResult sumPrice(); /** @@ -321,14 +331,15 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias="count") } // - ) // - }, // - filter = { "@count < 5", "@count > 2 && @brand != \"\"" } - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + filter = { "@count < 5", "@count > 2 && @brand != \"\"" } + ) + // AggregationResult filters(); /** @@ -342,20 +353,20 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT_DISTINCT, args="@price", alias="count"), // - @Reducer(func = ReducerFunction.TOLIST, args="@price", alias="prices") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count", direction = Direction.DESC), // - }, - limit = 5 // - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT_DISTINCT, args = "@price", alias = "count"), // + @Reducer(func = ReducerFunction.TOLIST, args = "@price", alias = "prices") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count", direction = Direction.DESC), // + }, limit = 5 // + ) + // AggregationResult toList(); /** @@ -369,19 +380,19 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { @Reducer(func = ReducerFunction.SUM, args="@price", alias="price") } // - ) // - }, // - apply = { @Apply(expression = "(@price % 10)", alias = "price") }, // - sortBy = { // - @SortBy(field = "@price", direction = Direction.ASC), // - @SortBy(field = "@brand", direction = Direction.DESC), // - }, - sortByMax = 10 - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { @Reducer(func = ReducerFunction.SUM, args = "@price", alias = "price") } // + ) // + }, // + apply = { @Apply(expression = "(@price % 10)", alias = "price") }, // + sortBy = { // + @SortBy(field = "@price", direction = Direction.ASC), // + @SortBy(field = "@brand", direction = Direction.DESC), // + }, sortByMax = 10 + ) + // AggregationResult sortByMany(); /** @@ -393,10 +404,10 @@ * */ @Aggregation( // - load = @Load(property = "@title"), - sortBy = @SortBy(field = "@price", direction = Direction.DESC), - limit = 2 - ) // + load = @Load(property = "@title"), sortBy = @SortBy(field = "@price", direction = Direction.DESC), + limit = 2 + ) + // AggregationResult loadWithSort(); /** @@ -410,10 +421,10 @@ * */ @Aggregation( // - load = { @Load(property = "@brand"), @Load(property = "@price"), @Load(property = "@__key") }, - sortBy = @SortBy(field = "@price", direction = Direction.DESC), - sortByMax = 4 - ) // + load = { @Load(property = "@brand"), @Load(property = "@price"), @Load(property = "@__key") }, + sortBy = @SortBy(field = "@price", direction = Direction.DESC), sortByMax = 4 + ) + // AggregationResult loadWithDocId(); /** @@ -429,20 +440,23 @@ * */ @Aggregation( // - value = "@brand:(sony|matias|beyerdynamic|(mad catz))", - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // + value = "@brand:(sony|matias|beyerdynamic|(mad catz))", groupBy = { // + @GroupBy( // + properties = { "@brand" }, // reduce = { // - @Reducer(func = ReducerFunction.FIRST_VALUE, args={"@title", "@price", "DESC"}, alias="top_item"), - @Reducer(func = ReducerFunction.FIRST_VALUE, args={"@price", "@price", "DESC"}, alias="top_price"), - @Reducer(func = ReducerFunction.FIRST_VALUE, args={"@title", "@price", "ASC"}, alias="bottom_item"), - @Reducer(func = ReducerFunction.FIRST_VALUE, args={"@price", "@price", "ASC"}, alias="bottom_price"), - } // - ) // - }, // - sortBy = @SortBy(field = "@top_price", direction = Direction.DESC), // - sortByMax = 5 // - ) // + @Reducer(func = ReducerFunction.FIRST_VALUE, args = { "@title", "@price", "DESC" }, alias = "top_item"), + @Reducer( + func = ReducerFunction.FIRST_VALUE, args = { "@price", "@price", "DESC" }, alias = "top_price" + ), @Reducer( + func = ReducerFunction.FIRST_VALUE, args = { "@title", "@price", "ASC" }, alias = "bottom_item" + ), @Reducer( + func = ReducerFunction.FIRST_VALUE, args = { "@price", "@price", "ASC" }, alias = "bottom_price" + ), } // + ) // + }, // + sortBy = @SortBy(field = "@top_price", direction = Direction.DESC), // + sortByMax = 5 // + ) + // AggregationResult firstValue(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/KitchenSinkRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/KitchenSinkRepository.java index 48e6e83f..acf364d3 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/KitchenSinkRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/KitchenSinkRepository.java @@ -2,6 +2,7 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -@SuppressWarnings("unused") public interface KitchenSinkRepository extends RedisDocumentRepository { +@SuppressWarnings("unused") +public interface KitchenSinkRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Metadata.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Metadata.java index f8e98eba..a41cc542 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Metadata.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Metadata.java @@ -15,10 +15,10 @@ public class Metadata { @Id private String id; - + @Indexed - private String employeeId; - + private String employeeId; + @Indexed private String deptId; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MetadataRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MetadataRepository.java index 01a2db23..6bb55cd7 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MetadataRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MetadataRepository.java @@ -4,6 +4,7 @@ import java.util.Set; -@SuppressWarnings({ "unused", "SpringDataRepositoryMethodParametersInspection" }) public interface MetadataRepository extends RedisDocumentRepository { +@SuppressWarnings({ "unused", "SpringDataRepositoryMethodParametersInspection" }) +public interface MetadataRepository extends RedisDocumentRepository { Iterable findByDeptId(Set list); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MovieRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MovieRepository.java index 9c785cd5..8e8a2887 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MovieRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MovieRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisDocumentRepository; -public interface MovieRepository extends RedisDocumentRepository { +public interface MovieRepository extends RedisDocumentRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MultiLingualDocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MultiLingualDocRepository.java index a2bdc853..a4a4b22c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MultiLingualDocRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MultiLingualDocRepository.java @@ -4,7 +4,8 @@ import com.redis.om.spring.repository.query.SearchLanguage; import redis.clients.jedis.search.SearchResult; -@SuppressWarnings({ "unused", "SpringDataRepositoryMethodReturnTypeInspection" }) public interface MultiLingualDocRepository extends RedisDocumentRepository< MultiLingualDoc, String> { +@SuppressWarnings({ "unused", "SpringDataRepositoryMethodReturnTypeInspection" }) +public interface MultiLingualDocRepository extends RedisDocumentRepository { SearchResult findByBody(String text, SearchLanguage language); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDoc.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDoc.java index 0e535e9c..045a9e4c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDoc.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDoc.java @@ -19,19 +19,19 @@ public class MyDoc { @NonNull @TextIndexed(alias = "title", sortable = true) private String title; - + @NonNull @GeoIndexed(alias = "location") private Point location; - + @NonNull @Indexed private Point location2; - + @NonNull @NumericIndexed private Integer aNumber; - + @TagIndexed(alias = "tag") private Set tag = new HashSet<>(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocQueriesImpl.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocQueriesImpl.java index 365fc9c2..258d4927 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocQueriesImpl.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocQueriesImpl.java @@ -22,12 +22,12 @@ public class MyDocQueriesImpl implements MyDocQueries { @Override public Optional findByTitle(String title) { - SearchOperations ops = modulesOperations - .opsForSearch("com.redis.om.spring.annotations.document.fixtures.MyDocIdx"); + SearchOperations ops = modulesOperations.opsForSearch( + "com.redis.om.spring.annotations.document.fixtures.MyDocIdx"); SearchResult result = ops.search(new Query("@title:'" + title + "'")); if (result.getTotalResults() > 0) { Document doc = result.getDocuments().get(0); - return Optional.of(gson.fromJson(SafeEncoder.encode((byte[])doc.get("$")), MyDoc.class)); + return Optional.of(gson.fromJson(SafeEncoder.encode((byte[]) doc.get("$")), MyDoc.class)); } else { return Optional.empty(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocRepository.java index e874ea1d..2905f020 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyDocRepository.java @@ -15,7 +15,8 @@ import java.util.List; import java.util.Set; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) public interface MyDocRepository extends RedisDocumentRepository, MyDocQueries { +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) +public interface MyDocRepository extends RedisDocumentRepository, MyDocQueries { /** *
    * > FT.SEARCH idx * RETURN 3 $.tag[0] AS first_tag 1) (integer) 1 2) "doc1" 3)
@@ -46,7 +47,7 @@
    *    2) "article"
    * 
*/ - @Aggregation(load = { @Load(property = "$.tag[1]", alias = "tag2")}) + @Aggregation(load = { @Load(property = "$.tag[1]", alias = "tag2") }) AggregationResult getSecondTagWithAggregation(); /** @@ -76,9 +77,9 @@ * > FT.SEARCH idx @title:pre* SORTBY title ASC LIMIT 1 12 RETURN 2 title aNumber * */ - @Query(value="@title:$prefix*", returnFields={"title", "aNumber"}, limit = 12, offset = 1, sortBy = "title") + @Query(value = "@title:$prefix*", returnFields = { "title", "aNumber" }, limit = 12, offset = 1, sortBy = "title") SearchResult customFindAllByTitleStartingWithReturnFieldsAndLimit(@Param("prefix") String prefix); - + /** *
    * > FT.TAGVALS idx tags
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyJavaEnum.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyJavaEnum.java
index aff3db5d..9d63e8e9 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyJavaEnum.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/MyJavaEnum.java
@@ -1,5 +1,7 @@
 package com.redis.om.spring.annotations.document.fixtures;
 
 public enum MyJavaEnum {
-  VALUE_1, VALUE_2, VALUE_3
+  VALUE_1,
+  VALUE_2,
+  VALUE_3
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/NiCompanyRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/NiCompanyRepository.java
index 98276af1..0c16dfe7 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/NiCompanyRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/NiCompanyRepository.java
@@ -4,6 +4,7 @@
 
 import java.util.Optional;
 
-@SuppressWarnings("unused") public interface NiCompanyRepository extends RedisDocumentRepository {
+@SuppressWarnings("unused")
+public interface NiCompanyRepository extends RedisDocumentRepository {
   Optional findFirstByName(String name);
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PermitRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PermitRepository.java
index db7155fa..c0707813 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PermitRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PermitRepository.java
@@ -6,46 +6,47 @@
 
 import java.util.Set;
 
-@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) public interface PermitRepository extends RedisDocumentRepository {
+@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" })
+public interface PermitRepository extends RedisDocumentRepository {
 
   // Numeric range queries:
   // FT.SEARCH permits "@construction_value:[42000,42000]"
   // find by numeric property
   // Result: Every document that has a construction value of exactly 42000, so tst:permit:1.
   Iterable findByConstructionValue(long value);
-  
+
   // Performing a text search on all text fields:
   // FT.SEARCH permits "veranda"
   // Result: Documents inside which the word 'veranda' occurs, so tst:permit:1.
   Iterable search(String text);
-  
+
   // Perform search with paging and sorting parameters
   Page search(String text, Pageable pageable);
-  
+
   // A fuzzy text search on all text fields:
   // FT.SEARCH permits "%%haus%%" 
   // Result: Documents with words similar to 'haus' (tst:permit:1 and tst:permit:3). The number of % indicates the allowed Levenshtein distance (later more about it). So the query would also match on 'house' because 'haus' and 'house' have a distance of two.
-  
+
   // Performing a text search on a specific field:
   // FT.SEARCH permits "@building_type:detached" 
   Iterable findByBuildingType(String buildingType);
-  
+
   // Performing a tag search
   // FT.SEARCH permits "@city:{Lisbon}"
   Iterable findByAddress_City(String city);
-  
+
   // search documents that have one of multiple tags (OR condition)
   // FT.SEARCH permits "@work_type:{construction|design}"
   Iterable findByWorkType(Set workTypes);
-  
+
   // Search documents that have all the tags (AND condition):
   // FT.SEARCH permits "@work_type:{construction} @work_type:{design}"
   Iterable findByWorkTypeContainingAll(Set workTypes);
-  
+
   // Performing a combined search on two fields (AND):
   // FT.SEARCH permits "@building_type:house @description:new"
   Iterable findByBuildingTypeAndDescription(String buildingType, String description);
-  
+
   // Performing a combined search on two fields (OR):
   // FT.SEARCH permits "(@city:{Lagos})|(@description:detached)"
   Iterable findByAddress_CityOrDescription(String buildingType, String description);
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Person.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Person.java
index a7e6b0f6..ead09771 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Person.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Person.java
@@ -12,62 +12,43 @@
 @Data
 @Document
 public class Person {
-  @Id
-  private String id;
-
   //@Indexed - Nope! This will cause a StackOverflow
   public Person mother;
-
   @Searchable
   public String name;
-
   @Indexed(sortable = true)
   public Point home;
-
   @Indexed(sortable = true)
   public Point work;
-
   @Indexed
   public PersonAddress personAddress;
-
   public boolean engineer;
-
   @Indexed(sortable = true)
   public int age;
-
   @Indexed(sortable = true)
   public double height;
-
   @Indexed
   public String[] nickNames;
-
   @Indexed
   public List nickNamesList;
-
   @Indexed
   public String tagField;
-
   @Indexed(sortable = true)
   public int departmentNumber;
-
   @Indexed(sortable = true)
   public double sales;
-
   @Indexed(sortable = true)
   public double salesAdjustment;
-
   @Indexed(sortable = true)
   public long lastTimeOnline;
-
   @Searchable
   public String timeString;
-
   @Indexed
   public String email;
-
   @Indexed(sortable = true)
   public String unaggreatableField;
-
   @Indexed
   public String nullableStringField;
+  @Id
+  private String id;
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonAddress.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonAddress.java
index 977c7ff2..730b7e68 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonAddress.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonAddress.java
@@ -13,14 +13,22 @@
 public class PersonAddress {
   private String streetName;
   private String zipCode;
-  @Indexed private AddressType addressType;
-  @Indexed private String city;
-  @Indexed private String state;
+  @Indexed
+  private AddressType addressType;
+  @Indexed
+  private String city;
+  @Indexed
+  private String state;
   // @Indexed - nope stackOverflow
   private PersonAddress forwardingAddress;
-  @Indexed private Point location;
-  @Indexed private int houseNumber;
-  @Indexed private boolean bool;
-  @Indexed private Ulid ulid;
-  @Indexed private UUID guid;
+  @Indexed
+  private Point location;
+  @Indexed
+  private int houseNumber;
+  @Indexed
+  private boolean bool;
+  @Indexed
+  private Ulid ulid;
+  @Indexed
+  private UUID guid;
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonRepository.java
index 86699010..f04c51e4 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PersonRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface PersonRepository extends RedisDocumentRepository {
+public interface PersonRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrder.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrder.java
index cc0e07ae..6130b4db 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrder.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrder.java
@@ -16,24 +16,31 @@
 @RequiredArgsConstructor(staticName = "of")
 @Document
 public class PizzaOrder {
-  @NonNull @Id
+  @NonNull
+  @Id
   private Integer id;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private String name;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private String size;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private double price;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private int quantity;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private Instant date;
 
-  @NonNull @Indexed(sortable = true)
+  @NonNull
+  @Indexed(sortable = true)
   private LocalDateTime created;
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrderRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrderRepository.java
index b1342589..cf9f07f2 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrderRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/PizzaOrderRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface PizzaOrderRepository extends RedisDocumentRepository {
+public interface PizzaOrderRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Product.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Product.java
index 30622131..dc36a082 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Product.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/Product.java
@@ -23,12 +23,12 @@ public class Product {
   private String name;
 
   @Indexed(//
-      schemaFieldType = SchemaFieldType.VECTOR, //
-      algorithm = VectorAlgorithm.HNSW, //
-      type = VectorType.FLOAT32, //
-      dimension = 512, //
-      distanceMetric = DistanceMetric.COSINE, //
-      initialCapacity = 10
+           schemaFieldType = SchemaFieldType.VECTOR, //
+           algorithm = VectorAlgorithm.HNSW, //
+           type = VectorType.FLOAT32, //
+           dimension = 512, //
+           distanceMetric = DistanceMetric.COSINE, //
+           initialCapacity = 10
   )
   private float[] imageEmbedding;
 
@@ -37,12 +37,12 @@ public class Product {
   private String imagePath;
 
   @Indexed(//
-      schemaFieldType = SchemaFieldType.VECTOR, //
-      algorithm = VectorAlgorithm.HNSW, //
-      type = VectorType.FLOAT32, //
-      dimension = 768, //
-      distanceMetric = DistanceMetric.COSINE, //
-      initialCapacity = 10
+           schemaFieldType = SchemaFieldType.VECTOR, //
+           algorithm = VectorAlgorithm.HNSW, //
+           type = VectorType.FLOAT32, //
+           dimension = 768, //
+           distanceMetric = DistanceMetric.COSINE, //
+           initialCapacity = 10
   )
   private float[] sentenceEmbedding;
 
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/RefRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/RefRepository.java
index 7fe6e85b..d47bea74 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/RefRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/RefRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface RefRepository extends RedisDocumentRepository {
+public interface RefRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocument.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocument.java
index 9f9e64b2..cf0d97d3 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocument.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocument.java
@@ -10,33 +10,35 @@
 
 import java.time.LocalDateTime;
 
-@Data @NoArgsConstructor(force = true)
-@Document public class SomeDocument {
-  @NonNull @Id @Indexed protected String id;
-  @NonNull @Indexed private String name;
-
-  @Indexed(sortable = true) private LocalDateTime documentCreationDate;
-  @Searchable private String description;
-  @Indexed private Source source;
-  @Searchable private String category;
-  @Indexed private Format format;
-  @Searchable private String objectStorageKey;
-  @Searchable private String searchableContent;
-
-  @SuppressWarnings("unused") public enum Format {
-    pdf,
-    word,
-    text,
-    png,
-    jpeg
-  }
+@Data
+@NoArgsConstructor(force = true)
+@Document
+public class SomeDocument {
+  @NonNull
+  @Id
+  @Indexed
+  protected String id;
+  @NonNull
+  @Indexed
+  private String name;
 
-  @SuppressWarnings("unused") public enum Source {
-    sourceA,
-    sourceB
-  }
+  @Indexed(sortable = true)
+  private LocalDateTime documentCreationDate;
+  @Searchable
+  private String description;
+  @Indexed
+  private Source source;
+  @Searchable
+  private String category;
+  @Indexed
+  private Format format;
+  @Searchable
+  private String objectStorageKey;
+  @Searchable
+  private String searchableContent;
 
-  @Override public boolean equals(Object o) {
+  @Override
+  public boolean equals(Object o) {
     if (this == o)
       return true;
     if (o == null || getClass() != o.getClass())
@@ -49,10 +51,26 @@
     return name.equals(that.name);
   }
 
-  @Override public int hashCode() {
+  @Override
+  public int hashCode() {
     int result = id.hashCode();
     result = 31 * result + name.hashCode();
     return result;
   }
 
+  @SuppressWarnings("unused")
+  public enum Format {
+    pdf,
+    word,
+    text,
+    png,
+    jpeg
+  }
+
+  @SuppressWarnings("unused")
+  public enum Source {
+    sourceA,
+    sourceB
+  }
+
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocumentRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocumentRepository.java
index 217b2034..2e325efa 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocumentRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SomeDocumentRepository.java
@@ -2,5 +2,6 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-@SuppressWarnings("unused") public interface SomeDocumentRepository extends RedisDocumentRepository {
+@SuppressWarnings("unused")
+public interface SomeDocumentRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SpanishDocRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SpanishDocRepository.java
index 31642c69..c642fb4b 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SpanishDocRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/SpanishDocRepository.java
@@ -3,7 +3,8 @@
 import com.redis.om.spring.repository.RedisDocumentRepository;
 import redis.clients.jedis.search.SearchResult;
 
-@SuppressWarnings({ "unused", "SpringDataRepositoryMethodReturnTypeInspection" }) public interface SpanishDocRepository extends RedisDocumentRepository {
+@SuppressWarnings({ "unused", "SpringDataRepositoryMethodReturnTypeInspection" })
+public interface SpanishDocRepository extends RedisDocumentRepository {
 
   SearchResult findByBody(String text);
 
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StateRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StateRepository.java
index f8f05815..c444baed 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StateRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StateRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface StateRepository extends RedisDocumentRepository {
+public interface StateRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StatesRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StatesRepository.java
index 0ea95939..72fcb453 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StatesRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/StatesRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface StatesRepository extends RedisDocumentRepository {
+public interface StatesRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/TooManyReferencesRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/TooManyReferencesRepository.java
index d54aca9e..97be5afc 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/TooManyReferencesRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/TooManyReferencesRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface TooManyReferencesRepository extends RedisDocumentRepository {
+public interface TooManyReferencesRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User.java
index 86a1afd4..543dd436 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User.java
@@ -16,15 +16,15 @@
 public class User {
   @Id
   private String id;
-  
+
   @NonNull
   @Indexed
   private String name;
-  
+
   @NonNull
   @Indexed
   private Double lotteryWinnings;
-  
+
   @Indexed
   private List roles = new ArrayList<>();
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2.java
index 5d7e57a3..5fd95968 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2.java
@@ -10,7 +10,7 @@
 @AllArgsConstructor(access = AccessLevel.PROTECTED)
 @NoArgsConstructor(force = true)
 @Document
-public class User2{
+public class User2 {
   @Id
   @Indexed
   private String id;
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2Repository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2Repository.java
index 1cdf7e28..4510fbd2 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2Repository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/User2Repository.java
@@ -4,12 +4,13 @@
 import com.redis.om.spring.repository.RedisDocumentRepository;
 import org.springframework.data.repository.query.Param;
 
-@SuppressWarnings("unused") public interface User2Repository extends RedisDocumentRepository {
+@SuppressWarnings("unused")
+public interface User2Repository extends RedisDocumentRepository {
 
   @Query("(@name:{$name}) (@address:{$address}) (@addressComplement:{$addressComp})")
   Iterable findUser( //
-      @Param("name") String name, //
-      @Param("address") String strAdd, //
-      @Param("addressComp") String strAddComp //
+    @Param("name") String name, //
+    @Param("address") String strAdd, //
+    @Param("addressComp") String strAddComp //
   );
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/UserRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/UserRepository.java
index 546bfe27..ae2e3981 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/UserRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/UserRepository.java
@@ -4,6 +4,7 @@
 
 import java.util.Optional;
 
-@SuppressWarnings("unused") public interface UserRepository  extends RedisDocumentRepository {
+@SuppressWarnings("unused")
+public interface UserRepository extends RedisDocumentRepository {
   Optional findFirstByName(String name);
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/VersionedEntity.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/VersionedEntity.java
index bb3a7fad..6fb14f36 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/VersionedEntity.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/VersionedEntity.java
@@ -7,14 +7,12 @@
 @Document
 public class VersionedEntity {
 
+  private final String name;
   @Id
   private long id;
-
   @Version
   private long version;
 
-  private final String name;
-
   public VersionedEntity(long id) {
     this(id, 0, null);
   }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAlias.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAlias.java
index 8548e824..6a02d664 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAlias.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAlias.java
@@ -7,7 +7,8 @@
 
 import java.util.Set;
 
-@SuppressWarnings("SpellCheckingInspection") @Data
+@SuppressWarnings("SpellCheckingInspection")
+@Data
 @NoArgsConstructor(force = true)
 @RequiredArgsConstructor(staticName = "of")
 @AllArgsConstructor(access = AccessLevel.PROTECTED)
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAliasRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAliasRepository.java
index bac2a558..719181da 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAliasRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithAliasRepository.java
@@ -4,6 +4,7 @@
 
 import java.util.Optional;
 
-@SuppressWarnings("unused") public interface WithAliasRepository extends RedisDocumentRepository {
+@SuppressWarnings("unused")
+public interface WithAliasRepository extends RedisDocumentRepository {
   Optional findFirstByNumber(Integer number);
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUUIDsRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUUIDsRepository.java
index 1dd072b6..38ab5964 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUUIDsRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUUIDsRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface WithNestedListOfUUIDsRepository extends RedisDocumentRepository {
+public interface WithNestedListOfUUIDsRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUlidsRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUlidsRepository.java
index 1e9de058..fef2ddc0 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUlidsRepository.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/WithNestedListOfUlidsRepository.java
@@ -2,5 +2,5 @@
 
 import com.redis.om.spring.repository.RedisDocumentRepository;
 
-public interface WithNestedListOfUlidsRepository extends RedisDocumentRepository {
+public interface WithNestedListOfUlidsRepository extends RedisDocumentRepository {
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ZipCode.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ZipCode.java
index dfcc16db..a988fcfa 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ZipCode.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/fixtures/ZipCode.java
@@ -25,8 +25,7 @@
  *   "pop" : 15338,
  *   "state" : "MA"
  * }
- */
-public class ZipCode {
+ */ public class ZipCode {
 
   @Id
   @SerializedName(value = "_id")
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/sentinel/BasicSentinelTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/sentinel/BasicSentinelTest.java
index a420791c..b2bd1219 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/sentinel/BasicSentinelTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/sentinel/BasicSentinelTest.java
@@ -28,8 +28,8 @@ void testBasicCrudOperations() {
       "stack@redis.com");
     redis.setMetaList(Set.of(CompanyMeta.of("Redis", 100, Set.of("RedisTag"))));
 
-    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-      new Point(-122.124500, 47.640160), "research@microsoft.com");
+    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+      "research@microsoft.com");
     microsoft.setMetaList(Set.of(CompanyMeta.of("MS", 50, Set.of("MsTag"))));
 
     repository.saveAll(List.of(redis, microsoft));
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/serialization/SerializationTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/serialization/SerializationTest.java
index 91fcc06d..1c6cd5ac 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/serialization/SerializationTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/serialization/SerializationTest.java
@@ -23,7 +23,8 @@
 
 import static org.assertj.core.api.Assertions.assertThat;
 
-@SuppressWarnings("SpellCheckingInspection") class SerializationTest extends AbstractBaseDocumentTest {
+@SuppressWarnings("SpellCheckingInspection")
+class SerializationTest extends AbstractBaseDocumentTest {
   @Autowired
   KitchenSinkRepository repository;
 
@@ -45,7 +46,6 @@
   private Set setThings;
   private List listThings;
 
-
   @BeforeEach
   void cleanUp() {
     repository.deleteAll();
@@ -61,38 +61,38 @@ void cleanUp() {
     instant = Instant.now();
 
     ks = KitchenSink.builder() //
-            .localDate(localDate) //
-            .localDateTime(localDateTime) //
-            .localOffsetDateTime(localOffsetDateTime) //
-            .date(date) //
-            .point(point) //
-            .ulid(ulid) //
-            .setThings(setThings) //
-            .listThings(listThings) //
-            .instant(instant) //
-            .build();
+      .localDate(localDate) //
+      .localDateTime(localDateTime) //
+      .localOffsetDateTime(localOffsetDateTime) //
+      .date(date) //
+      .point(point) //
+      .ulid(ulid) //
+      .setThings(setThings) //
+      .listThings(listThings) //
+      .instant(instant) //
+      .build();
 
     ks1 = KitchenSink.builder() //
-            .localDate(localDate) //
-            .localDateTime(localDateTime) //
-            .localOffsetDateTime(localOffsetDateTime) //
-            .date(date) //
-            .point(point) //
-            .ulid(ulid) //
-            .setThings(Set.of()) //
-            .listThings(List.of()) //
-            .instant(instant) //
-            .build();
+      .localDate(localDate) //
+      .localDateTime(localDateTime) //
+      .localOffsetDateTime(localOffsetDateTime) //
+      .date(date) //
+      .point(point) //
+      .ulid(ulid) //
+      .setThings(Set.of()) //
+      .listThings(List.of()) //
+      .instant(instant) //
+      .build();
 
     ks2 = KitchenSink.builder() //
-            .localDate(localDate) //
-            .localDateTime(localDateTime) //
-            .localOffsetDateTime(localOffsetDateTime) //
-            .date(date) //
-            .point(point) //
-            .ulid(ulid) //
-            .instant(instant) //
-            .build();
+      .localDate(localDate) //
+      .localDateTime(localDateTime) //
+      .localOffsetDateTime(localOffsetDateTime) //
+      .date(date) //
+      .point(point) //
+      .ulid(ulid) //
+      .instant(instant) //
+      .build();
 
     ks2.setSetThings(null);
     ks2.setListThings(null);
@@ -121,7 +121,7 @@ void testJSONSerialization() {
 
     // Point
     String redisGeo = "33.62826024782707,-111.83592170193586";
-    
+
     // Instant
     long instantInMillis = instant.toEpochMilli();
 
@@ -135,7 +135,8 @@ void testJSONSerialization() {
     assertThat(rawJSON.get("point").getAsString()).isEqualTo(redisGeo);
     assertThat(rawJSON.get("ulid").getAsString()).isEqualTo(ulid.toString());
     assertThat(rawJSON.get("instant").getAsLong()).isEqualTo(instantInMillis);
-    assertThat(Arrays.asList(rawJSON.get("setThings").getAsString().split("\\|"))).containsExactlyInAnyOrder("thingOne", "thingTwo", "thingThree");
+    assertThat(Arrays.asList(rawJSON.get("setThings").getAsString().split("\\|"))).containsExactlyInAnyOrder("thingOne",
+      "thingTwo", "thingThree");
     assertThat(rawJSON.get("listThings").getAsString()).isEqualTo("redFish|blueFish");
   }
 
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/vectorize/VectorizeDocumentTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/vectorize/VectorizeDocumentTest.java
index 9aad0ac3..020f0091 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/vectorize/VectorizeDocumentTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/document/vectorize/VectorizeDocumentTest.java
@@ -23,56 +23,62 @@
 import static org.junit.jupiter.api.Assertions.assertAll;
 
 class VectorizeDocumentTest extends AbstractBaseDocumentTest {
-  @Autowired ProductRepository repository;
-  @Autowired EntityStream entityStream;
+  @Autowired
+  ProductRepository repository;
+  @Autowired
+  EntityStream entityStream;
 
-  @Autowired FeatureExtractor featureExtractor;
+  @Autowired
+  FeatureExtractor featureExtractor;
 
-  @BeforeEach void loadTestData() throws IOException {
+  @BeforeEach
+  void loadTestData() throws IOException {
     if (repository.count() == 0) {
       repository.save(Product.of("cat", "classpath:/images/cat.jpg",
-          "The cat (Felis catus) is a domestic species of small carnivorous mammal."));
+        "The cat (Felis catus) is a domestic species of small carnivorous mammal."));
       repository.save(Product.of("cat2", "classpath:/images/cat2.jpg",
-          "It is the only domesticated species in the family Felidae and is commonly referred to as the domestic cat or house cat"));
-      repository.save(Product.of("catdog", "classpath:/images/catdog.jpg", "This is a picture of a cat and a dog together"));
-      repository.save(Product.of("face", "classpath:/images/face.jpg", "Three years later, the coffin was still full of Jello."));
-      repository.save(Product.of("face2", "classpath:/images/face2.jpg", "The person box was packed with jelly many dozens of months later."));
+        "It is the only domesticated species in the family Felidae and is commonly referred to as the domestic cat or house cat"));
+      repository.save(
+        Product.of("catdog", "classpath:/images/catdog.jpg", "This is a picture of a cat and a dog together"));
+      repository.save(
+        Product.of("face", "classpath:/images/face.jpg", "Three years later, the coffin was still full of Jello."));
+      repository.save(Product.of("face2", "classpath:/images/face2.jpg",
+        "The person box was packed with jelly many dozens of months later."));
     }
   }
 
   @Test
   @EnabledIf(
-      expression = "#{@featureExtractor.isReady()}", //
-      loadContext = true //
-  )
+    expression = "#{@featureExtractor.isReady()}", //
+    loadContext = true //
+    )
   void testImageIsVectorized() {
     Optional cat = repository.findFirstByName("cat");
     assertAll( //
-        () -> assertThat(cat).isPresent(), //
-        () -> assertThat(cat.get()).extracting("imageEmbedding").isNotNull(), //
-        () -> assertThat(cat.get().getImageEmbedding()).hasSize(512)
-    );
+      () -> assertThat(cat).isPresent(), //
+      () -> assertThat(cat.get()).extracting("imageEmbedding").isNotNull(), //
+      () -> assertThat(cat.get().getImageEmbedding()).hasSize(512));
   }
 
   @Test
   @EnabledIf(
-      expression = "#{@featureExtractor.isReady()}", //
-      loadContext = true //
-  )
+    expression = "#{@featureExtractor.isReady()}", //
+    loadContext = true //
+    )
   void testSentenceIsVectorized() {
     Optional cat = repository.findFirstByName("cat");
     assertAll( //
-        () -> assertThat(cat).isPresent(), //
-        () -> assertThat(cat.get()).extracting("sentenceEmbedding").isNotNull()//, //
-        //() -> assertThat(cat.get().getSentenceEmbedding()).hasSize(768*Float.BYTES)
+      () -> assertThat(cat).isPresent(), //
+      () -> assertThat(cat.get()).extracting("sentenceEmbedding").isNotNull()//, //
+      //() -> assertThat(cat.get().getSentenceEmbedding()).hasSize(768*Float.BYTES)
     );
   }
 
   @Test
   @EnabledIf(
-      expression = "#{@featureExtractor.isReady()}", //
-      loadContext = true //
-  )
+    expression = "#{@featureExtractor.isReady()}", //
+    loadContext = true //
+    )
   void testKnnImageSimilaritySearch() {
     Product cat = repository.findFirstByName("cat").get();
     int K = 5;
@@ -80,21 +86,21 @@ void testKnnImageSimilaritySearch() {
     SearchStream stream = entityStream.of(Product.class);
 
     List results = stream //
-        .filter(Product$.IMAGE_EMBEDDING.knn(K, cat.getImageEmbedding())) //
-        .sorted(Product$._IMAGE_EMBEDDING_SCORE) //
-        .limit(K) //
-        .collect(Collectors.toList());
+      .filter(Product$.IMAGE_EMBEDDING.knn(K, cat.getImageEmbedding())) //
+      .sorted(Product$._IMAGE_EMBEDDING_SCORE) //
+      .limit(K) //
+      .collect(Collectors.toList());
 
     assertThat(results).hasSize(5).map(Product::getName).containsExactly( //
-       "cat", "cat2", "catdog", "face", "face2" //
+      "cat", "cat2", "catdog", "face", "face2" //
     );
   }
 
   @Test
   @EnabledIf(
-      expression = "#{@featureExtractor.isReady()}", //
-      loadContext = true //
-  )
+    expression = "#{@featureExtractor.isReady()}", //
+    loadContext = true //
+    )
   void testKnnSentenceSimilaritySearch() {
     Product cat = repository.findFirstByName("cat").get();
     int K = 5;
@@ -102,10 +108,10 @@ void testKnnSentenceSimilaritySearch() {
     SearchStream stream = entityStream.of(Product.class);
 
     List results = stream //
-        .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) //
-        .sorted(Product$._SENTENCE_EMBEDDING_SCORE) //
-        .limit(K) //
-        .collect(Collectors.toList());
+      .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) //
+      .sorted(Product$._SENTENCE_EMBEDDING_SCORE) //
+      .limit(K) //
+      .collect(Collectors.toList());
 
     assertThat(results).hasSize(5).map(Product::getName).containsExactly( //
       "cat", "cat2", "catdog", "face", "face2" //
@@ -116,7 +122,7 @@ void testKnnSentenceSimilaritySearch() {
   @EnabledIf(
     expression = "#{@featureExtractor.isReady()}", //
     loadContext = true //
-  )
+    )
   void testKnnHybridSentenceSimilaritySearch() {
     Product cat = repository.findFirstByName("cat").get();
     int K = 5;
@@ -146,7 +152,7 @@ void testKnnSentenceSimilaritySearchWithScores() {
 
     SearchStream stream = entityStream.of(Product.class);
 
-    List> results = stream //
+    List> results = stream //
       .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) //
       .sorted(Product$._SENTENCE_EMBEDDING_SCORE) //
       .limit(K) //
@@ -154,8 +160,10 @@ void testKnnSentenceSimilaritySearchWithScores() {
       .collect(Collectors.toList());
 
     assertAll( //
-      () -> assertThat(results).hasSize(5).map(Pair::getFirst).map(Product::getName).containsExactly( "cat", "cat2", "catdog", "face", "face2"), //
-      () -> assertThat(results).hasSize(5).map(Pair::getSecond).usingElementComparator(closeToComparator).containsExactly(0.0, 0.6704, 0.7162, 0.7705, 0.8107) //
+      () -> assertThat(results).hasSize(5).map(Pair::getFirst).map(Product::getName)
+        .containsExactly("cat", "cat2", "catdog", "face", "face2"), //
+      () -> assertThat(results).hasSize(5).map(Pair::getSecond).usingElementComparator(closeToComparator)
+        .containsExactly(0.0, 0.6704, 0.7162, 0.7705, 0.8107) //
     );
   }
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/AggregationAnnotationTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/AggregationAnnotationTest.java
index 3124cc6c..301290a8 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/AggregationAnnotationTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/AggregationAnnotationTest.java
@@ -5,6 +5,7 @@
 import com.redis.om.spring.AbstractBaseEnhancedRedisTest;
 import com.redis.om.spring.annotations.hash.fixtures.Game;
 import com.redis.om.spring.annotations.hash.fixtures.GameRepository;
+import org.assertj.core.api.InstanceOfAssertFactories;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -20,11 +21,15 @@
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.entry;
 
-@SuppressWarnings("SpellCheckingInspection") class AggregationAnnotationTest extends AbstractBaseEnhancedRedisTest {
-  @Autowired GameRepository repository;
-  @Autowired Gson gson;
+@SuppressWarnings("SpellCheckingInspection")
+class AggregationAnnotationTest extends AbstractBaseEnhancedRedisTest {
+  @Autowired
+  GameRepository repository;
+  @Autowired
+  Gson gson;
 
-  @BeforeEach void beforeEach() throws IOException {
+  @BeforeEach
+  void beforeEach() throws IOException {
     // Load Sample Docs
     if (repository.count() == 0) {
       try (Reader reader = Files.newBufferedReader(Paths.get("src/test/resources/data/games.json"))) {
@@ -35,10 +40,11 @@
     }
   }
 
-  @Test void testCountAggregation() {
+  @Test
+  void testCountAggregation() {
     // TODO: report - values from the aggregation get lower cased
     String[][] expectedData = { //
-        { "", "1498" }, { "Mad Catz", "43" }, { "Generic", "40" }, { "SteelSeries", "37" }, { "Logitech", "35" } //
+      { "", "1498" }, { "Mad Catz", "43" }, { "Generic", "40" }, { "SteelSeries", "37" }, { "Logitech", "35" } //
     };
 
     var result = repository.countByBrand(PageRequest.of(0, 5));
@@ -49,18 +55,19 @@
     IntStream.range(0, expectedData.length - 1).forEach(i -> {
       var row = resultAsList.get(i);
       assertThat(row).isNotNull()//
-          .isNotEmpty() //
-          .contains(entry("brand", expectedData[i][0].toLowerCase())) //
-          .contains(entry("count", expectedData[i][1])) //
-          .hasSize(2);
+        .isNotEmpty() //
+        .contains(entry("brand", expectedData[i][0].toLowerCase())) //
+        .contains(entry("count", expectedData[i][1])) //
+        .hasSize(2);
     });
   }
 
-  @Test void testMinPrice() {
+  @Test
+  void testMinPrice() {
     String[][] expectedData = { //
-        { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, { "Goliton", "15.69" },
-        { "Lenmar", "15.41" }, { "Oceantree(TM)", "12.29" }, { "Oceantree", "11.39" }, { "oooo", "10.11" },
-        { "Case Logic", "9.99" }, { "Neewer", "9.71" } //
+      { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" }, { "Goliton", "15.69" },
+      { "Lenmar", "15.41" }, { "Oceantree(TM)", "12.29" }, { "Oceantree", "11.39" }, { "oooo", "10.11" },
+      { "Case Logic", "9.99" }, { "Neewer", "9.71" } //
     };
     var result = repository.minPricesContainingSony();
     assertThat(result.getTotalResults()).isEqualTo(27);
@@ -72,11 +79,12 @@
     });
   }
 
-  @Test void testMaxPrice() {
+  @Test
+  void testMaxPrice() {
     String[][] expectedData = { //
-        { "Sony", "695.8" }, { null, "303.59" }, { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" },
-        { "Playstation", "33.6" }, { "Neewer", "15.95" }, { "Goliton", "15.69" }, { "Lenmar", "15.41" },
-        { "Oceantree", "12.45" } //
+      { "Sony", "695.8" }, { null, "303.59" }, { "Genius", "88.54" }, { "Logitech", "78.98" }, { "Monster", "69.95" },
+      { "Playstation", "33.6" }, { "Neewer", "15.95" }, { "Goliton", "15.69" }, { "Lenmar", "15.41" },
+      { "Oceantree", "12.45" } //
     };
     var result = repository.maxPricesContainingSony();
     assertThat(result.getTotalResults()).isEqualTo(27);
@@ -89,10 +97,11 @@
     });
   }
 
-  @Test void testCountDistinctByBrandHarcodedLimit() {
+  @Test
+  void testCountDistinctByBrandHarcodedLimit() {
     // value for Mad Catz doesn't match the JSON version
     String[][] expectedData = { //
-        { null, "1466" }, { "Generic", "39" }, { "SteelSeries", "37" }, { "Mad Catz", "35" }, { "Logitech", "34" } //
+      { null, "1466" }, { "Generic", "39" }, { "SteelSeries", "37" }, { "Mad Catz", "35" }, { "Logitech", "34" } //
     };
 
     var result = repository.top5countDistinctByBrand();
@@ -106,40 +115,44 @@
     });
   }
 
-  @Test void testQuantiles() {
+  @Test
+  void testQuantiles() {
     String[][] expectedData = { //
-        { "q50","19.22" }, { "q90","95.91" }, { "q95", "144.96" }, { "__generated_aliasavgprice","29.7105941255" }, { "rowcount","1498" } //
+      { "q50", "19.22" }, { "q90", "95.91" }, { "q95", "144.96" }, { "__generated_aliasavgprice", "29.7105941255" },
+      { "rowcount", "1498" } //
     };
 
     var result = repository.priceQuantiles();
     assertThat(result.getTotalResults()).isEqualTo(293);
 
     var row = result.getRow(0);
-    IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
+    IntStream.range(0, expectedData.length - 1)
+      .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
   }
 
-  @Test void testPriceStdDev() {
+  @Test
+  void testPriceStdDev() {
     String[][][] expectedData = { //
-        { { "brand", null }, { "stddev(price)", "58.0682859441" }, { "avgPrice", "29.7105941255" },
-            { "q50Price", "19.22" }, { "rowcount", "1498" } }, //
-        { { "brand", "Mad Catz" }, { "stddev(price)", "63.3626941047" }, { "avgPrice", "92.4065116279" },
-            { "q50Price", "84.99" }, { "rowcount", "43" } }, //
-        { { "brand", "Generic" }, { "stddev(price)", "13.0528444292" }, { "avgPrice", "12.439" },
-            { "q50Price", "6.69" }, { "rowcount", "40" } }, //
-        { { "brand", "SteelSeries" }, { "stddev(price)", "44.5684434629" }, { "avgPrice", "50.0302702703" },
-            { "q50Price", "39.69" }, { "rowcount", "37" } }, //
-        { { "brand", "Logitech" }, { "stddev(price)", "48.016387201" }, { "avgPrice", "66.5488571429" },
-            { "q50Price", "55" }, { "rowcount", "35" } }, //
-        { { "brand", "Razer" }, { "stddev(price)", "49.0284634692" }, { "avgPrice", "98.4069230769" },
-            { "q50Price", "80.49" }, { "rowcount", "26" } }, //
-        { { "brand", "" }, { "stddev(price)", "11.6611915524" }, { "avgPrice", "13.711" }, { "q50Price", "10" },
-            { "rowcount", "20" } }, //
-        { { "brand", "ROCCAT" }, { "stddev(price)", "71.1336876222" }, { "avgPrice", "86.231" },
-            { "q50Price", "58.72" }, { "rowcount", "20" } }, //
-        { { "brand", "Sony" }, { "stddev(price)", "195.848045202" }, { "avgPrice", "109.536428571" },
-            { "q50Price", "44.95" }, { "rowcount", "14" } }, //
-        { { "brand", "Nintendo" }, { "stddev(price)", "71.1987671314" }, { "avgPrice", "53.2792307692" },
-            { "q50Price", "17.99" }, { "rowcount", "13" } } //
+      { { "brand", null }, { "stddev(price)", "58.0682859441" }, { "avgPrice", "29.7105941255" },
+        { "q50Price", "19.22" }, { "rowcount", "1498" } }, //
+      { { "brand", "Mad Catz" }, { "stddev(price)", "63.3626941047" }, { "avgPrice", "92.4065116279" },
+        { "q50Price", "84.99" }, { "rowcount", "43" } }, //
+      { { "brand", "Generic" }, { "stddev(price)", "13.0528444292" }, { "avgPrice", "12.439" }, { "q50Price", "6.69" },
+        { "rowcount", "40" } }, //
+      { { "brand", "SteelSeries" }, { "stddev(price)", "44.5684434629" }, { "avgPrice", "50.0302702703" },
+        { "q50Price", "39.69" }, { "rowcount", "37" } }, //
+      { { "brand", "Logitech" }, { "stddev(price)", "48.016387201" }, { "avgPrice", "66.5488571429" },
+        { "q50Price", "55" }, { "rowcount", "35" } }, //
+      { { "brand", "Razer" }, { "stddev(price)", "49.0284634692" }, { "avgPrice", "98.4069230769" },
+        { "q50Price", "80.49" }, { "rowcount", "26" } }, //
+      { { "brand", "" }, { "stddev(price)", "11.6611915524" }, { "avgPrice", "13.711" }, { "q50Price", "10" },
+        { "rowcount", "20" } }, //
+      { { "brand", "ROCCAT" }, { "stddev(price)", "71.1336876222" }, { "avgPrice", "86.231" }, { "q50Price", "58.72" },
+        { "rowcount", "20" } }, //
+      { { "brand", "Sony" }, { "stddev(price)", "195.848045202" }, { "avgPrice", "109.536428571" },
+        { "q50Price", "44.95" }, { "rowcount", "14" } }, //
+      { { "brand", "Nintendo" }, { "stddev(price)", "71.1987671314" }, { "avgPrice", "53.2792307692" },
+        { "q50Price", "17.99" }, { "rowcount", "13" } } //
     };
 
     var result = repository.priceStdDev();
@@ -155,74 +168,77 @@
     });
   }
 
-
-  @Test void testParseTime() {
+  @Test
+  void testParseTime() {
     String[][] expectedData = { //
-        { "brand", "" }, { "count", "20" }, { "dt", "2018-01-31T16:45:44Z" }, { "parsed_dt", "1517417144" } //
+      { "brand", "" }, { "count", "20" }, { "dt", "2018-01-31T16:45:44Z" }, { "parsed_dt", "1517417144" } //
     };
 
     var result = repository.parseTime();
     assertThat(result.getTotalResults()).isEqualTo(293);
 
     var row = result.getRow(0);
-    IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
+    IntStream.range(0, expectedData.length - 1)
+      .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
   }
 
-  @Test void testRandomSample() {
+  @Test
+  void testRandomSample() {
     var result = repository.randomSample();
     assertThat(result.getTotalResults()).isEqualTo(293);
 
     result.getResults().forEach(row -> {
       assertThat(row).isNotNull()//
-          .isNotEmpty() //
-          .containsKey("sample") //
-          .hasSize(3);
+        .isNotEmpty() //
+        .containsKey("sample") //
+        .hasSize(3);
 
-      assertThat(row.get("sample")).asList().hasSizeBetween(1, 10);
+      assertThat(row.get("sample")).asInstanceOf(InstanceOfAssertFactories.LIST).hasSizeBetween(1, 10);
     });
   }
 
-  @Test void testTimeFunctions() {
+  @Test
+  void testTimeFunctions() {
     String[][] expectedData = { //
-        { "dt", "1517417144" }, { "timefmt", "2018-01-31T16:45:44Z" }, { "day", "1517356800" },
-        { "hour", "1517414400" }, { "minute", "1517417100" }, { "month", "1514764800" }, { "dayofweek", "3" },
-        { "dayofmonth", "31" }, //
-        { "dayofyear", "30" }, { "year", "2018" } //
+      { "dt", "1517417144" }, { "timefmt", "2018-01-31T16:45:44Z" }, { "day", "1517356800" }, { "hour", "1517414400" },
+      { "minute", "1517417100" }, { "month", "1514764800" }, { "dayofweek", "3" }, { "dayofmonth", "31" }, //
+      { "dayofyear", "30" }, { "year", "2018" } //
     };
 
     var result = repository.timeFunctions();
     assertThat(result.getTotalResults()).isEqualTo(1);
 
     var row = result.getRow(0);
-    IntStream.range(0, expectedData.length - 1).forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
+    IntStream.range(0, expectedData.length - 1)
+      .forEach(i -> assertThat(row.getString(expectedData[i][0])).isEqualTo(expectedData[i][1]));
   }
 
-  @Test void testStringFormat() {
+  @Test
+  void testStringFormat() {
     String[][][] expectedData = { //
-        { { "title", "mad catz mov088150/04/1 ps3 s-video cable" },
-            { "titleBrand", "mad catz mov088150/04/1 ps3 s-video cable|(null)|Mark|0" } }, //
-        { { "title", "franklin sdm-500224hsmp 2002 stedman's medical dictionary springboard module" }, { "titleBrand",
-            "franklin sdm-500224hsmp 2002 stedman's medical dictionary springboard module|(null)|Mark|94.99" } }, //
-        { { "title", "razer deathstalker ultimate gaming keyboard" },
-            { "titleBrand", "razer deathstalker ultimate gaming keyboard|razer|Mark|255.35" } }, //
-        { { "title", "igadgitz blue eva hard case cover for nintendo 2ds" },
-            { "titleBrand", "igadgitz blue eva hard case cover for nintendo 2ds|(null)|Mark|6.99" } }, //
-        { { "title",
-            "buddies model wl2021 2.4 ghz wireless gamepad controller for pc/ps1/ps2/ps3 with rechargable lithium battery with one year warranty" },
-            { "titleBrand",
-                "buddies model wl2021 2.4 ghz wireless gamepad controller for pc/ps1/ps2/ps3 with rechargable lithium battery with one year warranty|(null)|Mark|19.95" } },
-        //
-        { { "title", "saitek x52 pro flight system controller" },
-            { "titleBrand", "saitek x52 pro flight system controller|(null)|Mark|144.96" } }, //
-        { { "title", "ideazon reaper gaming mouse" }, { "titleBrand", "ideazon reaper gaming mouse|(null)|Mark|0" } },
-        //
-        { { "title", "innovations 7-38012-48713-6 nes game pad" },
-            { "titleBrand", "innovations 7-38012-48713-6 nes game pad|micro innovations|Mark|5.23" } }, //
-        { { "title", "neuros mpeg-4 recorder 2 plus digital video recorder" },
-            { "titleBrand", "neuros mpeg-4 recorder 2 plus digital video recorder|(null)|Mark|79.64" } }, //
-        { { "title", "logitech cordless rumblepad 2 with vibration feedback (black)" },
-            { "titleBrand", "logitech cordless rumblepad 2 with vibration feedback (black)|(null)|Mark|31.79" } }
-    };
+      { { "title", "mad catz mov088150/04/1 ps3 s-video cable" },
+        { "titleBrand", "mad catz mov088150/04/1 ps3 s-video cable|(null)|Mark|0" } }, //
+      { { "title", "franklin sdm-500224hsmp 2002 stedman's medical dictionary springboard module" }, { "titleBrand",
+        "franklin sdm-500224hsmp 2002 stedman's medical dictionary springboard module|(null)|Mark|94.99" } }, //
+      { { "title", "razer deathstalker ultimate gaming keyboard" },
+        { "titleBrand", "razer deathstalker ultimate gaming keyboard|razer|Mark|255.35" } }, //
+      { { "title", "igadgitz blue eva hard case cover for nintendo 2ds" },
+        { "titleBrand", "igadgitz blue eva hard case cover for nintendo 2ds|(null)|Mark|6.99" } }, //
+      { { "title",
+        "buddies model wl2021 2.4 ghz wireless gamepad controller for pc/ps1/ps2/ps3 with rechargable lithium battery with one year warranty" },
+        { "titleBrand",
+          "buddies model wl2021 2.4 ghz wireless gamepad controller for pc/ps1/ps2/ps3 with rechargable lithium battery with one year warranty|(null)|Mark|19.95" } },
+      //
+      { { "title", "saitek x52 pro flight system controller" },
+        { "titleBrand", "saitek x52 pro flight system controller|(null)|Mark|144.96" } }, //
+      { { "title", "ideazon reaper gaming mouse" }, { "titleBrand", "ideazon reaper gaming mouse|(null)|Mark|0" } },
+      //
+      { { "title", "innovations 7-38012-48713-6 nes game pad" },
+        { "titleBrand", "innovations 7-38012-48713-6 nes game pad|micro innovations|Mark|5.23" } }, //
+      { { "title", "neuros mpeg-4 recorder 2 plus digital video recorder" },
+        { "titleBrand", "neuros mpeg-4 recorder 2 plus digital video recorder|(null)|Mark|79.64" } }, //
+      { { "title", "logitech cordless rumblepad 2 with vibration feedback (black)" },
+        { "titleBrand", "logitech cordless rumblepad 2 with vibration feedback (black)|(null)|Mark|31.79" } } };
 
     var result = repository.stringFormat();
     assertThat(result.getTotalResults()).isEqualTo(2218);
@@ -237,13 +253,14 @@
     });
   }
 
-  @Test void testSumPrice() {
+  @Test
+  void testSumPrice() {
     String[][][] expectedData = { //
-        { { "brand", null }, { "count", "1498" }, { "sum(price)", "44506.47" } }, //
-        { { "brand", "Mad Catz" }, { "count", "43" }, { "sum(price)", "3973.48" } }, //
-        { { "brand", "Razer" }, { "count", "26" }, { "sum(price)", "2558.58" } }, //
-        { { "brand", "Logitech" }, { "count", "35" }, { "sum(price)", "2329.21" } }, //
-        { { "brand", "SteelSeries" }, { "count", "37" }, { "sum(price)", "1851.12" } }, //
+      { { "brand", null }, { "count", "1498" }, { "sum(price)", "44506.47" } }, //
+      { { "brand", "Mad Catz" }, { "count", "43" }, { "sum(price)", "3973.48" } }, //
+      { { "brand", "Razer" }, { "count", "26" }, { "sum(price)", "2558.58" } }, //
+      { { "brand", "Logitech" }, { "count", "35" }, { "sum(price)", "2329.21" } }, //
+      { { "brand", "SteelSeries" }, { "count", "37" }, { "sum(price)", "1851.12" } }, //
     };
 
     var result = repository.sumPrice();
@@ -259,7 +276,8 @@
     });
   }
 
-  @Test void testFilters() {
+  @Test
+  void testFilters() {
     var result = repository.filters();
     assertThat(result.getTotalResults()).isEqualTo(293);
 
@@ -269,29 +287,31 @@
     });
   }
 
-  @Test void testToList() {
+  @Test
+  void testToList() {
     var result = repository.toList();
     assertThat(result.getTotalResults()).isEqualTo(293);
 
     IntStream.range(0, result.getResults().size() - 1).forEach(i -> {
       var row = result.getRow(i);
       var prices = result.getResults().get(i).get("prices");
-      assertThat(prices).asList().hasSize(Math.toIntExact(row.getLong("count")));
+      assertThat(prices).asInstanceOf(InstanceOfAssertFactories.LIST).hasSize(Math.toIntExact(row.getLong("count")));
     });
   }
 
-  @Test void testSortByMany() {
+  @Test
+  void testSortByMany() {
     String[][][] expectedData = { //
-        { { "brand", "Myiico" }, { "price", "0" } }, //
-        { { "brand", "Crystal Dynamics" }, { "price" } }, //
-        { { "brand", "yooZoo" }, { "price", "0" } }, //
-        { { "brand", "Century Accessory" }, { "price", "1" } }, //
-        { { "brand", "sumoto" }, { "price", "1" } }, //
-        { { "brand", "eGames" }, { "price", "1" } }, //
-        { { "brand", "Veecome" }, { "price", "1" } }, //
-        { { "brand", "Wimex" }, { "price", "1" } }, //
-        { { "brand", "gospel-online" }, { "price", "1" } }, //
-        { { "brand", "ETHAHE" }, { "price", "1" } }, //
+      { { "brand", "Myiico" }, { "price", "0" } }, //
+      { { "brand", "Crystal Dynamics" }, { "price" } }, //
+      { { "brand", "yooZoo" }, { "price", "0" } }, //
+      { { "brand", "Century Accessory" }, { "price", "1" } }, //
+      { { "brand", "sumoto" }, { "price", "1" } }, //
+      { { "brand", "eGames" }, { "price", "1" } }, //
+      { { "brand", "Veecome" }, { "price", "1" } }, //
+      { { "brand", "Wimex" }, { "price", "1" } }, //
+      { { "brand", "gospel-online" }, { "price", "1" } }, //
+      { { "brand", "ETHAHE" }, { "price", "1" } }, //
     };
 
     var result = repository.sortByMany();
@@ -299,37 +319,43 @@
 
     IntStream.range(0, expectedData.length - 1).forEach(i -> {
       var row = result.getRow(i);
-      IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1].toLowerCase()));
+      IntStream.range(0, expectedData[i].length - 1)
+        .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1].toLowerCase()));
     });
   }
 
-  @Test void testLoadWithSort() {
+  @Test
+  void testLoadWithSort() {
     String[][][] expectedData = { //
-        { { "title", "Logitech MOMO Racing - Wheel and pedals set - 6 button(s) - PC, MAC - black" }, { "price", "759.12" } }, //
-        { { "title", "Sony PSP Slim & Lite 2000 Console" }, { "price", "695.8" } }, //
+      { { "title", "Logitech MOMO Racing - Wheel and pedals set - 6 button(s) - PC, MAC - black" },
+        { "price", "759.12" } }, //
+      { { "title", "Sony PSP Slim & Lite 2000 Console" }, { "price", "695.8" } }, //
     };
     var result = repository.loadWithSort();
     assertThat(result.getTotalResults()).isEqualTo(2265);
 
     IntStream.range(0, expectedData.length - 1).forEach(i -> {
       var row = result.getRow(i);
-      IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1]));
+      IntStream.range(0, expectedData[i].length - 1)
+        .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1]));
     });
   }
 
-  @Test void testLoadWithDocId() {
+  @Test
+  void testLoadWithDocId() {
     String[][][] expectedData = { //
-        { { "__key", "games:B00006JJIC" }, { "price", "759.12" } }, //
-        { { "__key", "games:B000F6W1AG" }, { "price", "695.8" } }, //
-        { { "__key", "games:B00002JXBD" }, { "price", "599.99" } }, //
-        { { "__key", "games:B00006IZIL" }, { "price", "759.12" } }, //
+      { { "__key", "games:B00006JJIC" }, { "price", "759.12" } }, //
+      { { "__key", "games:B000F6W1AG" }, { "price", "695.8" } }, //
+      { { "__key", "games:B00002JXBD" }, { "price", "599.99" } }, //
+      { { "__key", "games:B00006IZIL" }, { "price", "759.12" } }, //
     };
     var result = repository.loadWithDocId();
     assertThat(result.getTotalResults()).isEqualTo(2265);
 
     IntStream.range(0, expectedData.length - 1).forEach(i -> {
       var row = result.getRow(i);
-      IntStream.range(0, expectedData[i].length - 1).forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1]));
+      IntStream.range(0, expectedData[i].length - 1)
+        .forEach(j -> assertThat(row.getString(expectedData[i][j][0])).isEqualTo(expectedData[i][j][1]));
     });
   }
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/BasicRedisHashMappingTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/BasicRedisHashMappingTest.java
index 2d77e0cb..97351840 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/BasicRedisHashMappingTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/BasicRedisHashMappingTest.java
@@ -32,7 +32,8 @@
 import static org.junit.jupiter.api.Assertions.*;
 import static org.testcontainers.shaded.org.awaitility.Awaitility.with;
 
-@SuppressWarnings("SpellCheckingInspection") class BasicRedisHashMappingTest extends AbstractBaseEnhancedRedisTest {
+@SuppressWarnings("SpellCheckingInspection")
+class BasicRedisHashMappingTest extends AbstractBaseEnhancedRedisTest {
   static Person john;
   static Person gray;
   static Person terryg;
@@ -72,8 +73,8 @@ void createTestDataIfNeeded() {
     terryg.setFavoriteFoods(Set.of("Shepherd’s Pie", "Cottage Pie", "Steak and Kidney Pie"));
 
     eric = Person.of("Eric Idle", "eric.idle@mp.com", "eric");
-    eric.setRoles(Set.of("Sir Robin the-not-quite-so-brave-as-Sir-Lancelot", "Lancelot's squire Concorde",
-        "Roger the Shrubber"));
+    eric.setRoles(
+      Set.of("Sir Robin the-not-quite-so-brave-as-Sir-Lancelot", "Lancelot's squire Concorde", "Roger the Shrubber"));
     eric.setFavoriteFoods(Set.of("Cottage Pie", "Steak and Kidney Pie"));
 
     terryj = Person.of("Terry Jones", "terry.jones@mp.com", "terry");
@@ -89,23 +90,22 @@ void createTestDataIfNeeded() {
     studentRepository.deleteAll();
     List students = new ArrayList<>();
     for (int i = 0; i < 10; i++) {
-      students.add(
-        Student.of((long) i, "Student" + i, LocalDateTime.now()));
+      students.add(Student.of((long) i, "Student" + i, LocalDateTime.now()));
     }
     studentRepository.saveAll(students);
   }
-  
+
   @Test
   void testDeleteAll() {
     assertThat(personRepo.count()).isEqualTo(6);
     personRepo.deleteAll();
     with() //
-     .pollInterval(Duration.ofMillis(100)).and() //
-         .with().pollDelay(20, MILLISECONDS) //
-        .await("repository cleared").until(() -> personRepo.count() == 0);
+      .pollInterval(Duration.ofMillis(100)).and() //
+      .with().pollDelay(20, MILLISECONDS) //
+      .await("repository cleared").until(() -> personRepo.count() == 0);
     assertThat(personRepo.count()).isZero();
   }
-  
+
   @Test
   void testDeleteOne() {
     assertThat(personRepo.count()).isEqualTo(6);
@@ -119,7 +119,7 @@ void testThatIndexedSimpleCollectionsAreSerializedAsCSV() {
     String hashKey = "people:" + eric.getId();
     String ericRolesRaw = Objects.requireNonNull(template.opsForHash().get(hashKey, "roles")).toString();
     Set ericRoles = Arrays.asList(ericRolesRaw.split("\\|")).stream().map(Object::toString)
-        .map(QueryUtils::unescape).collect(Collectors.toSet());
+      .map(QueryUtils::unescape).collect(Collectors.toSet());
     assertThat(ericRoles).containsExactlyInAnyOrderElementsOf(eric.getRoles());
   }
 
@@ -154,14 +154,14 @@ void testByTags() {
   @Test
   void testAggregationAnnotation01() {
     AggregationResult results = personRepo.allNamesInUppercase();
-    List upcasedNames = results.getResults().stream().map(m -> m.get("upcasedName"))
-        .map(Object::toString).toList();
+    List upcasedNames = results.getResults().stream().map(m -> m.get("upcasedName")).map(Object::toString)
+      .toList();
     assertThat(upcasedNames).containsExactlyInAnyOrder("JOHN CLEESE", //
-        "GRAHAM CHAPMAN", //
-        "TERRY GILLIAM", //
-        "ERIC IDLE", //
-        "TERRY JONES", //
-        "MICHAEL PALIN" //
+      "GRAHAM CHAPMAN", //
+      "TERRY GILLIAM", //
+      "ERIC IDLE", //
+      "TERRY JONES", //
+      "MICHAEL PALIN" //
     );
   }
 
@@ -172,9 +172,10 @@ void testAggregationAnnotation01() {
   @Test
   void testBasicCrudOperations() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
 
     assertEquals(2, companyRepo.count());
 
@@ -201,26 +202,28 @@ void testBasicCrudOperations() {
   @Test
   void testFindAllById() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
 
     assertEquals(2, companyRepo.count());
 
     Iterable companies = companyRepo.findAllById(List.of(redis.getId(), microsoft.getId()));
 
     assertAll( //
-        () -> assertThat(companies).hasSize(2), //
-        () -> assertThat(companies).containsExactly(redis, microsoft) //
+      () -> assertThat(companies).hasSize(2), //
+      () -> assertThat(companies).containsExactly(redis, microsoft) //
     );
   }
 
   @Test
   void testAuditAnnotations() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
 
     // created dates should not be null
     assertNotNull(redis.getCreatedDate());
@@ -230,7 +233,7 @@ void testAuditAnnotations() {
     assertNull(redis.getLastModifiedDate());
     assertNull(microsoft.getLastModifiedDate());
 
-    companyRepo.saveAll(List.of(redis,microsoft));
+    companyRepo.saveAll(List.of(redis, microsoft));
 
     // last modified dates should not be null after a second save
     assertNotNull(redis.getLastModifiedDate());
@@ -240,9 +243,10 @@ void testAuditAnnotations() {
   @Test
   void testTagEscapeChars() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
 
     assertEquals(2, companyRepo.count());
 
@@ -276,7 +280,7 @@ void testMaxQueryReturnMaxDefaultsTo10000() {
     final List bunchOfCompanies = new ArrayList<>();
     IntStream.range(1, 100).forEach(i -> {
       Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-          "company" + i + "@inc.com");
+        "company" + i + "@inc.com");
       if (i % 2 == 0)
         c.setPubliclyListed(true);
       bunchOfCompanies.add(c);
@@ -287,23 +291,24 @@ void testMaxQueryReturnMaxDefaultsTo10000() {
 
     //noinspection ResultOfMethodCallIgnored
     assertAll( //
-        () -> assertThat(publiclyListed).hasSize(49), //
-        () -> assertThat(publiclyListed).allSatisfy(Company::isPubliclyListed) //
+      () -> assertThat(publiclyListed).hasSize(49), //
+      () -> assertThat(publiclyListed).allSatisfy(Company::isPubliclyListed) //
     );
   }
 
   @Test
   void testFindByTagsIn() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
     redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql"));
 
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
     microsoft.setTags(Set.of("innovative", "reliable", "os", "ai"));
 
     Company tesla = companyRepo.save(
-        Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
+      Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
     tesla.setTags(Set.of("innovative", "futuristic", "ai"));
 
     companyRepo.saveAll(List.of(redis, microsoft, tesla));
@@ -322,7 +327,7 @@ void testBasicPagination() {
     final List bunchOfCompanies = new ArrayList<>();
     IntStream.range(1, 25).forEach(i -> {
       Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-          "company" + i + "@inc.com");
+        "company" + i + "@inc.com");
       bunchOfCompanies.add(c);
     });
     companyRepo.saveAll(bunchOfCompanies);
@@ -341,7 +346,7 @@ void testBasicPaginationWithSorting() {
     final List bunchOfCompanies = new ArrayList<>();
     IntStream.range(1, 25).forEach(i -> {
       Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-          "company" + i + "@inc.com");
+        "company" + i + "@inc.com");
       bunchOfCompanies.add(c);
     });
     companyRepo.saveAll(bunchOfCompanies);
@@ -363,7 +368,7 @@ void testFindAllWithSorting() {
     final List bunchOfCompanies = new ArrayList<>();
     IntStream.range(1, 25).forEach(i -> {
       Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-          "company" + i + "@inc.com");
+        "company" + i + "@inc.com");
       bunchOfCompanies.add(c);
     });
     companyRepo.saveAll(bunchOfCompanies);
@@ -371,7 +376,7 @@ void testFindAllWithSorting() {
     Iterable result = companyRepo.findAll(Sort.by("name").ascending());
 
     List companyNames = StreamSupport.stream(result.spliterator(), false).map(Company::getName)
-        .collect(Collectors.toList());
+      .collect(Collectors.toList());
     assertThat(Ordering.natural().isOrdered(companyNames)).isTrue();
   }
 
@@ -402,7 +407,8 @@ void testFindAllWithSortingByIdUsingMetamodel() {
     });
     companyRepo.saveAll(bunchOfCompanies);
 
-    Iterable result = companyRepo.findAll(com.redis.om.spring.repository.query.Sort.by(Company$.ID).ascending());
+    Iterable result = companyRepo.findAll(
+      com.redis.om.spring.repository.query.Sort.by(Company$.ID).ascending());
 
     List ids = StreamSupport.stream(result.spliterator(), false).map(Company::getId)
       .collect(Collectors.toList());
@@ -430,21 +436,22 @@ void testBasicPaginationForNonIndexedEntity() {
   @Test
   void testTagValsQuery() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
     redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql"));
 
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
     microsoft.setTags(Set.of("innovative", "reliable", "os", "ai"));
 
     Company tesla = companyRepo.save(
-        Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
+      Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
     tesla.setTags(Set.of("innovative", "futuristic", "ai"));
 
     companyRepo.saveAll(List.of(redis, microsoft, tesla));
 
     Set allTags = Set.of("fast", "scalable", "reliable", "database", "nosql", "innovative", "os", "ai",
-        "futuristic");
+      "futuristic");
 
     Iterable tags = companyRepo.getAllTags();
     assertThat(tags).containsAll(allTags);
@@ -453,15 +460,16 @@ void testTagValsQuery() {
   @Test
   void testFullTextSearch() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
     redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql"));
 
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
     microsoft.setTags(Set.of("innovative", "reliable", "os", "ai"));
 
     Company tesla = companyRepo.save(
-        Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
+      Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
     tesla.setTags(Set.of("innovative", "futuristic", "ai"));
 
     companyRepo.saveAll(List.of(redis, microsoft, tesla));
@@ -474,15 +482,16 @@ void testFullTextSearch() {
   @Test
   void testFindByFieldWithExplicitGeoIndexedAnnotation() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
     redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql"));
 
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
     microsoft.setTags(Set.of("innovative", "reliable", "os", "ai"));
 
     Company tesla = companyRepo.save(
-        Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
+      Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com"));
     tesla.setTags(Set.of("innovative", "futuristic", "ai"));
 
     companyRepo.saveAll(List.of(redis, microsoft, tesla));
@@ -499,7 +508,7 @@ void testFindAllUnpaged() {
     final List bunchOfCompanies = new ArrayList<>();
     IntStream.range(1, 5).forEach(i -> {
       Company c = Company.of("Company" + i, 2022, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-          "company" + i + "@inc.com");
+        "company" + i + "@inc.com");
       bunchOfCompanies.add(c);
     });
     companyRepo.saveAll(bunchOfCompanies);
@@ -514,7 +523,7 @@ void testFindAllUnpaged() {
   @Test
   void testUpdateSingleField() {
     Company redisInc = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
     companyRepo.updateField(redisInc, Company$.NAME, "Redis");
 
     Optional maybeRedis = companyRepo.findById(redisInc.getId());
@@ -527,18 +536,21 @@ void testUpdateSingleField() {
   @Test
   void testGetFieldsByIds() {
     Company redis = companyRepo.save(
-        Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
-    Company microsoft = companyRepo.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com"));
+      Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com"));
+    Company microsoft = companyRepo.save(
+      Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+        "research@microsoft.com"));
 
     Iterable ids = List.of(redis.getId(), microsoft.getId());
     Iterable companyNames = companyRepo.getFieldsByIds(ids, Company$.NAME);
     assertThat(companyNames).containsExactly(redis.getName(), microsoft.getName());
   }
 
-  @SuppressWarnings("ConstantConditions") @Test
+  @SuppressWarnings("ConstantConditions")
+  @Test
   void testPersistingEntityMustNotBeNull() {
-    IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> companyRepo.save(null));
+    IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class,
+      () -> companyRepo.save(null));
 
     Assertions.assertEquals("Entity must not be null", exception.getMessage());
   }
@@ -546,9 +558,9 @@ void testPersistingEntityMustNotBeNull() {
   @Test
   void testAuditAnnotationsOnSaveAll() {
     Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-        "stack@redis.com");
+      "stack@redis.com");
     Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
-        "research@microsoft.com");
+      "research@microsoft.com");
 
     companyRepo.saveAll(List.of(redis, microsoft));
 
@@ -561,21 +573,21 @@ void testAuditAnnotationsOnSaveAll() {
     Iterable companies = companyRepo.findAllById(List.of(redis.getId(), microsoft.getId()));
 
     assertAll( //
-        () -> assertThat(companies).hasSize(2), //
-        () -> assertThat(companies).containsExactly(redis, microsoft), //
-        () -> assertThat(redis.getCreatedDate()).isNotNull(), //
-        () -> assertThat(redis.getLastModifiedDate()).isNull(), //
-        () -> assertThat(microsoft.getCreatedDate()).isNotNull(), //
-        () -> assertThat(microsoft.getLastModifiedDate()).isNotNull());
+      () -> assertThat(companies).hasSize(2), //
+      () -> assertThat(companies).containsExactly(redis, microsoft), //
+      () -> assertThat(redis.getCreatedDate()).isNotNull(), //
+      () -> assertThat(redis.getLastModifiedDate()).isNull(), //
+      () -> assertThat(microsoft.getCreatedDate()).isNotNull(), //
+      () -> assertThat(microsoft.getLastModifiedDate()).isNotNull());
   }
 
   @Test
   void testFindByTagValueStartingWith() {
     Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-        "stack@redis.com");
+      "stack@redis.com");
 
-    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com");
+    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+      "research@microsoft.com");
 
     companyRepo.saveAll(List.of(redis, microsoft));
 
@@ -585,18 +597,18 @@ void testFindByTagValueStartingWith() {
     List shouldBeOnlyMS = companyRepo.findByEmailStartingWith("res");
 
     assertAll( //
-        () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
-        () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") //
+      () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
+      () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") //
     );
   }
 
   @Test
   void testFindByTagValueEndingWith() {
     Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-        "stack@redis.com");
+      "stack@redis.com");
 
-    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com");
+    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+      "research@microsoft.com");
 
     companyRepo.saveAll(List.of(redis, microsoft));
 
@@ -606,30 +618,28 @@ void testFindByTagValueEndingWith() {
     List shouldBeOnlyMS = companyRepo.findByEmailEndingWith("t.com");
 
     assertAll( //
-        () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
-        () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") //
+      () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
+      () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft") //
     );
   }
 
   @Test
   void testOrderByInMethodName() {
     companyRepo.saveAll(
-        List.of(
-            Company.of("aaa", 2000, LocalDate.of(2020, 5, 1), new Point(-122.066540, 37.377690), "aaa@aaa.com"),
-            Company.of("bbb", 2000, LocalDate.of(2021, 6, 2), new Point(-122.066540, 37.377690), "bbb@bbb.com"),
-            Company.of("ccc", 2000, LocalDate.of(2022, 7, 3), new Point(-122.066540, 37.377690), "ccc@ccc.com")
-        ));
+      List.of(Company.of("aaa", 2000, LocalDate.of(2020, 5, 1), new Point(-122.066540, 37.377690), "aaa@aaa.com"),
+        Company.of("bbb", 2000, LocalDate.of(2021, 6, 2), new Point(-122.066540, 37.377690), "bbb@bbb.com"),
+        Company.of("ccc", 2000, LocalDate.of(2022, 7, 3), new Point(-122.066540, 37.377690), "ccc@ccc.com")));
 
     List byNameAsc = companyRepo.findByYearFoundedOrderByNameAsc(2000);
     List byNameDesc = companyRepo.findByYearFoundedOrderByNameDesc(2000);
 
     assertAll( //
-        () -> assertThat(byNameAsc).extracting("name").containsExactly("aaa", "bbb", "ccc"),
-        () -> assertThat(byNameDesc).extracting("name").containsExactly("ccc", "bbb", "aaa")
-    );
+      () -> assertThat(byNameAsc).extracting("name").containsExactly("aaa", "bbb", "ccc"),
+      () -> assertThat(byNameDesc).extracting("name").containsExactly("ccc", "bbb", "aaa"));
   }
 
-  @Test void testEnumsAreIndexed() {
+  @Test
+  void testEnumsAreIndexed() {
     HashWithEnum doc1 = HashWithEnum.of(MyJavaEnum.VALUE_1);
     HashWithEnum doc2 = HashWithEnum.of(MyJavaEnum.VALUE_2);
     HashWithEnum doc3 = HashWithEnum.of(MyJavaEnum.VALUE_3);
@@ -641,9 +651,9 @@ void testOrderByInMethodName() {
     List onlyVal3 = hashWithEnumRepository.findByEnumProp(MyJavaEnum.VALUE_3);
 
     assertAll( //
-        () -> assertThat(onlyVal1).containsExactly(doc1), //
-        () -> assertThat(onlyVal2).containsExactly(doc2), //
-        () -> assertThat(onlyVal3).containsExactly(doc3)  //
+      () -> assertThat(onlyVal1).containsExactly(doc1), //
+      () -> assertThat(onlyVal2).containsExactly(doc2), //
+      () -> assertThat(onlyVal3).containsExactly(doc3)  //
     );
   }
 
@@ -652,8 +662,8 @@ void testFindByPropertyWithAliasWithHyphens() {
     List result = studentRepository.findByUserName("Student2");
 
     assertAll( //
-      () -> assertThat(result).hasSize(1),
-      () -> assertThat(result).extracting("userName").containsExactly("Student2") //
+      () -> assertThat(result).hasSize(1), () -> assertThat(result).extracting("userName").containsExactly("Student2")
+      //
     );
   }
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/ExplicitPrefixesHashTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/ExplicitPrefixesHashTest.java
index 5bee6b84..c33db20c 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/ExplicitPrefixesHashTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/ExplicitPrefixesHashTest.java
@@ -68,7 +68,8 @@ void testKeyGenerationWithCustomPrefixWithColon() {
     }
   }
 
-  @Test void testFindByIdForCustomPrefixWithColon() {
+  @Test
+  void testFindByIdForCustomPrefixWithColon() {
     Optional maybePanama = hashWithColonInPrefixRepository.findById("Panama");
     assertThat(maybePanama).isPresent();
   }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashQueryByExampleTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashQueryByExampleTest.java
index bbe3e00a..9ea55d51 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashQueryByExampleTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashQueryByExampleTest.java
@@ -77,11 +77,11 @@ void loadTestData() {
 
     companyRepository.deleteAll();
     Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690),
-        "stack@redis.com");
+      "stack@redis.com");
     redis.setTags(Set.of("RedisTag", "CommonTag"));
 
-    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15),
-        new Point(-122.124500, 47.640160), "research@microsoft.com");
+    Company microsoft = Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160),
+      "research@microsoft.com");
     microsoft.setTags(Set.of("MsTag", "CommonTag"));
 
     companyRepository.saveAll(List.of(redis, microsoft));
@@ -256,8 +256,7 @@ void testFindByTextPropertyStartingWith() {
     MyHash template = new MyHash();
     template.setTitle("hello");
 
-    ExampleMatcher matcher = ExampleMatcher.matching()
-          .withStringMatcher(StringMatcher.STARTING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.STARTING);
 
     Example example = Example.of(template, matcher);
 
@@ -271,8 +270,7 @@ void testFindByTextPropertyEndingWith() {
     MyHash template = new MyHash();
     template.setTitle("ndo");
 
-    ExampleMatcher matcher = ExampleMatcher.matching()
-        .withStringMatcher(StringMatcher.ENDING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.ENDING);
 
     Example example = Example.of(template, matcher);
 
@@ -286,8 +284,7 @@ void testFindByTextPropertyContaining() {
     MyHash template = new MyHash();
     template.setTitle("llo");
 
-    ExampleMatcher matcher = ExampleMatcher.matching()
-        .withStringMatcher(StringMatcher.CONTAINING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING);
 
     Example example = Example.of(template, matcher);
 
@@ -328,10 +325,9 @@ void testFindAllByExampleWithTags() {
     Iterable shouldBeBoth = companyRepository.findAll(bothExample);
 
     assertAll( //
-        () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
-        () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), //
-        () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc",
-            "Microsoft") //
+      () -> assertThat(shouldBeOnlyRedis).map(Company::getName).containsExactly("RedisInc"), //
+      () -> assertThat(shouldBeOnlyMS).map(Company::getName).containsExactly("Microsoft"), //
+      () -> assertThat(shouldBeBoth).map(Company::getName).containsExactlyInAnyOrder("RedisInc", "Microsoft") //
     );
   }
 
@@ -340,8 +336,7 @@ void testFindByShouldReturnFirstResult() {
     MyHash template = new MyHash();
     template.setTitle("llo");
 
-    ExampleMatcher matcher = ExampleMatcher.matching()
-        .withStringMatcher(StringMatcher.CONTAINING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING);
 
     Example example = Example.of(template, matcher);
 
@@ -361,19 +356,17 @@ void testFindByShouldReturnOneResult() {
 
     MyHash moreThanOneMatchTemplate = new MyHash();
     moreThanOneMatchTemplate.setTitle("llo");
-    ExampleMatcher matcher = ExampleMatcher.matching()
-        .withStringMatcher(StringMatcher.CONTAINING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING);
 
     assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(
-        () -> repository.findBy(Example.of(moreThanOneMatchTemplate, matcher), FluentQuery.FetchableFluentQuery::one));
+      () -> repository.findBy(Example.of(moreThanOneMatchTemplate, matcher), FluentQuery.FetchableFluentQuery::one));
   }
 
   @Test
   void testFindByShouldReturnAll() {
     MyHash template = new MyHash();
     template.setTitle("llo");
-    ExampleMatcher matcher = ExampleMatcher.matching()
-        .withStringMatcher(StringMatcher.CONTAINING);
+    ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING);
 
     List result = repository.findBy(Example.of(template, matcher), FluentQuery.FetchableFluentQuery::all);
 
@@ -385,15 +378,15 @@ void testFindByShouldApplySortAll() {
     Company probe = new Company();
 
     List result = companyRepository.findBy( //
-        Example.of(probe), //
-        it -> it.sortBy(Sort.by("name")).all() //
+      Example.of(probe), //
+      it -> it.sortBy(Sort.by("name")).all() //
     );
 
     assertThat(result).map(Company::getName).containsExactly("Microsoft", "RedisInc");
 
     result = companyRepository.findBy( //
-        Example.of(probe), //
-        it -> it.sortBy(Sort.by(Sort.Direction.DESC, "name")).all() //
+      Example.of(probe), //
+      it -> it.sortBy(Sort.by(Sort.Direction.DESC, "name")).all() //
     );
     assertThat(result).map(Company::getName).containsExactly("RedisInc", "Microsoft");
   }
@@ -404,13 +397,14 @@ void findByShouldApplyPagination() {
     template.setLocation(new Point(-122.066540, 37.377690));
 
     Page firstPage = repository.findBy(Example.of(template),
-        it -> it.page(PageRequest.of(0, 2, Sort.by("name"))));
+      it -> it.page(PageRequest.of(0, 2, Sort.by("name"))));
     assertThat(firstPage.getTotalElements()).isEqualTo(3);
     assertThat(firstPage.getContent().size()).isEqualTo(2);
-    assertThat(firstPage.getContent().stream().toList()).map(MyHash::getTitle).containsExactly("hello mundo", "ola mundo");
+    assertThat(firstPage.getContent().stream().toList()).map(MyHash::getTitle)
+      .containsExactly("hello mundo", "ola mundo");
 
     Page secondPage = repository.findBy(Example.of(template),
-        it -> it.page(PageRequest.of(1, 2, Sort.by("name"))));
+      it -> it.page(PageRequest.of(1, 2, Sort.by("name"))));
 
     assertThat(secondPage.getTotalElements()).isEqualTo(3);
     assertThat(secondPage.getContent().size()).isEqualTo(1);
@@ -460,5 +454,4 @@ void testFindByShouldApplyProjection() {
     assertThat(doc1.getTitle()).isNull();
   }
 
-
 }
diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashSearchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashSearchTest.java
index 6303eb0e..a7db2f32 100644
--- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashSearchTest.java
+++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashSearchTest.java
@@ -24,11 +24,13 @@
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.*;
 
-@SuppressWarnings("SpellCheckingInspection") class RedisHashSearchTest extends AbstractBaseEnhancedRedisTest {
+@SuppressWarnings("SpellCheckingInspection")
+class RedisHashSearchTest extends AbstractBaseEnhancedRedisTest {
   @Autowired
   MyHashRepository repository;
 
-  @Autowired StringRedisTemplate template;
+  @Autowired
+  StringRedisTemplate template;
 
   String id1;
   String id2;
@@ -86,8 +88,8 @@ void testCustomFinder() {
    * 
    * @Query("@title:$title @tag:{$tags}")
    *
-   * > FT.SEARCH idx '@title:hello @tag:{news}' 
-   * 1) (integer) 1 2) "doc1" 
+   * > FT.SEARCH idx '@title:hello @tag:{news}'
+   * 1) (integer) 1 2) "doc1"
    * 3) 1) "$"
    *    2) "{\"title\":\"hello world\",\"tag\":[\"news\",\"article\"]}"
    * 
@@ -210,8 +212,8 @@ void testFindByFieldWithExplicitGeoIndexedAnnotation() { MyHash doc = iter.next(); assertEquals("hello mundo", doc.getTitle()); - @SuppressWarnings("unused") - NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, iter::next); + @SuppressWarnings("unused") NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, + iter::next); } @Test @@ -223,8 +225,8 @@ void testFindByFieldWithIndexedGeoAnnotation() { MyHash doc = iter.next(); assertEquals("hello mundo", doc.getTitle()); - @SuppressWarnings("unused") - NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, iter::next); + @SuppressWarnings("unused") NoSuchElementException exception = Assertions.assertThrows(NoSuchElementException.class, + iter::next); } @Test @@ -235,46 +237,45 @@ void testFindByFieldWithExplicitNumericIndexedAnnotation() { assertEquals("hello world", doc.getTitle()); assertThat(doc.getTag()).containsExactlyInAnyOrder("news", "article"); } - + @Test void testQueryAnnotationWithReturnFieldsAndLimitAndOffset() { repository.deleteAll(); Point point = new Point(-122.066540, 37.377690); - repository.saveAll(List.of( - MyHash.of("predisposition", point, point, 4), // - MyHash.of("predestination", point, point, 8), // - MyHash.of("prepublication", point, point, 15), // - MyHash.of("predestinarian", point, point, 16), // - MyHash.of("preadolescence", point, point, 23), // - MyHash.of("premillenarian", point, point, 42), // - MyHash.of("precipitinogen", point, point, 4), // - MyHash.of("precipitations", point, point, 8), // - MyHash.of("precociousness", point, point, 15), // - MyHash.of("precombustions", point, point, 16), // - MyHash.of("preconditioned", point, point, 23), // - MyHash.of("preconceptions", point, point, 42), // - MyHash.of("precipitancies", point, point, 4), // - MyHash.of("preciousnesses", point, point, 8), // - MyHash.of("precentorships", point, point, 15), // - MyHash.of("preceptorships", point, point, 16) // + repository.saveAll(List.of(MyHash.of("predisposition", point, point, 4), // + MyHash.of("predestination", point, point, 8), // + MyHash.of("prepublication", point, point, 15), // + MyHash.of("predestinarian", point, point, 16), // + MyHash.of("preadolescence", point, point, 23), // + MyHash.of("premillenarian", point, point, 42), // + MyHash.of("precipitinogen", point, point, 4), // + MyHash.of("precipitations", point, point, 8), // + MyHash.of("precociousness", point, point, 15), // + MyHash.of("precombustions", point, point, 16), // + MyHash.of("preconditioned", point, point, 23), // + MyHash.of("preconceptions", point, point, 42), // + MyHash.of("precipitancies", point, point, 4), // + MyHash.of("preciousnesses", point, point, 8), // + MyHash.of("precentorships", point, point, 15), // + MyHash.of("preceptorships", point, point, 16) // )); SearchResult result = repository.customFindAllByTitleStartingWithReturnFieldsAndLimit("pre"); assertThat(result.getTotalResults()).isEqualTo(16); assertThat(result.getDocuments()).hasSize(12); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(0).get("title"))).isEqualTo("precentorships"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(1).get("title"))).isEqualTo("preceptorships"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(2).get("title"))).isEqualTo("preciousnesses"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(3).get("title"))).isEqualTo("precipitancies"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(4).get("title"))).isEqualTo("precipitations"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(5).get("title"))).isEqualTo("precipitinogen"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(6).get("title"))).isEqualTo("precociousness"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(7).get("title"))).isEqualTo("precombustions"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(8).get("title"))).isEqualTo("preconceptions"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(9).get("title"))).isEqualTo("preconditioned"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(10).get("title"))).isEqualTo("predestinarian"); - assertThat(SafeEncoder.encode((byte[])result.getDocuments().get(11).get("title"))).isEqualTo("predestination"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(0).get("title"))).isEqualTo("precentorships"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(1).get("title"))).isEqualTo("preceptorships"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(2).get("title"))).isEqualTo("preciousnesses"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(3).get("title"))).isEqualTo("precipitancies"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(4).get("title"))).isEqualTo("precipitations"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(5).get("title"))).isEqualTo("precipitinogen"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(6).get("title"))).isEqualTo("precociousness"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(7).get("title"))).isEqualTo("precombustions"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(8).get("title"))).isEqualTo("preconceptions"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(9).get("title"))).isEqualTo("preconditioned"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(10).get("title"))).isEqualTo("predestinarian"); + assertThat(SafeEncoder.encode((byte[]) result.getDocuments().get(11).get("title"))).isEqualTo("predestination"); } @Test @@ -282,29 +283,31 @@ void testEndingWithSearches() { repository.deleteAll(); Point point = new Point(-122.066540, 37.377690); repository.saveAll(List.of(MyHash.of("predisposition", point, point, 4), // - MyHash.of("predestination", point, point, 8), // - MyHash.of("prepublication", point, point, 15), // - MyHash.of("predestinarian", point, point, 16), // - MyHash.of("preadolescence", point, point, 23), // - MyHash.of("premillenarian", point, point, 42), // - MyHash.of("precipitinogen", point, point, 4), // - MyHash.of("precipitations", point, point, 8), // - MyHash.of("precociousness", point, point, 15), // - MyHash.of("precombustions", point, point, 16), // - MyHash.of("preconditioned", point, point, 23), // - MyHash.of("preconceptions", point, point, 42), // - MyHash.of("precipitancies", point, point, 4), // - MyHash.of("preciousnesses", point, point, 8), // - MyHash.of("precentorships", point, point, 15), // - MyHash.of("preceptorships", point, point, 16) // + MyHash.of("predestination", point, point, 8), // + MyHash.of("prepublication", point, point, 15), // + MyHash.of("predestinarian", point, point, 16), // + MyHash.of("preadolescence", point, point, 23), // + MyHash.of("premillenarian", point, point, 42), // + MyHash.of("precipitinogen", point, point, 4), // + MyHash.of("precipitations", point, point, 8), // + MyHash.of("precociousness", point, point, 15), // + MyHash.of("precombustions", point, point, 16), // + MyHash.of("preconditioned", point, point, 23), // + MyHash.of("preconceptions", point, point, 42), // + MyHash.of("precipitancies", point, point, 4), // + MyHash.of("preciousnesses", point, point, 8), // + MyHash.of("precentorships", point, point, 15), // + MyHash.of("preceptorships", point, point, 16) // )); List endsWithTion = repository.findAllByTitleEndingWith("tion"); List endsWithTions = repository.findAllByTitleEndingWith("tions"); assertAll( // - () -> assertThat(endsWithTion).extracting("title").containsExactlyInAnyOrder("predisposition", "predestination", "prepublication"), - () -> assertThat(endsWithTions).extracting("title").containsExactlyInAnyOrder("precipitations", "precombustions", "preconceptions")); + () -> assertThat(endsWithTion).extracting("title") + .containsExactlyInAnyOrder("predisposition", "predestination", "prepublication"), + () -> assertThat(endsWithTions).extracting("title") + .containsExactlyInAnyOrder("precipitations", "precombustions", "preconceptions")); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashTTLTests.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashTTLTests.java index 78f02066..1255b7d4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashTTLTests.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashTTLTests.java @@ -12,43 +12,45 @@ import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("SpellCheckingInspection") class RedisHashTTLTests extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class RedisHashTTLTests extends AbstractBaseEnhancedRedisTest { @Autowired ExpiringPersonWithDefaultRepository withDefaultrepository; - + @Autowired ExpiringPersonRepository withTTLAnnotationRepository; - + @Autowired ExpiringPersonDifferentTimeUnitRepository withTTLwTimeUnitAnnotationRepository; - - @Autowired StringRedisTemplate template; - + + @Autowired + StringRedisTemplate template; + @BeforeEach void cleanUp() { withDefaultrepository.deleteAll(); } - + @Test void testClassLevelDefaultTTL() { ExpiringPersonWithDefault gordon = ExpiringPersonWithDefault.of("Gordon Welchman"); withDefaultrepository.save(gordon); - + Long expire = withDefaultrepository.getExpiration(gordon.getId()); - + assertThat(expire).isEqualTo(5L); } - + @Test void testTimeToLiveAnnotation() { ExpiringPerson mWoodger = ExpiringPerson.of("Mike Woodger", 15L); withTTLAnnotationRepository.save(mWoodger); - + Long expire = withTTLAnnotationRepository.getExpiration(mWoodger.getId()); assertThat(expire).isEqualTo(15L); } - + @Test void testTimeToLiveAnnotationWithDifferentTimeUnit() { ExpiringPersonDifferentTimeUnit jWilkinson = ExpiringPersonDifferentTimeUnit.of("Jim Wilkinson", 7L); @@ -56,7 +58,7 @@ void testTimeToLiveAnnotationWithDifferentTimeUnit() { Long expire = withTTLwTimeUnitAnnotationRepository.getExpiration(jWilkinson.getId()); - assertThat(expire).isEqualTo(7L*24*60*60); + assertThat(expire).isEqualTo(7L * 24 * 60 * 60); } @Test @@ -70,7 +72,6 @@ void testClassLevelDefaultTTLOnSaveAll() { Long gordonExpiration = withDefaultrepository.getExpiration(gordon.getId()); Long irineuExpiration = withDefaultrepository.getExpiration(irineu.getId()); - assertThat(gordonExpiration).isEqualTo(5L); assertThat(irineuExpiration).isEqualTo(5L); } @@ -101,8 +102,8 @@ void testTimeToLiveAnnotationWithDifferentTimeUnitOnSaveAll() { Long jWilkinsonExpiration = withTTLwTimeUnitAnnotationRepository.getExpiration(jWilkinson.getId()); Long sDummontExpiration = withTTLwTimeUnitAnnotationRepository.getExpiration(sDummont.getId()); - assertThat(jWilkinsonExpiration).isEqualTo(7L*24*60*60); - assertThat(sDummontExpiration).isEqualTo(7L*24*60*60); + assertThat(jWilkinsonExpiration).isEqualTo(7L * 24 * 60 * 60); + assertThat(sDummontExpiration).isEqualTo(7L * 24 * 60 * 60); } @Test diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashVSSIndexCreationTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashVSSIndexCreationTest.java index d12676b5..2345cdd3 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashVSSIndexCreationTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashVSSIndexCreationTest.java @@ -18,78 +18,66 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisHashVSSIndexCreationTest extends AbstractBaseEnhancedRedisTest { - @Autowired HashWithVectorsRepository repository; - - @Autowired JedisConnectionFactory jedisConnectionFactory; - - private UnifiedJedis jedis; - private static final String INDEX = "com.redis.om.spring.annotations.hash.fixtures.HashWithVectorsIdx"; + @Autowired + HashWithVectorsRepository repository; + @Autowired + JedisConnectionFactory jedisConnectionFactory; + private UnifiedJedis jedis; private HashWithVectors hwv1; - private HashWithVectors hwv2; - private HashWithVectors hwv3; @BeforeEach void cleanUp() { repository.deleteAll(); hwv1 = repository.save(HashWithVectors.of("aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa")); - hwv2 = repository.save(HashWithVectors.of("aaaabaaa", "aaaabaaa", "aaaabaaa", "aaaabaaa")); - hwv3 = repository.save(HashWithVectors.of("aaaaabaa", "aaaaabaa", "aaaaabaa", "aaaaabaa")); + repository.save(HashWithVectors.of("aaaabaaa", "aaaabaaa", "aaaabaaa", "aaaabaaa")); + repository.save(HashWithVectors.of("aaaaabaa", "aaaaabaa", "aaaaabaa", "aaaaabaa")); jedis = new JedisPooled(Objects.requireNonNull(jedisConnectionFactory.getPoolConfig()), - jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort()); + jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort()); } - @Test void testFlatVectorFieldIndexCreationWithVectorIndexed() { - FTSearchParams searchParams = FTSearchParams.searchParams() - .addParam("vec", "aaaaaaaa") - .sortBy("__flat_score", SortingOrder.ASC) - .returnFields("__flat_score") - .dialect(2); + @Test + void testFlatVectorFieldIndexCreationWithVectorIndexed() { + FTSearchParams searchParams = FTSearchParams.searchParams().addParam("vec", "aaaaaaaa") + .sortBy("__flat_score", SortingOrder.ASC).returnFields("__flat_score").dialect(2); Document doc1 = jedis.ftSearch(INDEX, "*=>[KNN 2 @flat $vec]", searchParams).getDocuments().get(0); - assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:"+hwv1.getId()); + assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:" + hwv1.getId()); assertThat(doc1.get("__flat_score")).isEqualTo("0"); } - @Test void testHNSWVectorFieldIndexCreationWithVectorIndexed() { - FTSearchParams searchParams = FTSearchParams.searchParams() - .addParam("vec", "aaaaaaaa") - .sortBy("__hnsw_score", SortingOrder.ASC) - .returnFields("__hnsw_score") - .dialect(2); + @Test + void testHNSWVectorFieldIndexCreationWithVectorIndexed() { + FTSearchParams searchParams = FTSearchParams.searchParams().addParam("vec", "aaaaaaaa") + .sortBy("__hnsw_score", SortingOrder.ASC).returnFields("__hnsw_score").dialect(2); Document doc1 = jedis.ftSearch(INDEX, "*=>[KNN 2 @hnsw $vec]", searchParams).getDocuments().get(0); - assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:"+hwv1.getId()); + assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:" + hwv1.getId()); assertThat(doc1.get("__hnsw_score")).isEqualTo("0"); } - - @Test void testFlatVectorFieldIndexCreationWithIndexed() { - FTSearchParams searchParams = FTSearchParams.searchParams() - .addParam("vec", "aaaaaaaa") - .sortBy("__flat2_score", SortingOrder.ASC) - .returnFields("__flat2_score") - .dialect(2); + @Test + void testFlatVectorFieldIndexCreationWithIndexed() { + FTSearchParams searchParams = FTSearchParams.searchParams().addParam("vec", "aaaaaaaa") + .sortBy("__flat2_score", SortingOrder.ASC).returnFields("__flat2_score").dialect(2); Document doc1 = jedis.ftSearch(INDEX, "*=>[KNN 2 @flat2 $vec]", searchParams).getDocuments().get(0); - assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:"+hwv1.getId()); + assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:" + hwv1.getId()); assertThat(doc1.get("__flat2_score")).isEqualTo("0"); } - @Test void testHNSWVectorFieldIndexCreationWithIndexed() { - FTSearchParams searchParams = FTSearchParams.searchParams() - .addParam("vec", "aaaaaaaa") - .sortBy("__hnsw2_score", SortingOrder.ASC) - .returnFields("__hnsw2_score") - .dialect(2); + @Test + void testHNSWVectorFieldIndexCreationWithIndexed() { + FTSearchParams searchParams = FTSearchParams.searchParams().addParam("vec", "aaaaaaaa") + .sortBy("__hnsw2_score", SortingOrder.ASC).returnFields("__hnsw2_score").dialect(2); Document doc1 = jedis.ftSearch(INDEX, "*=>[KNN 2 @hnsw2 $vec]", searchParams).getDocuments().get(0); - assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:"+hwv1.getId()); + assertThat(doc1.getId()).isEqualTo("com.redis.om.spring.annotations.hash.fixtures.HashWithVectors:" + hwv1.getId()); assertThat(doc1.get("__hnsw2_score")).isEqualTo("0"); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashWithAliasTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashWithAliasTest.java index 3a0a7521..6008762b 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashWithAliasTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/RedisHashWithAliasTest.java @@ -23,12 +23,14 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("SpellCheckingInspection") class RedisHashWithAliasTest extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class RedisHashWithAliasTest extends AbstractBaseEnhancedRedisTest { @Autowired WithAliasRepository repository; String id1; - @SuppressWarnings("unused") String id2; + @SuppressWarnings("unused") + String id2; @Autowired EntityStream entityStream; @@ -78,26 +80,23 @@ void testBasicCrudOperations() { void testGetByAliasedProperty() { SearchStream stream = entityStream.of(WithAlias.class); List docs = stream // - .filter(WithAlias$.TEXT.eq("Oye man")) // - .collect(Collectors.toList()); + .filter(WithAlias$.TEXT.eq("Oye man")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(docs).hasSize(1), - () -> assertThat(docs).extracting("text").containsOnly("Oye man") - ); + () -> assertThat(docs).hasSize(1), () -> assertThat(docs).extracting("text").containsOnly("Oye man")); } @Test void testGetByTagAliasedProperty() { SearchStream stream = entityStream.of(WithAlias.class); List docs = stream // - .filter(WithAlias$.TAGS.in("articulo", "article")) // - .collect(Collectors.toList()); + .filter(WithAlias$.TAGS.in("articulo", "article")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(docs).hasSize(2), - () -> assertThat(docs).extracting("text").containsOnly("Epa chamo", "Oye man") - ); + () -> assertThat(docs).hasSize(2), + () -> assertThat(docs).extracting("text").containsOnly("Epa chamo", "Oye man")); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CompanyRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CompanyRepository.java index 1e91af56..54611cde 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CompanyRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CompanyRepository.java @@ -8,7 +8,8 @@ import java.util.Optional; import java.util.Set; -@SuppressWarnings("unused") public interface CompanyRepository extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface CompanyRepository extends RedisEnhancedRepository { List findByName(String companyName); boolean existsByEmail(String email); @@ -28,10 +29,11 @@ Iterable getAllTags(); Iterable search(String text); - + List findByLocationNear(Point point, Distance distance); // order by List findByYearFoundedOrderByNameAsc(int year); + List findByYearFoundedOrderByNameDesc(int year); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CountryRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CountryRepository.java index 508a0bb8..93b8ff61 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CountryRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/CountryRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -public interface CountryRepository extends RedisEnhancedRepository { +public interface CountryRepository extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Direccion.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Direccion.java index 1949ae00..d28c9f69 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Direccion.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Direccion.java @@ -6,7 +6,8 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; -@SuppressWarnings("SpellCheckingInspection") @Data +@SuppressWarnings("SpellCheckingInspection") +@Data @RequiredArgsConstructor(staticName = "of") public class Direccion { @NonNull diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/EmailTakenImpl.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/EmailTakenImpl.java index 4abfc975..d4c51718 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/EmailTakenImpl.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/EmailTakenImpl.java @@ -4,8 +4,9 @@ import com.redis.om.spring.ops.pds.BloomOperations; import org.springframework.beans.factory.annotation.Autowired; -@SuppressWarnings("ALL") public class EmailTakenImpl implements EmailTaken { - +@SuppressWarnings("ALL") +public class EmailTakenImpl implements EmailTaken { + @Autowired RedisModulesOperations modulesOperations; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPerson.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPerson.java index 4b190670..b0ddbf30 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPerson.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPerson.java @@ -13,10 +13,12 @@ @RequiredArgsConstructor(staticName = "of") @RedisHash(timeToLive = 5) public class ExpiringPerson { - @Id String id; + @Id + String id; @NonNull String name; - + @NonNull - @TimeToLive Long ttl; + @TimeToLive + Long ttl; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnit.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnit.java index 0c8ece36..6cd4d37d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnit.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnit.java @@ -15,10 +15,12 @@ @RequiredArgsConstructor(staticName = "of") @RedisHash(timeToLive = 5) public class ExpiringPersonDifferentTimeUnit { - @Id String id; + @Id + String id; @NonNull String name; - + @NonNull - @TimeToLive(unit = TimeUnit.DAYS) Long ttl; + @TimeToLive(unit = TimeUnit.DAYS) + Long ttl; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnitRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnitRepository.java index a14d888c..11e463e6 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnitRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonDifferentTimeUnitRepository.java @@ -2,6 +2,7 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -@SuppressWarnings("unused") public interface ExpiringPersonDifferentTimeUnitRepository - extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonDifferentTimeUnitRepository + extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonRepository.java index 6d44b7c2..cd33f36f 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -@SuppressWarnings("unused") public interface ExpiringPersonRepository extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonRepository extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefault.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefault.java index 9ea83cd1..c737f574 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefault.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefault.java @@ -12,7 +12,8 @@ @RequiredArgsConstructor(staticName = "of") @RedisHash(timeToLive = 5) public class ExpiringPersonWithDefault { - @Id String id; + @Id + String id; @NonNull String name; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefaultRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefaultRepository.java index 4e972d10..d17a7628 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefaultRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/ExpiringPersonWithDefaultRepository.java @@ -2,6 +2,7 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -@SuppressWarnings("unused") public interface ExpiringPersonWithDefaultRepository - extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface ExpiringPersonWithDefaultRepository + extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/GameRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/GameRepository.java index 7a7d87ea..8ec0021a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/GameRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/GameRepository.java @@ -9,7 +9,8 @@ import java.util.Map; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataRepositoryMethodReturnTypeInspection" }) public interface GameRepository extends RedisEnhancedRepository { +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataRepositoryMethodReturnTypeInspection" }) +public interface GameRepository extends RedisEnhancedRepository { /** *
    * FT.AGGREGATE "com.redis.om.spring.annotations.document.fixtures.GameIdx" '*'
@@ -20,16 +21,17 @@
    * 
*/ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count", direction = Direction.DESC), // - } - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count", direction = Direction.DESC), // + } + ) + // Page> countByBrand(Pageable pageable); /** @@ -42,20 +44,20 @@ *
*/ @Aggregation( // - value = "sony", // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MIN, args={"@price"}, alias="minPrice") - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@minPrice", direction = Direction.DESC), // - } - ) // + value = "sony", // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MIN, args = { "@price" }, alias = "minPrice") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@minPrice", direction = Direction.DESC), // + } + ) + // AggregationResult minPricesContainingSony(); /** @@ -68,20 +70,20 @@ * */ @Aggregation( // - value = "sony", // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MAX, args={"@price"}, alias="maxPrice") - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@maxPrice", direction = Direction.DESC), // - } - ) // + value = "sony", // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MAX, args = { "@price" }, alias = "maxPrice") } // + ) // + }, // + sortBy = { // + @SortBy(field = "@maxPrice", direction = Direction.DESC), // + } + ) + // AggregationResult maxPricesContainingSony(); /** @@ -95,20 +97,23 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT_DISTINCT, args={"@title"}, alias="count_distinct(title)"), // - @Reducer(func = ReducerFunction.COUNT) // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count_distinct(title)", direction = Direction.DESC), // - }, - limit = 5 - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer( + func = ReducerFunction.COUNT_DISTINCT, args = { "@title" }, + alias = "count_distinct(title)" + ), // + @Reducer(func = ReducerFunction.COUNT) // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count_distinct(title)", direction = Direction.DESC), // + }, limit = 5 + ) + // AggregationResult top5countDistinctByBrand(); /** @@ -124,23 +129,23 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.50"}, alias="q50"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.90"}, alias="q90"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.95"}, alias="q95"), // - @Reducer(func = ReducerFunction.AVG, args={"@price"}), // - @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@rowcount", direction = Direction.DESC), // - }, - sortByMax = 1 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.50" }, alias = "q50"), // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.90" }, alias = "q90"), // + @Reducer(func = ReducerFunction.QUANTILE, args = { "@price", "0.95" }, alias = "q95"), // + @Reducer(func = ReducerFunction.AVG, args = { "@price" }), // + @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@rowcount", direction = Direction.DESC), // + }, sortByMax = 1 // + ) + // AggregationResult priceQuantiles(); /** @@ -156,22 +161,24 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.STDDEV, args={"@price"}, alias="stddev(price)"), // - @Reducer(func = ReducerFunction.AVG, args={"@price"}, alias = "avgPrice"), // - @Reducer(func = ReducerFunction.QUANTILE, args={"@price", "0.50"}, alias="q50Price"), // - @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@rowcount", direction = Direction.DESC), // - }, - limit = 10 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.STDDEV, args = { "@price" }, alias = "stddev(price)"), // + @Reducer(func = ReducerFunction.AVG, args = { "@price" }, alias = "avgPrice"), // + @Reducer( + func = ReducerFunction.QUANTILE, args = { "@price", "0.50" }, alias = "q50Price" + ), // + @Reducer(func = ReducerFunction.COUNT, alias = "rowcount") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@rowcount", direction = Direction.DESC), // + }, limit = 10 // + ) + // AggregationResult priceStdDev(); /** @@ -185,18 +192,19 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // - ) // - }, // - apply = { // - @Apply(expression = "timefmt(1517417144)", alias = "dt"), // - @Apply(expression = "parsetime(@dt, \"%FT%TZ\")", alias = "parsed_dt"), // - }, // - limit = 1 // - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + apply = { // + @Apply(expression = "timefmt(1517417144)", alias = "dt"), // + @Apply(expression = "parsetime(@dt, \"%FT%TZ\")", alias = "parsed_dt"), // + }, // + limit = 1 // + ) + // AggregationResult parseTime(); /** @@ -209,20 +217,22 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = "@brand", // - reduce = { // - @Reducer(func = ReducerFunction.COUNT, alias = "num"), // - @Reducer(func = ReducerFunction.RANDOM_SAMPLE, args={"@price", "10"}, alias = "sample") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@num", direction = Direction.DESC), // - }, - sortByMax = 10 - ) // + groupBy = { // + @GroupBy( // + properties = "@brand", // + reduce = { // + @Reducer(func = ReducerFunction.COUNT, alias = "num"), // + @Reducer( + func = ReducerFunction.RANDOM_SAMPLE, args = { "@price", "10" }, alias = "sample" + ) // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@num", direction = Direction.DESC), // + }, sortByMax = 10 + ) + // AggregationResult randomSample(); /** @@ -242,20 +252,19 @@ * */ @Aggregation( // - apply = { - @Apply(expression = "1517417144", alias = "dt"), // - @Apply(expression = "timefmt(@dt)", alias = "timefmt"), // - @Apply(expression = "day(@dt)", alias = "day"), // - @Apply(expression = "hour(@dt)", alias = "hour"), // - @Apply(expression = "minute(@dt)", alias = "minute"), // - @Apply(expression = "month(@dt)", alias = "month"), // - @Apply(expression = "dayofweek(@dt)", alias = "dayofweek"), // - @Apply(expression = "dayofmonth(@dt)", alias = "dayofmonth"), // - @Apply(expression = "dayofyear(@dt)", alias = "dayofyear"), // - @Apply(expression = "year(@dt)", alias = "year"), // - }, - limit = 1 - ) // + apply = { @Apply(expression = "1517417144", alias = "dt"), // + @Apply(expression = "timefmt(@dt)", alias = "timefmt"), // + @Apply(expression = "day(@dt)", alias = "day"), // + @Apply(expression = "hour(@dt)", alias = "hour"), // + @Apply(expression = "minute(@dt)", alias = "minute"), // + @Apply(expression = "month(@dt)", alias = "month"), // + @Apply(expression = "dayofweek(@dt)", alias = "dayofweek"), // + @Apply(expression = "dayofmonth(@dt)", alias = "dayofmonth"), // + @Apply(expression = "dayofyear(@dt)", alias = "dayofyear"), // + @Apply(expression = "year(@dt)", alias = "year"), // + }, limit = 1 + ) + // AggregationResult timeFunctions(); /** @@ -268,20 +277,21 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@title", "@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT), // - @Reducer(func = ReducerFunction.MAX, args={"@price"}, alias = "price") // - } // - ) // - }, // - apply = { - @Apply(expression = "format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", alias = "titleBrand"), // - }, - limit = 10 - ) // + groupBy = { // + @GroupBy( // + properties = { "@title", "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT), // + @Reducer(func = ReducerFunction.MAX, args = { "@price" }, alias = "price") // + } // + ) // + }, // + apply = { @Apply( + expression = "format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", alias = "titleBrand" + ), // + }, limit = 10 + ) + // AggregationResult stringFormat(); /** @@ -295,20 +305,20 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT, alias="count"), // - @Reducer(func = ReducerFunction.SUM, args={"@price"}, alias = "sum(price)") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@sum(price)", direction = Direction.DESC), // - }, - limit = 5 // - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT, alias = "count"), // + @Reducer(func = ReducerFunction.SUM, args = { "@price" }, alias = "sum(price)") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@sum(price)", direction = Direction.DESC), // + }, limit = 5 // + ) + // AggregationResult sumPrice(); /** @@ -326,14 +336,15 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { @Reducer(func = ReducerFunction.COUNT, alias="count") } // - ) // - }, // - filter = { "@count < 5", "@count > 2 && @brand != \"\"" } - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { @Reducer(func = ReducerFunction.COUNT, alias = "count") } // + ) // + }, // + filter = { "@count < 5", "@count > 2 && @brand != \"\"" } + ) + // AggregationResult filters(); /** @@ -347,20 +358,20 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { // - @Reducer(func = ReducerFunction.COUNT_DISTINCT, args="@price", alias="count"), // - @Reducer(func = ReducerFunction.TOLIST, args="@price", alias="prices") // - } // - ) // - }, // - sortBy = { // - @SortBy(field = "@count", direction = Direction.DESC), // - }, - limit = 5 // - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { // + @Reducer(func = ReducerFunction.COUNT_DISTINCT, args = "@price", alias = "count"), // + @Reducer(func = ReducerFunction.TOLIST, args = "@price", alias = "prices") // + } // + ) // + }, // + sortBy = { // + @SortBy(field = "@count", direction = Direction.DESC), // + }, limit = 5 // + ) + // AggregationResult toList(); /** @@ -374,19 +385,19 @@ * */ @Aggregation( // - groupBy = { // - @GroupBy( // - properties = {"@brand"}, // - reduce = { @Reducer(func = ReducerFunction.SUM, args="@price", alias="price") } // - ) // - }, // - apply = { @Apply(expression = "(@price % 10)", alias = "price") }, // - sortBy = { // - @SortBy(field = "@price", direction = Direction.ASC), // - @SortBy(field = "@brand", direction = Direction.DESC), // - }, - sortByMax = 10 - ) // + groupBy = { // + @GroupBy( // + properties = { "@brand" }, // + reduce = { @Reducer(func = ReducerFunction.SUM, args = "@price", alias = "price") } // + ) // + }, // + apply = { @Apply(expression = "(@price % 10)", alias = "price") }, // + sortBy = { // + @SortBy(field = "@price", direction = Direction.ASC), // + @SortBy(field = "@brand", direction = Direction.DESC), // + }, sortByMax = 10 + ) + // AggregationResult sortByMany(); /** @@ -398,10 +409,10 @@ * */ @Aggregation( // - load = @Load(property = "@title"), - sortBy = @SortBy(field = "@price", direction = Direction.DESC), - limit = 2 - ) // + load = @Load(property = "@title"), sortBy = @SortBy(field = "@price", direction = Direction.DESC), + limit = 2 + ) + // AggregationResult loadWithSort(); /** @@ -415,9 +426,9 @@ * */ @Aggregation( // - load = { @Load(property = "@brand"), @Load(property = "@price"), @Load(property = "@__key") }, - sortBy = @SortBy(field = "@price", direction = Direction.DESC), - sortByMax = 4 - ) // + load = { @Load(property = "@brand"), @Load(property = "@price"), @Load(property = "@__key") }, + sortBy = @SortBy(field = "@price", direction = Direction.DESC), sortByMax = 4 + ) + // AggregationResult loadWithDocId(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionPojo.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionPojo.java index a4f02b35..b31b193b 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionPojo.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionPojo.java @@ -10,15 +10,15 @@ @Data public class HashProjectionPojo { - @Id - private String id; + @Id + private String id; - private String name; + private String name; - private String test; + private String test; - public HashProjectionPojo() { - this.id = UUID.randomUUID().toString(); - } + public HashProjectionPojo() { + this.id = UUID.randomUUID().toString(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionRepository.java index bd71790d..4a4da15d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashProjectionRepository.java @@ -8,7 +8,9 @@ import java.util.Optional; public interface HashProjectionRepository extends RedisEnhancedRepository { - Optional findByName(String name); - Collection findAllByName(String name); - Page findAllByName(String name, Pageable pageable); + Optional findByName(String name); + + Collection findAllByName(String name); + + Page findAllByName(String name, Pageable pageable); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVector.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVector.java index 4a07a0be..1137d0be 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVector.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVector.java @@ -20,13 +20,12 @@ public class HashWithByteArrayFlatVector { private String id; @Indexed(// - schemaFieldType = SchemaFieldType.VECTOR, // - algorithm = VectorAlgorithm.FLAT, // - type = VectorType.FLOAT32, // - dimension = 100, // - distanceMetric = DistanceMetric.L2, // - initialCapacity = 300, - m = 40 + schemaFieldType = SchemaFieldType.VECTOR, // + algorithm = VectorAlgorithm.FLAT, // + type = VectorType.FLOAT32, // + dimension = 100, // + distanceMetric = DistanceMetric.L2, // + initialCapacity = 300, m = 40 ) @NonNull private byte[] vector; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVectorRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVectorRepository.java index 6beb4ca4..af5ee4ad 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVectorRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayFlatVectorRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -public interface HashWithByteArrayFlatVectorRepository extends RedisEnhancedRepository { +public interface HashWithByteArrayFlatVectorRepository + extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVector.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVector.java index c8fac1e2..c3b71404 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVector.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVector.java @@ -20,13 +20,12 @@ public class HashWithByteArrayHNSWVector { private String id; @Indexed(// - schemaFieldType = SchemaFieldType.VECTOR, // - algorithm = VectorAlgorithm.HNSW, // - type = VectorType.FLOAT32, // - dimension = 100, // - distanceMetric = DistanceMetric.L2, // - initialCapacity = 300, - m = 40 + schemaFieldType = SchemaFieldType.VECTOR, // + algorithm = VectorAlgorithm.HNSW, // + type = VectorType.FLOAT32, // + dimension = 100, // + distanceMetric = DistanceMetric.L2, // + initialCapacity = 300, m = 40 ) @NonNull private byte[] vector; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVectorRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVectorRepository.java index 8cf5de2a..d691357c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVectorRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithByteArrayHNSWVectorRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -public interface HashWithByteArrayHNSWVectorRepository extends RedisEnhancedRepository { +public interface HashWithByteArrayHNSWVectorRepository + extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithColonInPrefixRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithColonInPrefixRepository.java index a4a90dda..e80bb9b2 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithColonInPrefixRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithColonInPrefixRepository.java @@ -2,5 +2,5 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -public interface HashWithColonInPrefixRepository extends RedisEnhancedRepository { +public interface HashWithColonInPrefixRepository extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithVectors.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithVectors.java index 02abe560..93db8175 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithVectors.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/HashWithVectors.java @@ -20,18 +20,28 @@ public class HashWithVectors { private String id; @NonNull - @VectorIndexed(algorithm = VectorAlgorithm.FLAT, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2) + @VectorIndexed( + algorithm = VectorAlgorithm.FLAT, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2 + ) private String flat; @NonNull - @VectorIndexed(algorithm = VectorAlgorithm.HNSW, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2) + @VectorIndexed( + algorithm = VectorAlgorithm.HNSW, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2 + ) private String hnsw; @NonNull - @Indexed(schemaFieldType = SchemaFieldType.VECTOR, algorithm = VectorAlgorithm.FLAT, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2) + @Indexed( + schemaFieldType = SchemaFieldType.VECTOR, algorithm = VectorAlgorithm.FLAT, type = VectorType.FLOAT32, + dimension = 2, distanceMetric = DistanceMetric.L2 + ) private String flat2; @NonNull - @Indexed(schemaFieldType = SchemaFieldType.VECTOR, algorithm = VectorAlgorithm.HNSW, type = VectorType.FLOAT32, dimension = 2, distanceMetric = DistanceMetric.L2) + @Indexed( + schemaFieldType = SchemaFieldType.VECTOR, algorithm = VectorAlgorithm.HNSW, type = VectorType.FLOAT32, + dimension = 2, distanceMetric = DistanceMetric.L2 + ) private String hnsw2; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSink.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSink.java index 7d1ad334..b6e959b1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSink.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSink.java @@ -56,8 +56,8 @@ public class KitchenSink { @Singular @Indexed private List listThings; - + private byte[] byteArray; - + private List listOfStringArrays; } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSinkRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSinkRepository.java index 5062c3a3..434f6834 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSinkRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/KitchenSinkRepository.java @@ -6,7 +6,9 @@ import java.util.List; import java.util.Optional; -@SuppressWarnings("unused") public interface KitchenSinkRepository extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface KitchenSinkRepository extends RedisEnhancedRepository { List findByLocalDateGreaterThan(LocalDate localDate); + Optional findFirstByName(String name); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHash.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHash.java index 8760fd7b..c19a660f 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHash.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHash.java @@ -17,23 +17,23 @@ public class MyHash { @Id private String id; - + @NonNull @TextIndexed(alias = "title", sortable = true) private String title; - + @NonNull @GeoIndexed(alias = "location") private Point location; - + @NonNull @Indexed private Point location2; - + @NonNull @NumericIndexed private Integer aNumber; - + @TagIndexed(alias = "tag") private Set tag = new HashSet<>(); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashQueriesImpl.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashQueriesImpl.java index 4afb4a31..d7ca945b 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashQueriesImpl.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashQueriesImpl.java @@ -11,13 +11,13 @@ import java.util.Optional; -@SuppressWarnings({ "unused", "SpringJavaAutowiredMembersInspection" }) public class MyHashQueriesImpl implements MyHashQueries { +@SuppressWarnings({ "unused", "SpringJavaAutowiredMembersInspection" }) +public class MyHashQueriesImpl implements MyHashQueries { + private final MappingRedisOMConverter converter = new MappingRedisOMConverter(); @Autowired RedisModulesOperations modulesOperations; - private final MappingRedisOMConverter converter = new MappingRedisOMConverter(); - @Override public Optional findByTitle(String title) { SearchOperations ops = modulesOperations.opsForSearch(MyHash.class.getName() + "Idx"); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashRepository.java index 4d7af8ea..1f63fb5c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/MyHashRepository.java @@ -12,19 +12,20 @@ import java.util.List; import java.util.Set; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) public interface MyHashRepository extends RedisEnhancedRepository, MyHashQueries { +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) +public interface MyHashRepository extends RedisEnhancedRepository, MyHashQueries { /** *
-   * > FT.SEARCH idx '@title:hello @tag:{news}' 
-   * 1) (integer) 1 
-   * 2) "doc1" 
+   * > FT.SEARCH idx '@title:hello @tag:{news}'
+   * 1) (integer) 1
+   * 2) "doc1"
    * 3) 1) "$"
    *    2) "{\"title\":\"hello world\",\"tag\":[\"news\",\"article\"]}"
    * 
*/ @Query("@title:$title @tag:{$tags}") Iterable findByTitleAndTags(@Param("title") String title, @Param("tags") Set tags); - + /** *
    * > FT.SEARCH idx @title:hel* SORTBY title ASC LIMIT 0 2
@@ -38,7 +39,7 @@
    * 
*/ List findAllByTitleEndingWith(String title); - + /** *
    * > FT.SEARCH idx @title:hel* LIMIT 0 2
@@ -46,27 +47,27 @@
    */
   @Query("@title:$prefix*")
   Page customFindAllByTitleStartingWith(@Param("prefix") String prefix, Pageable pageable);
-  
+
   /**
    * 
    * > FT.SEARCH idx @title:pre* SORTBY title ASC LIMIT 1 12 RETURN 2 title aNumber
    * 
*/ - @Query(value="@title:$prefix*", returnFields={"title", "aNumber"}, limit = 12, offset = 1, sortBy = "title") + @Query(value = "@title:$prefix*", returnFields = { "title", "aNumber" }, limit = 12, offset = 1, sortBy = "title") SearchResult customFindAllByTitleStartingWithReturnFieldsAndLimit(@Param("prefix") String prefix); - + /** *
    * > FT.TAGVALS idx tags
    * 
*/ Iterable getAllTag(); - + Iterable findByTag(Set tags); - Iterable findByLocationNear(Point point, Distance distance); - - Iterable findByLocation2Near(Point point, Distance distance); - + Iterable findByLocationNear(Point point, Distance distance); + + Iterable findByLocation2Near(Point point, Distance distance); + Iterable findByaNumber(Integer anotherNumber); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/NonIndexedHashRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/NonIndexedHashRepository.java index 9c064676..c279d3d4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/NonIndexedHashRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/NonIndexedHashRepository.java @@ -2,5 +2,6 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; -@SuppressWarnings("unused") public interface NonIndexedHashRepository extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface NonIndexedHashRepository extends RedisEnhancedRepository { } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person.java index f47c5aaa..95745da1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person.java @@ -17,25 +17,25 @@ @RedisHash("people") public class Person { - @Id + @Id String id; - - @NonNull + + @NonNull String name; - - @NonNull - @AutoComplete + + @NonNull + @AutoComplete @Bloom(name = "bf_person_email", capacity = 100000, errorRate = 0.001) String email; - + @NonNull @Bloom(capacity = 100000, errorRate = 0.001) String nickname; - + @NonNull @Indexed Set roles = new HashSet<>(); - + @NonNull Set favoriteFoods = new HashSet<>(); } \ No newline at end of file diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2.java index 3786642b..a88a4a38 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2.java @@ -13,17 +13,17 @@ @RedisHash("people2") public class Person2 { - @Id + @Id String id; - - @NonNull + + @NonNull String name; - - @NonNull - @AutoComplete + + @NonNull + @AutoComplete @Cuckoo(name = "cf_person_email", capacity = 100000) String email; - + @NonNull @Cuckoo(capacity = 100000) String nickname; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2Repository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2Repository.java index 2db00e85..310f918e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2Repository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/Person2Repository.java @@ -3,7 +3,8 @@ import com.redis.om.spring.repository.RedisEnhancedRepository; import org.springframework.stereotype.Repository; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) @Repository +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) +@Repository public interface Person2Repository extends RedisEnhancedRepository { boolean existsByEmail(String email); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/PersonRepository.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/PersonRepository.java index f5a99a62..f2ac293b 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/PersonRepository.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/fixtures/PersonRepository.java @@ -13,7 +13,8 @@ import java.util.List; import java.util.Set; -@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) @Repository +@SuppressWarnings({ "unused", "SpellCheckingInspection", "SpringDataMethodInconsistencyInspection" }) +@Repository public interface PersonRepository extends RedisEnhancedRepository, EmailTaken { boolean existsByEmail(String email); @@ -33,6 +34,8 @@ public interface PersonRepository extends RedisEnhancedRepository { +@SuppressWarnings("unused") +public interface WithAliasRepository extends RedisEnhancedRepository { Optional findFirstByNumber(Integer number); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/serialization/SerializationTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/serialization/SerializationTest.java index 6cf6ca2a..b00bb718 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/serialization/SerializationTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/serialization/SerializationTest.java @@ -19,9 +19,11 @@ import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("SpellCheckingInspection") class SerializationTest extends AbstractBaseEnhancedRedisTest { +@SuppressWarnings("SpellCheckingInspection") +class SerializationTest extends AbstractBaseEnhancedRedisTest { - @Autowired StringRedisTemplate template; + @Autowired + StringRedisTemplate template; @Autowired KitchenSinkRepository repository; @@ -59,83 +61,82 @@ public void cleanUp() throws IOException { localDateTime = LocalDateTime.now(); localOffsetDateTime = OffsetDateTime.now(); date = new Date(); - point = new Point(-111.83592170193586,33.62826024782707); + point = new Point(-111.83592170193586, 33.62826024782707); ulid = UlidCreator.getMonotonicUlid(); byteArray = "Hello World!".getBytes(); byteArray2 = featureExtractor.getImageEmbeddingsAsByteArrayFor( // - applicationContext.getResource("classpath:/images/cat.jpg").getInputStream() - ); + applicationContext.getResource("classpath:/images/cat.jpg").getInputStream()); List listOfStringArrays = new ArrayList<>(); - listOfStringArrays.add(new String[] {"a", "b"}); - listOfStringArrays.add(new String[] {"c", "d"}); - listOfStringArrays.add(new String[] { null, "e"}); + listOfStringArrays.add(new String[] { "a", "b" }); + listOfStringArrays.add(new String[] { "c", "d" }); + listOfStringArrays.add(new String[] { null, "e" }); listOfStringArrays.add(null); - + setThings = Set.of("thingOne", "thingTwo", "thingThree"); listThings = List.of("redFish", "blueFish"); ks = KitchenSink.builder() // - .name("ks") // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .setThings(setThings) // - .listThings(listThings) // - .build(); + .name("ks") // + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .setThings(setThings) // + .listThings(listThings) // + .build(); ks1 = KitchenSink.builder() // - .name("ks1") // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .setThings(Set.of()) // - .listThings(List.of()) // - .build(); + .name("ks1") // + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .setThings(Set.of()) // + .listThings(List.of()) // + .build(); ks2 = KitchenSink.builder() // - .name("ks2") // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .build(); + .name("ks2") // + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .build(); ks2.setSetThings(null); ks2.setListThings(null); ks2.setByteArray(byteArray2); - + ks3 = KitchenSink.builder() // - .name("ks3") // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .build(); - + .name("ks3") // + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .build(); + ks3.setUlid(null); ks3.setByteArray(byteArray); - + ks4 = KitchenSink.builder() // - .name("ks4") // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .build(); - + .name("ks4") // + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .build(); + ks4.setUlid(null); ks4.setByteArray(null); ks4.setListOfStringArrays(listOfStringArrays); @@ -154,12 +155,14 @@ void testHashSerialization() { // LocalDateTime Instant localDateTimeInstant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); long localDateTimeInMillis = localDateTimeInstant.toEpochMilli(); - long rawLocalDateTime = Long.parseLong(Objects.requireNonNull(template.opsForHash().get(key, "localDateTime")).toString()); + long rawLocalDateTime = Long.parseLong( + Objects.requireNonNull(template.opsForHash().get(key, "localDateTime")).toString()); // OffsetDateTime Instant localOffsetDateTimeInstant = localOffsetDateTime.atZoneSameInstant(ZoneId.systemDefault()).toInstant(); long localOffsetDateTimeInMillis = localOffsetDateTimeInstant.toEpochMilli(); - long rawlocalOffsetDateTime = Long.parseLong(Objects.requireNonNull(template.opsForHash().get(key, "localOffsetDateTime")).toString()); + long rawlocalOffsetDateTime = Long.parseLong( + Objects.requireNonNull(template.opsForHash().get(key, "localOffsetDateTime")).toString()); // Date long dateInMillis = date.getTime(); @@ -170,7 +173,7 @@ void testHashSerialization() { String rawPoint = Objects.requireNonNull(template.opsForHash().get(key, "point")).toString(); String rawUlid = Objects.requireNonNull(template.opsForHash().get(key, "ulid")).toString(); - + // String rawSetThings = Objects.requireNonNull(template.opsForHash().get(key, "setThings")).toString(); String rawListThings = Objects.requireNonNull(template.opsForHash().get(key, "listThings")).toString(); @@ -216,13 +219,13 @@ void testHashDeserializationUsingCustomFinder() { assertThat(fromDb.get().getSetThings()).isEqualTo(setThings); assertThat(fromDb.get().getListThings()).isEqualTo(listThings); } - + @Test void testLocalDateDeSerializationInQuery() { List all = repository.findByLocalDateGreaterThan(localDate.minusDays(2)); assertThat(all).containsExactlyInAnyOrder(ks, ks1, ks2, ks3, ks4); } - + @Test void testEmptyUlidReturnsAsNull() { Optional fromDb = repository.findById(ks3.getId()); @@ -236,7 +239,7 @@ void testEmptyUlidReturnsAsNullUsingCustomFinder() { assertThat(fromDb).isPresent(); assertThat(fromDb.get().getUlid()).isNull(); } - + @Test void testArraySerialization() { Optional fromDb = repository.findById(ks3.getId()); @@ -264,7 +267,7 @@ void testArraySerializationLargeBlobUsingCustomFinder() { assertThat(fromDb).isPresent(); assertThat(fromDb.get().getByteArray()).isEqualTo(byteArray2); } - + @Test void testCantPersistCollectionWithNulls() { Optional fromDb = repository.findById(ks4.getId()); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/VectorizeHashTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/VectorizeHashTest.java index c7088e86..2b0f2837 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/VectorizeHashTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/VectorizeHashTest.java @@ -23,56 +23,61 @@ import static org.junit.jupiter.api.Assertions.assertAll; class VectorizeHashTest extends AbstractBaseEnhancedRedisTest { - @Autowired ProductRepository repository; - @Autowired EntityStream entityStream; + @Autowired + ProductRepository repository; + @Autowired + EntityStream entityStream; - @Autowired FeatureExtractor featureExtractor; + @Autowired + FeatureExtractor featureExtractor; - @BeforeEach void loadTestData() throws IOException { + @BeforeEach + void loadTestData() throws IOException { if (repository.count() == 0) { repository.save(Product.of("cat", "classpath:/images/cat.jpg", - "The cat (Felis catus) is a domestic species of small carnivorous mammal.")); + "The cat (Felis catus) is a domestic species of small carnivorous mammal.")); repository.save(Product.of("cat2", "classpath:/images/cat2.jpg", - "It is the only domesticated species in the family Felidae and is commonly referred to as the domestic cat or house cat")); - repository.save(Product.of("catdog", "classpath:/images/catdog.jpg", "This is a picture of a cat and a dog together")); - repository.save(Product.of("face", "classpath:/images/face.jpg", "Three years later, the coffin was still full of Jello.")); - repository.save(Product.of("face2", "classpath:/images/face2.jpg", "The person box was packed with jelly many dozens of months later.")); + "It is the only domesticated species in the family Felidae and is commonly referred to as the domestic cat or house cat")); + repository.save( + Product.of("catdog", "classpath:/images/catdog.jpg", "This is a picture of a cat and a dog together")); + repository.save( + Product.of("face", "classpath:/images/face.jpg", "Three years later, the coffin was still full of Jello.")); + repository.save(Product.of("face2", "classpath:/images/face2.jpg", + "The person box was packed with jelly many dozens of months later.")); } } @Test @EnabledIf( - expression = "#{@featureExtractor.isReady()}", // - loadContext = true // - ) + expression = "#{@featureExtractor.isReady()}", // + loadContext = true // + ) void testImageIsVectorized() { Optional cat = repository.findFirstByName("cat"); assertAll( // - () -> assertThat(cat).isPresent(), // - () -> assertThat(cat.get()).extracting("imageEmbedding").isNotNull(), // - () -> assertThat(cat.get().getImageEmbedding()).hasSize(512*Float.BYTES) - ); + () -> assertThat(cat).isPresent(), // + () -> assertThat(cat.get()).extracting("imageEmbedding").isNotNull(), // + () -> assertThat(cat.get().getImageEmbedding()).hasSize(512 * Float.BYTES)); } @Test @EnabledIf( - expression = "#{@featureExtractor.isReady()}", // - loadContext = true // - ) + expression = "#{@featureExtractor.isReady()}", // + loadContext = true // + ) void testSentenceIsVectorized() { Optional cat = repository.findFirstByName("cat"); assertAll( // - () -> assertThat(cat).isPresent(), // - () -> assertThat(cat.get()).extracting("sentenceEmbedding").isNotNull(), // - () -> assertThat(cat.get().getSentenceEmbedding()).hasSize(768*Float.BYTES) - ); + () -> assertThat(cat).isPresent(), // + () -> assertThat(cat.get()).extracting("sentenceEmbedding").isNotNull(), // + () -> assertThat(cat.get().getSentenceEmbedding()).hasSize(768 * Float.BYTES)); } @Test @EnabledIf( - expression = "#{@featureExtractor.isReady()}", // - loadContext = true // - ) + expression = "#{@featureExtractor.isReady()}", // + loadContext = true // + ) void testKnnImageSimilaritySearch() { Product cat = repository.findFirstByName("cat").get(); int K = 5; @@ -80,10 +85,10 @@ void testKnnImageSimilaritySearch() { SearchStream stream = entityStream.of(Product.class); List results = stream // - .filter(Product$.IMAGE_EMBEDDING.knn(K, cat.getImageEmbedding())) // - .sorted(Product$._IMAGE_EMBEDDING_SCORE) // - .limit(K) // - .collect(Collectors.toList()); + .filter(Product$.IMAGE_EMBEDDING.knn(K, cat.getImageEmbedding())) // + .sorted(Product$._IMAGE_EMBEDDING_SCORE) // + .limit(K) // + .collect(Collectors.toList()); assertThat(results).hasSize(5).map(Product::getName).containsExactly( // "cat", "cat2", "catdog", "face", "face2" // @@ -92,9 +97,9 @@ void testKnnImageSimilaritySearch() { @Test @EnabledIf( - expression = "#{@featureExtractor.isReady()}", // - loadContext = true // - ) + expression = "#{@featureExtractor.isReady()}", // + loadContext = true // + ) void testKnnSentenceSimilaritySearch() { Product cat = repository.findFirstByName("cat").get(); int K = 5; @@ -102,10 +107,10 @@ void testKnnSentenceSimilaritySearch() { SearchStream stream = entityStream.of(Product.class); List results = stream // - .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) // - .sorted(Product$._SENTENCE_EMBEDDING_SCORE) // - .limit(K) // - .collect(Collectors.toList()); + .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) // + .sorted(Product$._SENTENCE_EMBEDDING_SCORE) // + .limit(K) // + .collect(Collectors.toList()); assertThat(results).hasSize(5).map(Product::getName).containsExactly( // "cat", "cat2", "catdog", "face", "face2" // @@ -146,7 +151,7 @@ void testKnnSentenceSimilaritySearchWithScores() { SearchStream stream = entityStream.of(Product.class); - List> results = stream // + List> results = stream // .filter(Product$.SENTENCE_EMBEDDING.knn(K, cat.getSentenceEmbedding())) // .sorted(Product$._SENTENCE_EMBEDDING_SCORE) // .limit(K) // @@ -154,8 +159,10 @@ void testKnnSentenceSimilaritySearchWithScores() { .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(5).map(Pair::getFirst).map(Product::getName).containsExactly( "cat", "cat2", "catdog", "face", "face2"), // - () -> assertThat(results).hasSize(5).map(Pair::getSecond).usingElementComparator(closeToComparator).containsExactly(0.0, 0.6704, 0.7162, 0.7705, 0.8107) // + () -> assertThat(results).hasSize(5).map(Pair::getFirst).map(Product::getName) + .containsExactly("cat", "cat2", "catdog", "face", "face2"), // + () -> assertThat(results).hasSize(5).map(Pair::getSecond).usingElementComparator(closeToComparator) + .containsExactly(0.0, 0.6704, 0.7162, 0.7705, 0.8107) // ); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/face/FaceDetectionTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/face/FaceDetectionTest.java index bfa28cfa..8b3a5561 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/face/FaceDetectionTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/annotations/hash/vectorize/face/FaceDetectionTest.java @@ -23,14 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertAll; class FaceDetectionTest extends AbstractBaseEnhancedRedisTest { - @Autowired - private ApplicationContext applicationContext; - @Autowired(required = false) public ZooModel faceDetectionModel; - @Autowired(required = false) public ZooModel faceEmbeddingModel; + @Autowired + private ApplicationContext applicationContext; @Test void testFaceDetection() throws TranslateException, IOException { @@ -40,14 +38,14 @@ void testFaceDetection() throws TranslateException, IOException { try (Predictor predictor = faceDetectionModel.newPredictor()) { DetectedObjects detection = predictor.predict(img); List detectedObjects = IntStream // - .range(0, detection.getNumberOfObjects()) // - .mapToObj(i -> (DetectedObject)detection.item(i)) // - .collect(Collectors.toList()); + .range(0, detection.getNumberOfObjects()) // + .mapToObj(i -> (DetectedObject) detection.item(i)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(detectedObjects).hasSize(338), - () -> assertThat(detectedObjects).map(DetectedObject::getClassName).allMatch(cn -> cn.equalsIgnoreCase("Face")) - ); + () -> assertThat(detectedObjects).hasSize(338), + () -> assertThat(detectedObjects).map(DetectedObject::getClassName) + .allMatch(cn -> cn.equalsIgnoreCase("Face"))); } } } @@ -62,7 +60,7 @@ void testFaceEmbedding() throws TranslateException, IOException { byte[] embeddingAsByteArray = floatArrayToByteArray(embedding); assertAll( // - () -> assertThat(embedding).hasSize(512), () -> assertThat(embeddingAsByteArray).hasSize(2048)); + () -> assertThat(embedding).hasSize(512), () -> assertThat(embeddingAsByteArray).hasSize(2048)); } } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/client/RedisModulesClientTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/client/RedisModulesClientTest.java index 1aed7b71..43d92aca 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/client/RedisModulesClientTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/client/RedisModulesClientTest.java @@ -15,19 +15,6 @@ class RedisModulesClientTest extends AbstractBaseDocumentTest { @Autowired Gson gson; - - /* A simple class that represents an object in real life */ - @SuppressWarnings("unused") - private static class IRLObject { - public final String str; - public final boolean bTrue; - - public IRLObject() { - this.str = "string"; - this.bTrue = true; - } - } - @Autowired RedisModulesClient client; @@ -36,7 +23,7 @@ void testJSONClient() { RedisJsonCommands jsonClient = client.clientForJSON(); IRLObject obj = new IRLObject(); - jsonClient.jsonSetLegacy("obj", obj); + jsonClient.jsonSetWithEscape("obj", obj); Object expected = gson.fromJson(gson.toJson(obj), Object.class); assertEquals(expected, jsonClient.jsonGet("obj")); } @@ -53,4 +40,16 @@ void testBloomClient() { assertNotNull(bloomClient); } + /* A simple class that represents an object in real life */ + @SuppressWarnings("unused") + private static class IRLObject { + public final String str; + public final boolean bTrue; + + public IRLObject() { + this.str = "string"; + this.bTrue = true; + } + } + } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/id/ULIDIdentifierTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/id/ULIDIdentifierTest.java index c466460c..0300a04d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/id/ULIDIdentifierTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/id/ULIDIdentifierTest.java @@ -22,25 +22,26 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("SpellCheckingInspection") class ULIDIdentifierTest extends AbstractBaseEnhancedRedisTest { - +@SuppressWarnings("SpellCheckingInspection") +class ULIDIdentifierTest extends AbstractBaseEnhancedRedisTest { + private final ULIDIdentifierGenerator generator = ULIDIdentifierGenerator.INSTANCE; @Autowired PersonRepository repository; - + @Autowired BadDocRepository badDocRepo; - + @Autowired DocWithExplicitUlidIdRepository docWithUlidRepo; - + @Autowired DocWithIntegerIdRepository docWithIntRepo; - + @Autowired RedisModulesOperations modulesOperations; - + @Test void testMonotonicallyIncreasingUlidAssignment() { Person ofer = Person.of("Ofer Bengal", "ofer@redis.com", "ofer"); @@ -52,34 +53,38 @@ void testMonotonicallyIncreasingUlidAssignment() { Ulid yiftachUlid = Ulid.from(yiftachId); assertTrue(oferUlid.getInstant().isBefore(yiftachUlid.getInstant())); } - + @Test void testUnsupportedIdTypesThrowException() { BadDoc badDoc = new BadDoc(); - InvalidDataAccessApiUsageException exception = Assertions.assertThrows(InvalidDataAccessApiUsageException.class, () -> badDocRepo.save(badDoc)); + InvalidDataAccessApiUsageException exception = Assertions.assertThrows(InvalidDataAccessApiUsageException.class, + () -> badDocRepo.save(badDoc)); - String expectedErrorMessage = String.format("Identifier cannot be generated for %s. Supported types are: ULID, String, Integer, and Long.", BigInteger.class.getName()); + String expectedErrorMessage = String.format( + "Identifier cannot be generated for %s. Supported types are: ULID, String, Integer, and Long.", + BigInteger.class.getName()); Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - + @Test void testExplicitUlid() { JSONOperations ops = modulesOperations.opsForJSON(); - + DocWithExplicitUlidId ulidDoc = new DocWithExplicitUlidId(); Ulid generatedId = docWithUlidRepo.save(ulidDoc).getId(); - - JsonObject rawJSON = ops.get(DocWithExplicitUlidId.class.getName() + ":" + generatedId.toString(), JsonObject.class); + + JsonObject rawJSON = ops.get(DocWithExplicitUlidId.class.getName() + ":" + generatedId.toString(), + JsonObject.class); String ulidAsString = Objects.requireNonNull(rawJSON).get("id").getAsString(); Ulid ulidFromRawJSON = Ulid.from(ulidAsString); - + assertThat(ulidFromRawJSON).isEqualByComparingTo(generatedId); } - + @Test void shouldThrowExceptionForUnsupportedType() { - assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) - .isThrownBy(() -> generator.generateIdentifierOfType(TypeInformation.of(Date.class))); + assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy( + () -> generator.generateIdentifierOfType(TypeInformation.of(Date.class))); } @Test @@ -89,16 +94,16 @@ void shouldGenerateUlidValueCorrectly() { assertThat(value).isNotNull().isInstanceOf(Ulid.class); } - + @Test void testIntegerId() { JSONOperations ops = modulesOperations.opsForJSON(); - + DocWithIntegerId intDoc = new DocWithIntegerId(); Integer generatedId = docWithIntRepo.save(intDoc).getId(); - + JsonObject rawJSON = ops.get(DocWithIntegerId.class.getName() + ":" + generatedId.toString(), JsonObject.class); - + assertThat(Objects.requireNonNull(rawJSON).get("id").getAsInt()).isEqualByComparingTo(generatedId); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/metamodel/MetamodelGeneratorTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/metamodel/MetamodelGeneratorTest.java index 1798b846..b56b111a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/metamodel/MetamodelGeneratorTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/metamodel/MetamodelGeneratorTest.java @@ -17,7 +17,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings("SpellCheckingInspection") @ExtendWith(JavacExtension.class) +@SuppressWarnings("SpellCheckingInspection") +@ExtendWith(JavacExtension.class) @Options("-Werror") @Processors({ MetamodelGenerator.class }) class MetamodelGeneratorTest { @@ -38,75 +39,101 @@ void testValidDocumentIndexed(Results results) throws IOException { assertAll( // - // test package matches source package - () -> assertThat(fileContents).contains("package valid;"), // - - // test Fields generation - () -> assertThat(fileContents).contains("public static Field createdDate;"), // - () -> assertThat(fileContents).contains("public static Field lastModifiedDate;"), // - () -> assertThat(fileContents).contains("public static Field email;"), // - () -> assertThat(fileContents).contains("public static Field publiclyListed;"), // - () -> assertThat(fileContents).contains("public static Field lastValuation;"), // - () -> assertThat(fileContents).contains("public static Field id;"), // - () -> assertThat(fileContents).contains("public static Field yearFounded;"), // - () -> assertThat(fileContents).contains("public static Field name;"), // - () -> assertThat(fileContents).contains("public static Field location;"), // - () -> assertThat(fileContents).contains("public static Field tags;"), // - - // test fields initialization - () -> assertThat(fileContents) - .contains("createdDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"createdDate\");"), // - () -> assertThat(fileContents) - .contains("lastModifiedDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"lastModifiedDate\");"), // - () -> assertThat(fileContents).contains("email = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"email\");"), // - () -> assertThat(fileContents) - .contains("publiclyListed = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"publiclyListed\");"), // - () -> assertThat(fileContents) - .contains("lastValuation = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"lastValuation\");"), // - () -> assertThat(fileContents).contains("id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"id\");"), // - () -> assertThat(fileContents) - .contains("yearFounded = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"yearFounded\");"), // - () -> assertThat(fileContents).contains("name = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"name\");"), // - () -> assertThat(fileContents) - .contains("location = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"location\");"), // - () -> assertThat(fileContents).contains("tags = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"tags\");"), // - - // test Metamodel Field generation - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField CREATED_DATE;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField LAST_MODIFIED_DATE;"), // - () -> assertThat(fileContents).contains("public static TextTagField EMAIL;"), // - () -> assertThat(fileContents) - .contains("public static BooleanField PUBLICLY_LISTED;"), // - () -> assertThat(fileContents) - .contains("public static DateField LAST_VALUATION;"), // - () -> assertThat(fileContents).contains("public static TextTagField ID;"), // - () -> assertThat(fileContents) - .contains("public static NumericField YEAR_FOUNDED;"), // - () -> assertThat(fileContents).contains("public static TextField NAME;"), // - () -> assertThat(fileContents).contains("public static GeoField LOCATION;"), // - () -> assertThat(fileContents).contains("public static TagField> TAGS;"), // - - // test Metamodel Field initialization - () -> assertThat(fileContents) - .contains("CREATED_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"createdDate\", \"$.createdDate\", createdDate),false);"), // - () -> assertThat(fileContents).contains( - "LAST_MODIFIED_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"lastModifiedDate\", \"$.lastModifiedDate\", lastModifiedDate),false);"), // - () -> assertThat(fileContents) - .contains("PUBLICLY_LISTED = new BooleanField(new SearchFieldAccessor(\"publiclyListed\", \"$.publiclyListed\", publiclyListed),true);"), // - () -> assertThat(fileContents) - .contains("LAST_VALUATION = new DateField(new SearchFieldAccessor(\"lastValuation\", \"$.lastValuation\", lastValuation),true);"), // - () -> assertThat(fileContents) - .contains("ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), // - () -> assertThat(fileContents) - .contains("YEAR_FOUNDED = new NumericField(new SearchFieldAccessor(\"yearFounded\", \"$.yearFounded\", yearFounded),true);"), // - () -> assertThat(fileContents).contains("NAME = new TextField(new SearchFieldAccessor(\"name\", \"$.name\", name),true);"), // - () -> assertThat(fileContents).contains("LOCATION = new GeoField(new SearchFieldAccessor(\"location\", \"$.location\", location),true);"), // - () -> assertThat(fileContents).contains("TAGS = new TagField>(new SearchFieldAccessor(\"tags\", \"$.tags\", tags),true);"), // - () -> assertThat(fileContents).contains("EMAIL = new TextTagField(new SearchFieldAccessor(\"email\", \"$.email\", email),true);"), - () -> assertThat(fileContents).contains("_KEY = new MetamodelField(\"__key\", String.class, true);") - ); + // test package matches source package + () -> assertThat(fileContents).contains("package valid;"), // + + // test Fields generation + () -> assertThat(fileContents).contains("public static Field createdDate;"), // + () -> assertThat(fileContents).contains("public static Field lastModifiedDate;"), // + () -> assertThat(fileContents).contains("public static Field email;"), // + () -> assertThat(fileContents).contains("public static Field publiclyListed;"), // + () -> assertThat(fileContents).contains("public static Field lastValuation;"), // + () -> assertThat(fileContents).contains("public static Field id;"), // + () -> assertThat(fileContents).contains("public static Field yearFounded;"), // + () -> assertThat(fileContents).contains("public static Field name;"), // + () -> assertThat(fileContents).contains("public static Field location;"), // + () -> assertThat(fileContents).contains("public static Field tags;"), // + + // test fields initialization + () -> assertThat(fileContents).contains( + "createdDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"createdDate\");"), + // + () -> assertThat(fileContents).contains( + "lastModifiedDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"lastModifiedDate\");"), + // + () -> assertThat(fileContents).contains( + "email = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"email\");"), + // + () -> assertThat(fileContents).contains( + "publiclyListed = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"publiclyListed\");"), + // + () -> assertThat(fileContents).contains( + "lastValuation = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"lastValuation\");"), + // + () -> assertThat(fileContents).contains( + "id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"id\");"), + // + () -> assertThat(fileContents).contains( + "yearFounded = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"yearFounded\");"), + // + () -> assertThat(fileContents).contains( + "name = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"name\");"), + // + () -> assertThat(fileContents).contains( + "location = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"location\");"), + // + () -> assertThat(fileContents).contains( + "tags = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexed.class, \"tags\");"), + // + + // test Metamodel Field generation + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField CREATED_DATE;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField LAST_MODIFIED_DATE;"), // + () -> assertThat(fileContents).contains("public static TextTagField EMAIL;"), // + () -> assertThat(fileContents).contains( + "public static BooleanField PUBLICLY_LISTED;"), // + () -> assertThat(fileContents).contains( + "public static DateField LAST_VALUATION;"), // + () -> assertThat(fileContents).contains("public static TextTagField ID;"), // + () -> assertThat(fileContents).contains( + "public static NumericField YEAR_FOUNDED;"), // + () -> assertThat(fileContents).contains("public static TextField NAME;"), // + () -> assertThat(fileContents).contains("public static GeoField LOCATION;"), // + () -> assertThat(fileContents).contains("public static TagField> TAGS;"), // + + // test Metamodel Field initialization + () -> assertThat(fileContents).contains( + "CREATED_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"createdDate\", \"$.createdDate\", createdDate),false);"), + // + () -> assertThat(fileContents).contains( + "LAST_MODIFIED_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"lastModifiedDate\", \"$.lastModifiedDate\", lastModifiedDate),false);"), + // + () -> assertThat(fileContents).contains( + "PUBLICLY_LISTED = new BooleanField(new SearchFieldAccessor(\"publiclyListed\", \"$.publiclyListed\", publiclyListed),true);"), + // + () -> assertThat(fileContents).contains( + "LAST_VALUATION = new DateField(new SearchFieldAccessor(\"lastValuation\", \"$.lastValuation\", lastValuation),true);"), + // + () -> assertThat(fileContents).contains( + "ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), // + () -> assertThat(fileContents).contains( + "YEAR_FOUNDED = new NumericField(new SearchFieldAccessor(\"yearFounded\", \"$.yearFounded\", yearFounded),true);"), + // + () -> assertThat(fileContents).contains( + "NAME = new TextField(new SearchFieldAccessor(\"name\", \"$.name\", name),true);"), + // + () -> assertThat(fileContents).contains( + "LOCATION = new GeoField(new SearchFieldAccessor(\"location\", \"$.location\", location),true);"), + // + () -> assertThat(fileContents).contains( + "TAGS = new TagField>(new SearchFieldAccessor(\"tags\", \"$.tags\", tags),true);"), + // + () -> assertThat(fileContents).contains( + "EMAIL = new TextTagField(new SearchFieldAccessor(\"email\", \"$.email\", email),true);"), + () -> assertThat(fileContents).contains( + "_KEY = new MetamodelField(\"__key\", String.class, true);")); } @Test @@ -125,93 +152,125 @@ void testValidDocumentUnindexed(Results results) throws IOException { var fileContents = metamodel.getCharContent(true); assertAll( // - // test package matches source package - () -> assertThat(fileContents).contains("package valid;"), // - - // test Fields generation - () -> assertThat(fileContents).contains("public final class ValidDocumentUnindexed$ {"), // - () -> assertThat(fileContents).contains("public static Field id;"), // - () -> assertThat(fileContents).contains("public static Field ulid;"), // - () -> assertThat(fileContents).contains("public static Field setThings;"), // - () -> assertThat(fileContents).contains("public static Field localDateTime;"), // - () -> assertThat(fileContents).contains("public static Field point;"), // - () -> assertThat(fileContents).contains("public static Field listThings;"), // - () -> assertThat(fileContents).contains("public static Field date;"), // - () -> assertThat(fileContents).contains("public static Field localDate;"), // - () -> assertThat(fileContents).contains("public static Field integerWrapper;"), // - () -> assertThat(fileContents).contains("public static Field integerPrimitive;"), // - () -> assertThat(fileContents).contains("public static Field string;"), // - () -> assertThat(fileContents).contains("public static Field bool;"), // - - // test fields initialization - () -> assertThat(fileContents).contains("id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"id\");"), // - () -> assertThat(fileContents) - .contains("setThings = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"setThings\");"), // - () -> assertThat(fileContents) - .contains("localDateTime = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"localDateTime\");"), // - () -> assertThat(fileContents).contains("point = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"point\");"), // - () -> assertThat(fileContents) - .contains("listThings = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"listThings\");"), // - () -> assertThat(fileContents).contains("date = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"date\");"), // - () -> assertThat(fileContents) - .contains("localDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"localDate\");"), // - () -> assertThat(fileContents).contains("ulid = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"ulid\");"), // - () -> assertThat(fileContents) - .contains("integerWrapper = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"integerWrapper\");"), // - () -> assertThat(fileContents) - .contains("integerPrimitive = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"integerPrimitive\");"), // - () -> assertThat(fileContents).contains("string = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"string\");"), // - () -> assertThat(fileContents).contains("bool = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"bool\");"), // - - // test Metamodel Field generation - () -> assertThat(fileContents) - .contains("public static TextTagField ID;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedTagField> SET_THINGS;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField LOCAL_DATE_TIME;"), // - () -> assertThat(fileContents).contains("public static NonIndexedGeoField POINT;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedTagField> LIST_THINGS;"), // - () -> assertThat(fileContents).contains(" static NonIndexedNumericField DATE;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField LOCAL_DATE;"), // - () -> assertThat(fileContents).contains("public static NonIndexedTextField ULID;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField INTEGER_WRAPPER;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedNumericField INTEGER_PRIMITIVE;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedTextField STRING_;"), // - () -> assertThat(fileContents) - .contains("public static NonIndexedBooleanField BOOL;"), // - - // test Metamodel Field initialization - () -> assertThat(fileContents) - .contains("ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), // - () -> assertThat(fileContents) - .contains("SET_THINGS = new NonIndexedTagField>(new SearchFieldAccessor(\"setThings\", \"$.setThings\", setThings),false);"), // - () -> assertThat(fileContents).contains( - "LOCAL_DATE_TIME = new NonIndexedNumericField(new SearchFieldAccessor(\"localDateTime\", \"$.localDateTime\", localDateTime),false);"), // - () -> assertThat(fileContents) - .contains("POINT = new NonIndexedGeoField(new SearchFieldAccessor(\"point\", \"$.point\", point),false);"), // - () -> assertThat(fileContents) - .contains("LIST_THINGS = new NonIndexedTagField>(new SearchFieldAccessor(\"listThings\", \"$.listThings\", listThings),false);"), // - () -> assertThat(fileContents) - .contains("DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"date\", \"$.date\", date),false);"), // - () -> assertThat(fileContents) - .contains("LOCAL_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"localDate\", \"$.localDate\", localDate),false);"), // - () -> assertThat(fileContents).contains("ULID = new NonIndexedTextField(new SearchFieldAccessor(\"ulid\", \"$.ulid\", ulid),false);"), // - () -> assertThat(fileContents).contains( - "INTEGER_WRAPPER = new NonIndexedNumericField(new SearchFieldAccessor(\"integerWrapper\", \"$.integerWrapper\", integerWrapper),false);"), // - () -> assertThat(fileContents).contains( - "INTEGER_PRIMITIVE = new NonIndexedNumericField(new SearchFieldAccessor(\"integerPrimitive\", \"$.integerPrimitive\", integerPrimitive),false);"), // - () -> assertThat(fileContents) - .contains("STRING_ = new NonIndexedTextField(new SearchFieldAccessor(\"string\", \"$.string\", string),false);"), // - () -> assertThat(fileContents) - .contains("BOOL = new NonIndexedBooleanField(new SearchFieldAccessor(\"bool\", \"$.bool\", bool),false);"), // - () -> assertThat(fileContents) - .contains("_KEY = new MetamodelField(\"__key\", String.class, true);") // + // test package matches source package + () -> assertThat(fileContents).contains("package valid;"), // + + // test Fields generation + () -> assertThat(fileContents).contains("public final class ValidDocumentUnindexed$ {"), // + () -> assertThat(fileContents).contains("public static Field id;"), // + () -> assertThat(fileContents).contains("public static Field ulid;"), // + () -> assertThat(fileContents).contains("public static Field setThings;"), // + () -> assertThat(fileContents).contains("public static Field localDateTime;"), // + () -> assertThat(fileContents).contains("public static Field point;"), // + () -> assertThat(fileContents).contains("public static Field listThings;"), // + () -> assertThat(fileContents).contains("public static Field date;"), // + () -> assertThat(fileContents).contains("public static Field localDate;"), // + () -> assertThat(fileContents).contains("public static Field integerWrapper;"), // + () -> assertThat(fileContents).contains("public static Field integerPrimitive;"), // + () -> assertThat(fileContents).contains("public static Field string;"), // + () -> assertThat(fileContents).contains("public static Field bool;"), // + + // test fields initialization + () -> assertThat(fileContents).contains( + "id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"id\");"), + // + () -> assertThat(fileContents).contains( + "setThings = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"setThings\");"), + // + () -> assertThat(fileContents).contains( + "localDateTime = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"localDateTime\");"), + // + () -> assertThat(fileContents).contains( + "point = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"point\");"), + // + () -> assertThat(fileContents).contains( + "listThings = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"listThings\");"), + // + () -> assertThat(fileContents).contains( + "date = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"date\");"), + // + () -> assertThat(fileContents).contains( + "localDate = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"localDate\");"), + // + () -> assertThat(fileContents).contains( + "ulid = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"ulid\");"), + // + () -> assertThat(fileContents).contains( + "integerWrapper = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"integerWrapper\");"), + // + () -> assertThat(fileContents).contains( + "integerPrimitive = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"integerPrimitive\");"), + // + () -> assertThat(fileContents).contains( + "string = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"string\");"), + // + () -> assertThat(fileContents).contains( + "bool = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentUnindexed.class, \"bool\");"), + // + + // test Metamodel Field generation + () -> assertThat(fileContents).contains("public static TextTagField ID;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedTagField> SET_THINGS;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField LOCAL_DATE_TIME;"), // + () -> assertThat(fileContents).contains("public static NonIndexedGeoField POINT;"), + // + () -> assertThat(fileContents).contains( + "public static NonIndexedTagField> LIST_THINGS;"), // + () -> assertThat(fileContents).contains(" static NonIndexedNumericField DATE;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField LOCAL_DATE;"), // + () -> assertThat(fileContents).contains("public static NonIndexedTextField ULID;"), + // + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField INTEGER_WRAPPER;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedNumericField INTEGER_PRIMITIVE;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedTextField STRING_;"), // + () -> assertThat(fileContents).contains( + "public static NonIndexedBooleanField BOOL;"), // + + // test Metamodel Field initialization + () -> assertThat(fileContents).contains( + "ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), + // + () -> assertThat(fileContents).contains( + "SET_THINGS = new NonIndexedTagField>(new SearchFieldAccessor(\"setThings\", \"$.setThings\", setThings),false);"), + // + () -> assertThat(fileContents).contains( + "LOCAL_DATE_TIME = new NonIndexedNumericField(new SearchFieldAccessor(\"localDateTime\", \"$.localDateTime\", localDateTime),false);"), + // + () -> assertThat(fileContents).contains( + "POINT = new NonIndexedGeoField(new SearchFieldAccessor(\"point\", \"$.point\", point),false);"), + // + () -> assertThat(fileContents).contains( + "LIST_THINGS = new NonIndexedTagField>(new SearchFieldAccessor(\"listThings\", \"$.listThings\", listThings),false);"), + // + () -> assertThat(fileContents).contains( + "DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"date\", \"$.date\", date),false);"), + // + () -> assertThat(fileContents).contains( + "LOCAL_DATE = new NonIndexedNumericField(new SearchFieldAccessor(\"localDate\", \"$.localDate\", localDate),false);"), + // + () -> assertThat(fileContents).contains( + "ULID = new NonIndexedTextField(new SearchFieldAccessor(\"ulid\", \"$.ulid\", ulid),false);"), + // + () -> assertThat(fileContents).contains( + "INTEGER_WRAPPER = new NonIndexedNumericField(new SearchFieldAccessor(\"integerWrapper\", \"$.integerWrapper\", integerWrapper),false);"), + // + () -> assertThat(fileContents).contains( + "INTEGER_PRIMITIVE = new NonIndexedNumericField(new SearchFieldAccessor(\"integerPrimitive\", \"$.integerPrimitive\", integerPrimitive),false);"), + // + () -> assertThat(fileContents).contains( + "STRING_ = new NonIndexedTextField(new SearchFieldAccessor(\"string\", \"$.string\", string),false);"), + // + () -> assertThat(fileContents).contains( + "BOOL = new NonIndexedBooleanField(new SearchFieldAccessor(\"bool\", \"$.bool\", bool),false);"), + // + () -> assertThat(fileContents).contains( + "_KEY = new MetamodelField(\"__key\", String.class, true);") // ); } @@ -221,12 +280,12 @@ void testValidDocumentUnindexed(Results results) throws IOException { void testValidDocumentIndexedNested(Results results) throws IOException { List warnings = getWarningStrings(results); assertThat(warnings).hasSize(1).containsOnly( - "Processing class ValidDocumentIndexedNested could not resolve valid.Address while checking for nested @Indexed"); + "Processing class ValidDocumentIndexedNested could not resolve valid.Address while checking for nested @Indexed"); List errors = getErrorStrings(results); assertAll( // - () -> assertThat(errors).hasSize(1), // - () -> assertThat(errors).containsOnly("warnings found and -Werror specified") // + () -> assertThat(errors).hasSize(1), // + () -> assertThat(errors).containsOnly("warnings found and -Werror specified") // ); assertThat(results.generated).hasSize(1); @@ -237,41 +296,45 @@ void testValidDocumentIndexedNested(Results results) throws IOException { assertAll( // - // test package matches source package - () -> assertThat(fileContents).contains("package valid;"), // - - // test Fields generation - () -> assertThat(fileContents).contains("public final class ValidDocumentIndexedNested$ {"), // - () -> assertThat(fileContents).contains("public static Field id;"), // - () -> assertThat(fileContents).contains("public static Field address_street;"), // - () -> assertThat(fileContents).contains("public static Field address_city;"), // - - // test fields initialization - () -> assertThat(fileContents) - .contains("id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"id\");"), // - () -> assertThat(fileContents) - .contains("address_street = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"address\").getType(), \"street\");"), // - () -> assertThat(fileContents) - .contains("address_city = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"address\").getType(), \"city\");"), // - - // test Metamodel Field generation - () -> assertThat(fileContents) - .contains("public static TextTagField ID;"), // - () -> assertThat(fileContents) - .contains("public static TextField ADDRESS_STREET;"), // - () -> assertThat(fileContents) - .contains("public static TextTagField ADDRESS_CITY;"), // - - // test Metamodel Field initialization - () -> assertThat(fileContents) - .contains("ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), // - () -> assertThat(fileContents) - .contains("ADDRESS_STREET = new TextField(new SearchFieldAccessor(\"address_street\", \"$.address.street\", address_street),true);"), // - () -> assertThat(fileContents) - .contains("ADDRESS_CITY = new TextTagField(new SearchFieldAccessor(\"address_city\", \"$.address.city\", address_city),true);"), // - () -> assertThat(fileContents) - .contains("_KEY = new MetamodelField(\"__key\", String.class, true);") - ); + // test package matches source package + () -> assertThat(fileContents).contains("package valid;"), // + + // test Fields generation + () -> assertThat(fileContents).contains("public final class ValidDocumentIndexedNested$ {"), // + () -> assertThat(fileContents).contains("public static Field id;"), // + () -> assertThat(fileContents).contains("public static Field address_street;"), // + () -> assertThat(fileContents).contains("public static Field address_city;"), // + + // test fields initialization + () -> assertThat(fileContents).contains( + "id = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"id\");"), + // + () -> assertThat(fileContents).contains( + "address_street = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"address\").getType(), \"street\");"), + // + () -> assertThat(fileContents).contains( + "address_city = com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(com.redis.om.spring.util.ObjectUtils.getDeclaredFieldTransitively(ValidDocumentIndexedNested.class, \"address\").getType(), \"city\");"), + // + + // test Metamodel Field generation + () -> assertThat(fileContents).contains("public static TextTagField ID;"), // + () -> assertThat(fileContents).contains( + "public static TextField ADDRESS_STREET;"), // + () -> assertThat(fileContents).contains( + "public static TextTagField ADDRESS_CITY;"), // + + // test Metamodel Field initialization + () -> assertThat(fileContents).contains( + "ID = new TextTagField(new SearchFieldAccessor(\"id\", \"$.id\", id),true);"), + // + () -> assertThat(fileContents).contains( + "ADDRESS_STREET = new TextField(new SearchFieldAccessor(\"address_street\", \"$.address.street\", address_street),true);"), + // + () -> assertThat(fileContents).contains( + "ADDRESS_CITY = new TextTagField(new SearchFieldAccessor(\"address_city\", \"$.address.city\", address_city),true);"), + // + () -> assertThat(fileContents).contains( + "_KEY = new MetamodelField(\"__key\", String.class, true);")); } @Test @@ -280,14 +343,14 @@ void testValidDocumentUnindexedWithoutPackage(Results results) { assertThat(results.generated).hasSize(1); List warnings = getWarningStrings(results); assertAll( // - () -> assertThat(warnings).hasSize(1), // - () -> assertThat(warnings).containsOnly("Class ValidDocumentUnindexedWoPackage has an unnamed package.") // + () -> assertThat(warnings).hasSize(1), // + () -> assertThat(warnings).containsOnly("Class ValidDocumentUnindexedWoPackage has an unnamed package.") // ); List errors = getErrorStrings(results); assertAll( // - () -> assertThat(errors).hasSize(1), // - () -> assertThat(errors).containsOnly("warnings found and -Werror specified") // + () -> assertThat(errors).hasSize(1), // + () -> assertThat(errors).containsOnly("warnings found and -Werror specified") // ); } @@ -298,16 +361,20 @@ void testValidDocumentInBadJavaBean(Results results) { List errors = getErrorStrings(results); assertAll( // - () -> assertThat(errors).hasSize(3), // - () -> assertThat(errors).contains("Class valid.BadBean is not a proper JavaBean because id has no standard getter."), // - () -> assertThat(errors).contains("Class valid.BadBean is not a proper JavaBean because name has no standard getter."), // - () -> assertThat(errors).contains("Class valid.BadBean is not a proper JavaBean because age has no standard getter.") // + () -> assertThat(errors).hasSize(3), // + () -> assertThat(errors).contains( + "Class valid.BadBean is not a proper JavaBean because id has no standard getter."), // + () -> assertThat(errors).contains( + "Class valid.BadBean is not a proper JavaBean because name has no standard getter."), // + () -> assertThat(errors).contains( + "Class valid.BadBean is not a proper JavaBean because age has no standard getter.") // ); } @Test @Classpath("data.metamodel.IdOnly") - void testValidIdOnlyDocument(Results results) throws IOException {List warnings = getWarningStrings(results); + void testValidIdOnlyDocument(Results results) throws IOException { + List warnings = getWarningStrings(results); assertThat(warnings).isEmpty(); List errors = getErrorStrings(results); @@ -320,22 +387,22 @@ void testValidDocumentInBadJavaBean(Results results) { var fileContents = metamodel.getCharContent(true); var expected = """ - package valid; - - import com.redis.om.spring.metamodel.MetamodelField; - import java.lang.String; - - public final class IdOnly$ { - public static MetamodelField _KEY; - - public static MetamodelField _THIS; - - static { - _KEY = new MetamodelField("__key", String.class, true); - _THIS = new MetamodelField("__this", IdOnly.class, true); + package valid; + + import com.redis.om.spring.metamodel.MetamodelField; + import java.lang.String; + + public final class IdOnly$ { + public static MetamodelField _KEY; + + public static MetamodelField _THIS; + + static { + _KEY = new MetamodelField("__key", String.class, true); + _THIS = new MetamodelField("__this", IdOnly.class, true); + } } - } - """; + """; assertThat(fileContents).containsIgnoringWhitespaces(expected); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/ops/json/OpsForJSONTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/ops/json/OpsForJSONTest.java index bf8302db..b95e44b5 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/ops/json/OpsForJSONTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/ops/json/OpsForJSONTest.java @@ -15,100 +15,6 @@ @SuppressWarnings({ "unused", "SpellCheckingInspection" }) class OpsForJSONTest extends AbstractBaseDocumentTest { - /* A simple class that represents an object in real life */ - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - private static class IRLObject { - public final String str; - public final boolean bTrue; - - public IRLObject() { - this.str = "string"; - this.bTrue = true; - } - - @Override - public boolean equals(Object other) { - IRLObject o = (IRLObject) other; - return this.str.equals(o.str) && this.bTrue == o.bTrue; - } - } - - @SuppressWarnings("unused") - private static class FooBarObject { - public final String foo; - public final boolean fooB; - public final int fooI; - public final float fooF; - public final String[] fooArr; - - public FooBarObject() { - this.foo = "bar"; - this.fooB = true; - this.fooI = 6574; - this.fooF = 435.345f; - this.fooArr = new String[] { "a", "b", "c" }; - } - } - - @SuppressWarnings({ "SpellCheckingInspection", "FieldMayBeFinal" }) - private static class Baz { - private String quuz; - private String grault; - private String waldo; - - public Baz(final String quuz, final String grault, final String waldo) { - this.quuz = quuz; - this.grault = grault; - this.waldo = waldo; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null) - return false; - if (getClass() != o.getClass()) - return false; - Baz other = (Baz) o; - - return Objects.equals(quuz, other.quuz) && // - Objects.equals(grault, other.grault) && // - Objects.equals(waldo, other.waldo); - } - } - - @SuppressWarnings({ "SpellCheckingInspection", "FieldMayBeFinal" }) - private static class Qux { - private String quux; - private String corge; - private String garply; - private Baz baz; - - public Qux(String quux, String corge, String garply, Baz baz) { - this.quux = quux; - this.corge = corge; - this.garply = garply; - this.baz = baz; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null) - return false; - if (getClass() != o.getClass()) - return false; - Qux other = (Qux) o; - - return Objects.equals(quux, other.quux) && // - Objects.equals(corge, other.corge) && // - Objects.equals(garply, other.garply) && // - Objects.equals(baz, other.baz); - } - } - @Autowired RedisModulesOperations modulesOperations; @@ -198,13 +104,13 @@ void testMultipleGetAtRootPathAllKeysExist() { assertEquals(qux1, oneQux.get(0)); Qux testQux1 = allQux.stream() // - .filter(q -> q.quux.equals("quux1")) // - .findFirst() // - .orElseThrow(() -> new NullPointerException("")); + .filter(q -> q.quux.equals("quux1")) // + .findFirst() // + .orElseThrow(() -> new NullPointerException("")); Qux testQux2 = allQux.stream() // - .filter(q -> q.quux.equals("quux2")) // - .findFirst() // - .orElseThrow(() -> new NullPointerException("")); + .filter(q -> q.quux.equals("quux2")) // + .findFirst() // + .orElseThrow(() -> new NullPointerException("")); assertEquals(qux1, testQux1); assertEquals(qux2, testQux2); @@ -268,4 +174,98 @@ void typeChecksShouldSucceed() { assertTrue(ops.type("foobar", Path2.of(".fooErr")).isEmpty()); } + /* A simple class that represents an object in real life */ + @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") + private static class IRLObject { + public final String str; + public final boolean bTrue; + + public IRLObject() { + this.str = "string"; + this.bTrue = true; + } + + @Override + public boolean equals(Object other) { + IRLObject o = (IRLObject) other; + return this.str.equals(o.str) && this.bTrue == o.bTrue; + } + } + + @SuppressWarnings("unused") + private static class FooBarObject { + public final String foo; + public final boolean fooB; + public final int fooI; + public final float fooF; + public final String[] fooArr; + + public FooBarObject() { + this.foo = "bar"; + this.fooB = true; + this.fooI = 6574; + this.fooF = 435.345f; + this.fooArr = new String[] { "a", "b", "c" }; + } + } + + @SuppressWarnings({ "SpellCheckingInspection", "FieldMayBeFinal" }) + private static class Baz { + private String quuz; + private String grault; + private String waldo; + + public Baz(final String quuz, final String grault, final String waldo) { + this.quuz = quuz; + this.grault = grault; + this.waldo = waldo; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (getClass() != o.getClass()) + return false; + Baz other = (Baz) o; + + return Objects.equals(quuz, other.quuz) && // + Objects.equals(grault, other.grault) && // + Objects.equals(waldo, other.waldo); + } + } + + @SuppressWarnings({ "SpellCheckingInspection", "FieldMayBeFinal" }) + private static class Qux { + private String quux; + private String corge; + private String garply; + private Baz baz; + + public Qux(String quux, String corge, String garply, Baz baz) { + this.quux = quux; + this.corge = corge; + this.garply = garply; + this.baz = baz; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (getClass() != o.getClass()) + return false; + Qux other = (Qux) o; + + return Objects.equals(quux, other.quux) && // + Objects.equals(corge, other.corge) && // + Objects.equals(garply, other.garply) && // + Objects.equals(baz, other.baz); + } + } + } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForBloomTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForBloomTest.java index fbec409c..6e493003 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForBloomTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForBloomTest.java @@ -15,7 +15,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings("SpellCheckingInspection") class OpsForBloomTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class OpsForBloomTest extends AbstractBaseDocumentTest { @Autowired RedisModulesOperations modulesOperations; @@ -58,12 +59,10 @@ void testExampleBytesApi() { // If you have a long list of items to check/add, you can use the // "multi" methods - bloom.addMulti("simpleBloom", "foo", "bar", "baz", "bat", - "bag"); + bloom.addMulti("simpleBloom", "foo", "bar", "baz", "bat", "bag"); // Check if they exist: - List rv = bloom.existsMulti("simpleBloom", "foo", "bar", "baz", - "bat", "Mark", "nonexist"); + List rv = bloom.existsMulti("simpleBloom", "foo", "bar", "baz", "bat", "Mark", "nonexist"); // All items except the last one will be 'true' assertThat(List.of(true, true, true, true, true, false)).isEqualTo(rv); @@ -72,7 +71,8 @@ void testExampleBytesApi() { @Test void reserveExpansionNoCreate() { - JedisDataException exception = Assertions.assertThrows(JedisDataException.class, () -> bloom.insert("bfexpansion", BFInsertParams.insertParams().noCreate(), "a", "b", "c")); + JedisDataException exception = Assertions.assertThrows(JedisDataException.class, + () -> bloom.insert("bfexpansion", BFInsertParams.insertParams().noCreate(), "a", "b", "c")); Assertions.assertEquals("ERR not found", exception.getMessage()); template.delete("bfexpansion"); @@ -80,8 +80,8 @@ void reserveExpansionNoCreate() { @Test void reserveExpansion() { - assertThat(bloom.insert("bfexpansion2", BFInsertParams.insertParams().capacity(1000), "a", "b", "c")) - .isEqualTo(List.of(true, true, true)); + assertThat(bloom.insert("bfexpansion2", BFInsertParams.insertParams().capacity(1000), "a", "b", "c")).isEqualTo( + List.of(true, true, true)); template.delete("bfexpansion2"); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForCountMinSketchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForCountMinSketchTest.java index dc046b37..672c222d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForCountMinSketchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForCountMinSketchTest.java @@ -73,7 +73,7 @@ void testMerge() { List q5 = cms.cmsQuery("C", "foo", "bar", "baz"); assertArrayEquals(new Long[] { 16L, 15L, 21L }, q5.toArray(new Long[0])); } - + @Test void testInitByProb() { cms.cmsInitByProb("cms2", 0.01, 0.01); @@ -82,7 +82,7 @@ void testInitByProb() { assertEquals(7L, info.get("depth")); assertEquals(0L, info.get("count")); } - + @Test void testIncrBy() { cms.cmsInitByDim("cms3", 1000L, 5L); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForPDSesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForPDSesTest.java index be570ac6..0a5737d1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForPDSesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/ops/pds/OpsForPDSesTest.java @@ -7,35 +7,36 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; -@SuppressWarnings("SpellCheckingInspection") class OpsForPDSesTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class OpsForPDSesTest extends AbstractBaseDocumentTest { @Autowired RedisModulesOperations modulesOperations; - + @Test void testBasicBloomOperations() { BloomOperations bloom = modulesOperations.opsForBloom(); assertNotNull(bloom); } - + @Test void testBasicCMSOperations() { CountMinSketchOperations cms = modulesOperations.opsForCountMinSketch(); assertNotNull(cms); } - + @Test void testTopKOperations() { TopKOperations topk = modulesOperations.opsForTopK(); - + assertNotNull(topk); } - + @Test void testCuckooKOperations() { CuckooFilterOperations cuckoo = modulesOperations.opsForCuckoFilter(); - + assertNotNull(cuckoo); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/ops/search/JSONSearchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/ops/search/JSONSearchTest.java index 157ed71d..a5413773 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/ops/search/JSONSearchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/ops/search/JSONSearchTest.java @@ -1,5 +1,7 @@ package com.redis.om.spring.ops.search; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import com.redis.om.spring.AbstractBaseDocumentTest; import com.redis.om.spring.ops.RedisModulesOperations; import com.redis.om.spring.ops.json.JSONOperations; @@ -19,34 +21,22 @@ import redis.clients.jedis.util.SafeEncoder; import java.util.HashSet; +import java.util.Map; import java.util.Set; import java.util.stream.StreamSupport; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class JSONSearchTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class JSONSearchTest extends AbstractBaseDocumentTest { public static final String searchIndex = "idx"; - - /* A simple class that represents an object in real life */ - /* '{"title":"hello world", "tag": ["news", "article"]}' */ - private static class SomeJSON { - @SuppressWarnings("unused") - public String title; - public final Set tag = new HashSet<>(); - - public SomeJSON() { - this.title = "hello world"; - this.tag.add("news"); - this.tag.add("article"); - } - } - @Autowired RedisModulesOperations modulesOperations; - @Autowired private StringRedisTemplate template; + private final ObjectMapper objectMapper = new ObjectMapper(); + @BeforeEach void setup() { SearchOperations ops = modulesOperations.opsForSearch(searchIndex); @@ -59,8 +49,8 @@ void setup() { // FT.CREATE idx ON JSON SCHEMA $.title AS title TEXT $.tag[*] AS tag TAG Schema sc = new Schema() // - .addField(new TextField(FieldName.of("$.title").as("title"))) // - .addField(new Field(FieldName.of("$.tag[*]").as("tag"), FieldType.TAG)); + .addField(new TextField(FieldName.of("$.title").as("title"))) // + .addField(new Field(FieldName.of("$.tag[*]").as("tag"), FieldType.TAG)); IndexDefinition def = new IndexDefinition(IndexDefinition.Type.JSON); ops.createIndex(sc, IndexOptions.defaultOptions().setDefinition(def)); @@ -82,14 +72,19 @@ void cleanUp() { * 2) "{\"title\":\"hello world\",\"tag\":[\"news\",\"article\"]}" */ @Test - void testBasicSearchOverJSON() { + void testBasicSearchOverJSON() throws Exception { SearchOperations ops = modulesOperations.opsForSearch(searchIndex); SearchResult result = ops.search(new Query("@title:hello @tag:{news}")); assertEquals(1, result.getTotalResults()); Document doc = result.getDocuments().get(0); assertEquals(1.0, doc.getScore(), 0); - assertEquals("{\"title\":\"hello world\",\"tag\":[\"news\",\"article\"]}", SafeEncoder.encode((byte[])doc.get("$"))); + + String jsonString = SafeEncoder.encode((byte[]) doc.get("$")); + Map actualMap = objectMapper.readValue(jsonString, new TypeReference>() {}); + Map expectedMap = objectMapper.readValue("{\"title\":\"hello world\",\"tag\":[\"news\",\"article\"]}", new TypeReference>() {}); + + assertEquals(expectedMap, actualMap); } /** @@ -107,8 +102,9 @@ void testSearchOverJSONWithPathProjection() { Document doc = result.getDocuments().get(0); assertEquals(1.0, doc.getScore(), 0); assertTrue(StreamSupport // - .stream(doc.getProperties().spliterator(), false) // - .anyMatch(p -> p.getKey().contentEquals("first_tag") && SafeEncoder.encode((byte[])p.getValue()).equals("news"))); + .stream(doc.getProperties().spliterator(), false) // + .anyMatch( + p -> p.getKey().contentEquals("first_tag") && SafeEncoder.encode((byte[]) p.getValue()).equals("news"))); } /** @@ -131,4 +127,18 @@ void testAggregateLoadUsingJSONPath() { assertTrue(row.containsKey("tag2")); assertEquals("article", row.getString("tag2")); } + + /* A simple class that represents an object in real life */ + /* '{"title":"hello world", "tag": ["news", "article"]}' */ + private static class SomeJSON { + public final Set tag = new HashSet<>(); + @SuppressWarnings("unused") + public String title; + + public SomeJSON() { + this.title = "hello world"; + this.tag.add("news"); + this.tag.add("article"); + } + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/AbstractDocument.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/AbstractDocument.java index 45e568a4..2ecab799 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/AbstractDocument.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/AbstractDocument.java @@ -6,30 +6,30 @@ import java.util.UUID; public abstract class AbstractDocument { - @Id - private String id; + @Id + private String id; - @Indexed - private String inherited; + @Indexed + private String inherited; - protected AbstractDocument() { - this.id = UUID.randomUUID().toString(); - this.inherited = "inherited"; - } + protected AbstractDocument() { + this.id = UUID.randomUUID().toString(); + this.inherited = "inherited"; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getInherited() { - return inherited; - } + public String getInherited() { + return inherited; + } - public void setInherited(String inherited) { - this.inherited = inherited; - } + public void setInherited(String inherited) { + this.inherited = inherited; + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/DocumentProjectionTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/DocumentProjectionTest.java index 80e318a0..23e725c3 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/DocumentProjectionTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/DocumentProjectionTest.java @@ -18,56 +18,57 @@ class DocumentProjectionTest extends AbstractBaseDocumentTest { - public static final String TEST_NAME = "testName"; - public static final String TEST_PROP_1 = "test1"; - private final DocumentProjectionRepository documentProjectionRepository; + public static final String TEST_NAME = "testName"; + public static final String TEST_PROP_1 = "test1"; + private final DocumentProjectionRepository documentProjectionRepository; - @Autowired - DocumentProjectionTest(DocumentProjectionRepository documentProjectionRepository) { - this.documentProjectionRepository = documentProjectionRepository; - } + @Autowired + DocumentProjectionTest(DocumentProjectionRepository documentProjectionRepository) { + this.documentProjectionRepository = documentProjectionRepository; + } - @BeforeEach - void setUp() { - for (int i = 0; i < 2; i++) { - DocumentProjectionPojo entity = new DocumentProjectionPojo(); - entity.setName(TEST_NAME); - entity.setTest(TEST_PROP_1); - documentProjectionRepository.save(entity); - } + @BeforeEach + void setUp() { + for (int i = 0; i < 2; i++) { + DocumentProjectionPojo entity = new DocumentProjectionPojo(); + entity.setName(TEST_NAME); + entity.setTest(TEST_PROP_1); + documentProjectionRepository.save(entity); } + } - @Test - void testProjectionSingleEntityReturnType() { - Optional byNameProjection = documentProjectionRepository.findByName(TEST_NAME); - assertTrue(byNameProjection.isPresent()); - assertEquals(TEST_NAME, byNameProjection.get().getName()); - assertNotNull(byNameProjection.get().getSpelTest()); - assertEquals(TEST_NAME + " " + TEST_PROP_1, byNameProjection.get().getSpelTest()); - } + @Test + void testProjectionSingleEntityReturnType() { + Optional byNameProjection = documentProjectionRepository.findByName(TEST_NAME); + assertTrue(byNameProjection.isPresent()); + assertEquals(TEST_NAME, byNameProjection.get().getName()); + assertNotNull(byNameProjection.get().getSpelTest()); + assertEquals(TEST_NAME + " " + TEST_PROP_1, byNameProjection.get().getSpelTest()); + } - @Test - void testProjectionCollectionReturnType() { - Collection byNameProjection = documentProjectionRepository.findAllByName(TEST_NAME); - assertNotNull(byNameProjection); - assertEquals(2, byNameProjection.size()); - byNameProjection.forEach(documentProjection -> { - assertNotNull(documentProjection.getName()); - assertNotNull(documentProjection.getSpelTest()); - }); - } + @Test + void testProjectionCollectionReturnType() { + Collection byNameProjection = documentProjectionRepository.findAllByName(TEST_NAME); + assertNotNull(byNameProjection); + assertEquals(2, byNameProjection.size()); + byNameProjection.forEach(documentProjection -> { + assertNotNull(documentProjection.getName()); + assertNotNull(documentProjection.getSpelTest()); + }); + } - @Test - void testProjectionPageReturnType() { - Page byNameProjection = documentProjectionRepository.findAllByName(TEST_NAME, Pageable.ofSize(1)); - assertNotNull(byNameProjection); - assertEquals(1, byNameProjection.getNumberOfElements()); - assertEquals(2, byNameProjection.getTotalPages()); - } + @Test + void testProjectionPageReturnType() { + Page byNameProjection = documentProjectionRepository.findAllByName(TEST_NAME, + Pageable.ofSize(1)); + assertNotNull(byNameProjection); + assertEquals(1, byNameProjection.getNumberOfElements()); + assertEquals(2, byNameProjection.getTotalPages()); + } - @AfterEach - void tearDown() { - documentProjectionRepository.deleteAll(); - } + @AfterEach + void tearDown() { + documentProjectionRepository.deleteAll(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/HashProjectionTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/HashProjectionTest.java index 86fc78b5..7ca849c4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/HashProjectionTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/HashProjectionTest.java @@ -10,68 +10,64 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.projection.SpelAwareProxyProjectionFactory; -import org.springframework.data.redis.core.mapping.RedisMappingContext; import java.util.Collection; -import java.util.HashMap; -import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; class HashProjectionTest extends AbstractBaseEnhancedRedisTest { - public static final String TEST_NAME = "testName"; - public static final String TEST_PROP_1 = "test1"; - private final HashProjectionRepository hashProjectionRepository; + public static final String TEST_NAME = "testName"; + public static final String TEST_PROP_1 = "test1"; + private final HashProjectionRepository hashProjectionRepository; - @Autowired - HashProjectionTest(HashProjectionRepository hashProjectionRepository) { - this.hashProjectionRepository = hashProjectionRepository; - } + @Autowired + HashProjectionTest(HashProjectionRepository hashProjectionRepository) { + this.hashProjectionRepository = hashProjectionRepository; + } - @BeforeEach - void setUp() { - for (int i = 0; i < 2; i++) { - HashProjectionPojo entity = new HashProjectionPojo(); - entity.setName(TEST_NAME); - entity.setTest(TEST_PROP_1); - hashProjectionRepository.save(entity); - } + @BeforeEach + void setUp() { + for (int i = 0; i < 2; i++) { + HashProjectionPojo entity = new HashProjectionPojo(); + entity.setName(TEST_NAME); + entity.setTest(TEST_PROP_1); + hashProjectionRepository.save(entity); } + } - @Test - void testProjectionSingleEntityReturnType() { - Optional byNameProjection = hashProjectionRepository.findByName(TEST_NAME); - assertTrue(byNameProjection.isPresent()); - assertEquals(TEST_NAME, byNameProjection.get().getName()); - assertNotNull(byNameProjection.get().getSpelTest()); - assertEquals(TEST_NAME + " " + TEST_PROP_1, byNameProjection.get().getSpelTest()); - } + @Test + void testProjectionSingleEntityReturnType() { + Optional byNameProjection = hashProjectionRepository.findByName(TEST_NAME); + assertTrue(byNameProjection.isPresent()); + assertEquals(TEST_NAME, byNameProjection.get().getName()); + assertNotNull(byNameProjection.get().getSpelTest()); + assertEquals(TEST_NAME + " " + TEST_PROP_1, byNameProjection.get().getSpelTest()); + } - @Test - void testProjectionCollectionReturnType() { - Collection byNameProjection = hashProjectionRepository.findAllByName(TEST_NAME); - assertNotNull(byNameProjection); - assertEquals(2, byNameProjection.size()); - byNameProjection.forEach(documentProjection -> { - assertNotNull(documentProjection.getName()); - assertNotNull(documentProjection.getSpelTest()); - }); - } + @Test + void testProjectionCollectionReturnType() { + Collection byNameProjection = hashProjectionRepository.findAllByName(TEST_NAME); + assertNotNull(byNameProjection); + assertEquals(2, byNameProjection.size()); + byNameProjection.forEach(documentProjection -> { + assertNotNull(documentProjection.getName()); + assertNotNull(documentProjection.getSpelTest()); + }); + } - @Test - void testProjectionPageReturnType() { - Page byNameProjection = hashProjectionRepository.findAllByName(TEST_NAME, Pageable.ofSize(1)); - assertNotNull(byNameProjection); - assertEquals(1, byNameProjection.getNumberOfElements()); - assertEquals(2, byNameProjection.getTotalPages()); - } + @Test + void testProjectionPageReturnType() { + Page byNameProjection = hashProjectionRepository.findAllByName(TEST_NAME, Pageable.ofSize(1)); + assertNotNull(byNameProjection); + assertEquals(1, byNameProjection.getNumberOfElements()); + assertEquals(2, byNameProjection.getTotalPages()); + } - @AfterEach - void tearDown() { - hashProjectionRepository.deleteAll(); - } + @AfterEach + void tearDown() { + hashProjectionRepository.deleteAll(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocument.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocument.java index 431fa6c8..e01762d3 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocument.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocument.java @@ -5,19 +5,19 @@ @Document public class InheritingDocument extends AbstractDocument { - @Indexed - private String notInherited; + @Indexed + private String notInherited; - public InheritingDocument() { - super(); - this.notInherited = "notInherited"; - } + public InheritingDocument() { + super(); + this.notInherited = "notInherited"; + } - public String getNotInherited() { - return notInherited; - } + public String getNotInherited() { + return notInherited; + } - public void setNotInherited(String notInherited) { - this.notInherited = notInherited; - } + public void setNotInherited(String notInherited) { + this.notInherited = notInherited; + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocumentTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocumentTest.java index c14fa8f4..8423ae45 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocumentTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/InheritingDocumentTest.java @@ -15,60 +15,57 @@ import static org.assertj.core.api.Assumptions.assumeThat; class InheritingDocumentTest extends AbstractBaseDocumentTest { - private static final int SIZE = 20; + private static final int SIZE = 20; - private final InheritingDocumentRepository inheritingDocumentRepository; - private final SearchOperations searchOperations; + private final InheritingDocumentRepository inheritingDocumentRepository; + private final SearchOperations searchOperations; - @Autowired - InheritingDocumentTest(InheritingDocumentRepository inheritingDocumentRepository, RedisModulesOperations redisModulesOperations) { - this.inheritingDocumentRepository = inheritingDocumentRepository; - this.searchOperations = redisModulesOperations.opsForSearch(InheritingDocument.class.getName() + "Idx"); - } + @Autowired + InheritingDocumentTest(InheritingDocumentRepository inheritingDocumentRepository, + RedisModulesOperations redisModulesOperations) { + this.inheritingDocumentRepository = inheritingDocumentRepository; + this.searchOperations = redisModulesOperations.opsForSearch(InheritingDocument.class.getName() + "Idx"); + } - @BeforeEach - void setUp() { - for (int i = 0; i < SIZE; ++i) { - inheritingDocumentRepository.save(new InheritingDocument()); - } + @BeforeEach + void setUp() { + for (int i = 0; i < SIZE; ++i) { + inheritingDocumentRepository.save(new InheritingDocument()); } + } - @Test - @SuppressWarnings("unchecked") - void testIndexCreatedCorrectly() { - Map info = searchOperations.getInfo(); - Object rawAttributes = info.get("attributes"); - assertThat(rawAttributes).isNotNull().isInstanceOf(List.class); - List attributes = (List) rawAttributes; - assertThat(attributes).hasSize(3) - .allSatisfy(element -> { - assertThat(element).isInstanceOf(List.class); - assertThat((List) element).allSatisfy(item -> assertThat(item).isInstanceOf(String.class)); - }) - .map(element -> (List) element) // cast is checked through assertion - .extracting((List attribute) -> { - for (int i = 0; i < attribute.size(); i++) { - String value = attribute.get(i); - if ("attribute".equals(value)) { - return attribute.get(i + 1); - } - } - return null; - }) - .doesNotContain((String) null) - .containsExactlyInAnyOrderElementsOf(List.of("id", "inherited", "notInherited")); - } + @Test + @SuppressWarnings("unchecked") + void testIndexCreatedCorrectly() { + Map info = searchOperations.getInfo(); + Object rawAttributes = info.get("attributes"); + assertThat(rawAttributes).isNotNull().isInstanceOf(List.class); + List attributes = (List) rawAttributes; + assertThat(attributes).hasSize(3).allSatisfy(element -> { + assertThat(element).isInstanceOf(List.class); + assertThat((List) element).allSatisfy(item -> assertThat(item).isInstanceOf(String.class)); + }).map(element -> (List) element) // cast is checked through assertion + .extracting((List attribute) -> { + for (int i = 0; i < attribute.size(); i++) { + String value = attribute.get(i); + if ("attribute".equals(value)) { + return attribute.get(i + 1); + } + } + return null; + }).doesNotContain((String) null).containsExactlyInAnyOrderElementsOf(List.of("id", "inherited", "notInherited")); + } - @Test - void testAllInheritedDocumentsReturned() { - assumeThat(inheritingDocumentRepository.count()).isEqualTo(SIZE); + @Test + void testAllInheritedDocumentsReturned() { + assumeThat(inheritingDocumentRepository.count()).isEqualTo(SIZE); - List documents = inheritingDocumentRepository.findAll(); - assertThat(documents).isNotNull().hasSize(SIZE); - } + List documents = inheritingDocumentRepository.findAll(); + assertThat(documents).isNotNull().hasSize(SIZE); + } - @AfterEach - void tearDown() { - inheritingDocumentRepository.deleteAll(); - } + @AfterEach + void tearDown() { + inheritingDocumentRepository.deleteAll(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocument.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocument.java index 84ac7c96..828fec35 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocument.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocument.java @@ -7,18 +7,18 @@ @Document public class SimpleDocument { - @Id - private String id; + @Id + private String id; - public SimpleDocument() { - this.id = UUID.randomUUID().toString(); - } + public SimpleDocument() { + this.id = UUID.randomUUID().toString(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocumentTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocumentTest.java index fc22c434..a2fb0808 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocumentTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleDocumentTest.java @@ -13,32 +13,32 @@ class SimpleDocumentTest extends AbstractBaseDocumentTest { - private static final int SIZE = 20; + private static final int SIZE = 20; - private final SimpleDocumentRepository simpleDocumentRepository; + private final SimpleDocumentRepository simpleDocumentRepository; - @Autowired - SimpleDocumentTest(SimpleDocumentRepository simpleDocumentRepository) { - this.simpleDocumentRepository = simpleDocumentRepository; - } + @Autowired + SimpleDocumentTest(SimpleDocumentRepository simpleDocumentRepository) { + this.simpleDocumentRepository = simpleDocumentRepository; + } - @BeforeEach - void setUp() { - for (int i = 0; i < SIZE; ++i) { - simpleDocumentRepository.save(new SimpleDocument()); - } + @BeforeEach + void setUp() { + for (int i = 0; i < SIZE; ++i) { + simpleDocumentRepository.save(new SimpleDocument()); } + } - @Test - void testAllSimpleDocumentsReturned() { - assumeThat(simpleDocumentRepository.count()).isEqualTo(SIZE); + @Test + void testAllSimpleDocumentsReturned() { + assumeThat(simpleDocumentRepository.count()).isEqualTo(SIZE); - List documents = simpleDocumentRepository.findAll(); - assertThat(documents).isNotNull().hasSize(SIZE); - } + List documents = simpleDocumentRepository.findAll(); + assertThat(documents).isNotNull().hasSize(SIZE); + } - @AfterEach - void tearDown() { - simpleDocumentRepository.deleteAll(); - } + @AfterEach + void tearDown() { + simpleDocumentRepository.deleteAll(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHash.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHash.java index f542e877..60046bf1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHash.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHash.java @@ -7,18 +7,18 @@ @RedisHash public class SimpleHash { - @Id - private String id; + @Id + private String id; - public SimpleHash() { - this.id = UUID.randomUUID().toString(); - } + public SimpleHash() { + this.id = UUID.randomUUID().toString(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHashTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHashTest.java index 38599b41..1437dfe4 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHashTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/SimpleHashTest.java @@ -13,32 +13,32 @@ class SimpleHashTest extends AbstractBaseEnhancedRedisTest { - private static final int SIZE = 20; + private static final int SIZE = 20; - private final SimpleHashRepository simpleHashRepository; + private final SimpleHashRepository simpleHashRepository; - @Autowired - SimpleHashTest(SimpleHashRepository simpleHashRepository) { - this.simpleHashRepository = simpleHashRepository; - } + @Autowired + SimpleHashTest(SimpleHashRepository simpleHashRepository) { + this.simpleHashRepository = simpleHashRepository; + } - @BeforeEach - void setUp() { - for (int i = 0; i < SIZE; ++i) { - simpleHashRepository.save(new SimpleHash()); - } + @BeforeEach + void setUp() { + for (int i = 0; i < SIZE; ++i) { + simpleHashRepository.save(new SimpleHash()); } + } - @Test - void testAllSimpleDocumentsReturned() { - assumeThat(simpleHashRepository.count()).isEqualTo(SIZE); + @Test + void testAllSimpleDocumentsReturned() { + assumeThat(simpleHashRepository.count()).isEqualTo(SIZE); - List documents = simpleHashRepository.findAll(); - assertThat(documents).isNotNull().hasSize(SIZE); - } + List documents = simpleHashRepository.findAll(); + assertThat(documents).isNotNull().hasSize(SIZE); + } - @AfterEach - void tearDown() { - simpleHashRepository.deleteAll(); - } + @AfterEach + void tearDown() { + simpleHashRepository.deleteAll(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/QueryUtilsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/QueryUtilsTest.java index f7043c16..4ed619ba 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/QueryUtilsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/QueryUtilsTest.java @@ -14,7 +14,7 @@ void testEscapeTagField() { } @Test - void testSearchIndexFieldAlliasFor(){ + void testSearchIndexFieldAlliasFor() { // Arrange Field field = Mockito.mock(Field.class); Mockito.when(field.getName()).thenReturn("redis"); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/clause/QueryClauseTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/clause/QueryClauseTest.java index 92c2f480..dc37a002 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/clause/QueryClauseTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/repository/query/clause/QueryClauseTest.java @@ -14,7 +14,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -@SuppressWarnings("SpellCheckingInspection") class QueryClauseTest { +@SuppressWarnings("SpellCheckingInspection") +class QueryClauseTest { @Test void testItShouldFindTheClauseByFieldTypeandPartType() { @@ -66,14 +67,16 @@ void testGetNonCustomMethodName() { } @Test - void testPrepareQuery(){ + void testPrepareQuery() { // Arrange List tagContainingAll = new ArrayList<>(Arrays.asList("db1", "db2")); - List numericContaining = new ArrayList<>(Arrays.asList(1,2,3)); - List numericContainingAll = new ArrayList<>(Arrays.asList(1,2,3)); - List geoContaining = new ArrayList<>(Arrays.asList(new Point(-122.066540, 37.377690), new Point(122.066540, -37.377690))); - List geoContainingAll = new ArrayList<>(Arrays.asList(new Point(-122.066540, 37.377690), new Point(122.066540, -37.377690))); - List numericGreaterThan = new ArrayList<>(Arrays.asList(5,10)); + List numericContaining = new ArrayList<>(Arrays.asList(1, 2, 3)); + List numericContainingAll = new ArrayList<>(Arrays.asList(1, 2, 3)); + List geoContaining = new ArrayList<>( + Arrays.asList(new Point(-122.066540, 37.377690), new Point(122.066540, -37.377690))); + List geoContainingAll = new ArrayList<>( + Arrays.asList(new Point(-122.066540, 37.377690), new Point(122.066540, -37.377690))); + List numericGreaterThan = new ArrayList<>(Arrays.asList(5, 10)); // Act String tagContainingAllQuery = QueryClause.TAG_CONTAINING_ALL.prepareQuery("database", tagContainingAll); @@ -87,13 +90,15 @@ void testPrepareQuery(){ assertEquals("@database:{db1} @database:{db2}", tagContainingAllQuery); assertEquals("@number:[1 1]|@number:[2 2]|@number:[3 3]", numericContainingQuery); assertEquals("@number:[1 1] @number:[2 2] @number:[3 3]", numericContainingAllQuery); - assertEquals("@location:[-122.06654 37.37769 .000001 ft]|@location:[122.06654 -37.37769 .000001 ft]", geoContainingQuery); - assertEquals("@location:[-122.06654 37.37769 .000001 ft] @location:[122.06654 -37.37769 .000001 ft]", geoContainigAllQuery); + assertEquals("@location:[-122.06654 37.37769 .000001 ft]|@location:[122.06654 -37.37769 .000001 ft]", + geoContainingQuery); + assertEquals("@location:[-122.06654 37.37769 .000001 ft] @location:[122.06654 -37.37769 .000001 ft]", + geoContainigAllQuery); assertEquals("@number:[(5|10 inf]", numericGreaterThanQuery); } @Test - void testGetPostProcessMethodName(){ + void testGetPostProcessMethodName() { String methodName1 = "SomeOtherMethodName"; assertEquals(methodName1, QueryClause.getPostProcessMethodName(methodName1)); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/DialectSwitchTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/DialectSwitchTest.java index 713a95d0..b12877fa 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/DialectSwitchTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/DialectSwitchTest.java @@ -12,13 +12,15 @@ import static org.junit.jupiter.api.Assertions.assertAll; class DialectSwitchTest extends AbstractBaseDocumentTest { - @Autowired DocRepository docRepository; + @Autowired + DocRepository docRepository; - @Autowired EntityStream entityStream; + @Autowired + EntityStream entityStream; /** * Consider the differences in parser behavior in example hello world | "goodbye" moon: - * + *

* In DIALECT 1, this query is interpreted as searching for (hello world | "goodbye") moon. * In DIALECT 2 or greater, this query is interpreted as searching for either hello world OR "goodbye" moon. */ @@ -29,24 +31,23 @@ void testSimpleQuery() { Doc goodbyeMoon = docRepository.save(Doc.of("doc2", "goodbye moon")); var dialectOne = entityStream.of(Doc.class) // - .dialect(1) // - .filter("hello world | \"goodbye\" moon") // - .collect(Collectors.toList()); + .dialect(1) // + .filter("hello world | \"goodbye\" moon") // + .collect(Collectors.toList()); var dialectTwo = entityStream.of(Doc.class) // - .dialect(2) // - .filter("hello world | \"goodbye\" moon") // - .collect(Collectors.toList()); + .dialect(2) // + .filter("hello world | \"goodbye\" moon") // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(dialectOne).containsExactly(goodbyeMoon), - () -> assertThat(dialectTwo).containsExactly(helloWorld, goodbyeMoon) - ); + () -> assertThat(dialectOne).containsExactly(goodbyeMoon), + () -> assertThat(dialectTwo).containsExactly(helloWorld, goodbyeMoon)); } /** * Consider a simple query with negation -hello world: - * + *

* In DIALECT 1, this query is interpreted as "find values in any field that does not contain hello AND does not * contain world". The equivalent is -(hello world) or -hello -world. * In DIALECT 2 or greater, this query is interpreted as -hello AND world (only hello is negated). @@ -60,20 +61,17 @@ void testSimpleQueryWithNegation() { docRepository.save(Doc.of("doc3", "hello world")); var dialectOne = entityStream.of(Doc.class) // - .dialect(1) // - .filter("-hello world") // - .collect(Collectors.toList()); + .dialect(1) // + .filter("-hello world") // + .collect(Collectors.toList()); var dialectTwo = entityStream.of(Doc.class) // - .dialect(2) // - .filter("-hello world") // - .collect(Collectors.toList()); + .dialect(2) // + .filter("-hello world") // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(dialectOne).containsExactly(hello, world), - () -> assertThat(dialectTwo).containsExactly(world) - ); + () -> assertThat(dialectOne).containsExactly(hello, world), () -> assertThat(dialectTwo).containsExactly(world)); } - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamDocsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamDocsTest.java index 2e1758f5..55d57c84 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamDocsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamDocsTest.java @@ -27,46 +27,53 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class EntityStreamDocsTest extends AbstractBaseDocumentTest { - @Autowired CompanyRepository repository; +@SuppressWarnings("SpellCheckingInspection") +class EntityStreamDocsTest extends AbstractBaseDocumentTest { + @Autowired + CompanyRepository repository; - @Autowired UserRepository userRepository; + @Autowired + UserRepository userRepository; // repository with an entity with only one indexed field - @Autowired NiCompanyRepository nicRepository; + @Autowired + NiCompanyRepository nicRepository; - @Autowired EntityStream entityStream; + @Autowired + EntityStream entityStream; - @Autowired Doc3Repository doc3Repository; + @Autowired + Doc3Repository doc3Repository; String redisId; String microsoftId; String teslaId; - @BeforeEach void cleanUp() { + @BeforeEach + void cleanUp() { if (repository.count() == 0) { Company redis = repository.save(Company.of( // - "RedisInc", 2011, // - LocalDate.of(2021, 5, 1), // - new Point(-122.066540, 37.377690), "stack@redis.com" // + "RedisInc", 2011, // + LocalDate.of(2021, 5, 1), // + new Point(-122.066540, 37.377690), "stack@redis.com" // )); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Set employees = Sets.newHashSet(Employee.of("Brian Sam-Bodden"), Employee.of("Guy Royse"), - Employee.of("Justin Castilla")); + Employee.of("Justin Castilla")); redis.setEmployees(employees); Company microsoft = repository.save(Company.of(// - "Microsoft", 1975, // - LocalDate.of(2022, 8, 15), // - new Point(-122.124500, 47.640160), "research@microsoft.com" // + "Microsoft", 1975, // + LocalDate.of(2022, 8, 15), // + new Point(-122.124500, 47.640160), "research@microsoft.com" // )); microsoft.setTags(Set.of("innovative", "reliable", "os", "ai")); Company tesla = repository.save(Company.of( // - "Tesla", 2003, // - LocalDate.of(2022, 1, 1), // - new Point(-97.6208903, 30.2210767), "elon@tesla.com" // + "Tesla", 2003, // + LocalDate.of(2022, 1, 1), // + new Point(-97.6208903, 30.2210767), "elon@tesla.com" // )); tesla.setTags(Set.of("innovative", "futuristic", "ai")); @@ -81,7 +88,7 @@ // users if (userRepository.count() == 0) { List users = List.of(User.of("Steve Lorello", .9999), User.of("Nava Levy", 1234.5678), - User.of("Savannah Norem", 999.99), User.of("Suze Shardlow", 899.0)); + User.of("Savannah Norem", 999.99), User.of("Suze Shardlow", 899.0)); for (User user : users) { user.setRoles(List.of("devrel", "educator", "guru")); } @@ -91,23 +98,23 @@ // partially non-indexed companies if (nicRepository.count() == 0) { NiCompany niRedis = nicRepository.save(NiCompany.of( // - "RedisInc", 2011, // - LocalDate.of(2021, 5, 1), // - new Point(-122.066540, 37.377690), "stack@redis.com" // + "RedisInc", 2011, // + LocalDate.of(2021, 5, 1), // + new Point(-122.066540, 37.377690), "stack@redis.com" // )); niRedis.setTags(List.of("fast", "scalable", "reliable", "database", "nosql")); NiCompany niMicrosoft = nicRepository.save(NiCompany.of( // - "Microsoft", 1975, // - LocalDate.of(2022, 8, 15), // - new Point(-122.124500, 47.640160), "research@microsoft.com" // + "Microsoft", 1975, // + LocalDate.of(2022, 8, 15), // + new Point(-122.124500, 47.640160), "research@microsoft.com" // )); niMicrosoft.setTags(List.of("innovative", "reliable", "os", "ai")); NiCompany niTesla = nicRepository.save(NiCompany.of( // - "Tesla", 2003, // - LocalDate.of(2022, 1, 1), // - new Point(-97.6208903, 30.2210767), "elon@tesla.com" // + "Tesla", 2003, // + LocalDate.of(2022, 1, 1), // + new Point(-97.6208903, 30.2210767), "elon@tesla.com" // )); niTesla.setTags(List.of("innovative", "futuristic", "ai")); @@ -133,7 +140,8 @@ } } - @Test void testStreamSelectAll() { + @Test + void testStreamSelectAll() { SearchStream stream = entityStream.of(Company.class); List allCompanies = stream.collect(Collectors.toList()); @@ -141,264 +149,288 @@ assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByOnePropertyEquals() { + @Test + void testFindByOnePropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.eq("RedisInc")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.eq("RedisInc")) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByOnePropertyNotEquals() { + @Test + void testFindByOnePropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.notEq("RedisInc")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.notEq("RedisInc")) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft", "Tesla"); } - @Test void testFindByTwoPropertiesOredEquals() { + @Test + void testFindByTwoPropertiesOredEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.eq("RedisInc") // - .or(Company$.NAME.eq("Microsoft")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.eq("RedisInc") // + .or(Company$.NAME.eq("Microsoft")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft"); } - @Test void testFindByThreePropertiesOredEquals() { + @Test + void testFindByThreePropertiesOredEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.eq("RedisInc") // - .or(Company$.NAME.eq("Microsoft")) // - .or(Company$.NAME.eq("Tesla")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.eq("RedisInc") // + .or(Company$.NAME.eq("Microsoft")) // + .or(Company$.NAME.eq("Tesla")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByThreePropertiesOrList() { + @Test + void testFindByThreePropertiesOrList() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.in("RedisInc", "Microsoft", "Tesla")).collect(Collectors.toList()); + .filter(Company$.NAME.in("RedisInc", "Microsoft", "Tesla")).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByThreePropertiesOrList2() { + @Test + void testFindByThreePropertiesOrList2() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.in("RedisInc", "Tesla")).collect(Collectors.toList()); + .filter(Company$.NAME.in("RedisInc", "Tesla")).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Tesla"); } - @Test void testFindByThreeNumericPropertiesOrList() { + @Test + void testFindByThreeNumericPropertiesOrList() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.in(2011, 1975, 2003)).collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.in(2011, 1975, 2003)).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByTwoPropertiesAndedNotEquals() { + @Test + void testFindByTwoPropertiesAndedNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla"); } - @Test void testFindByNumericPropertyEquals() { + @Test + void testFindByNumericPropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.eq(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.eq(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByNumericPropertyNotEquals() { + @Test + void testFindByNumericPropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.notEq(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.notEq(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla", "Microsoft"); } - @Test void testFindByNumericPropertyGreaterThan() { + @Test + void testFindByNumericPropertyGreaterThan() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.gt(2000)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.gt(2000)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Tesla"); } - @Test void testFindByNumericPropertyGreaterThanOrEqual() { + @Test + void testFindByNumericPropertyGreaterThanOrEqual() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.ge(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.ge(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByNumericPropertyLessThan() { + @Test + void testFindByNumericPropertyLessThan() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.lt(2000)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.lt(2000)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft"); } - @Test void testFindByNumericPropertyLessThanOrEqual() { + @Test + void testFindByNumericPropertyLessThanOrEqual() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.le(1975)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.le(1975)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft"); } - @Test void testFindByNumericPropertyBetween() { + @Test + void testFindByNumericPropertyBetween() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.between(1976, 2010)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.between(1976, 2010)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla"); } - @Test void testCount() { + @Test + void testCount() { long count = entityStream // - .of(Company.class) // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ).count(); + .of(Company.class) // + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ).count(); assertEquals(1, count); } - @Test void testLimit() { + @Test + void testLimit() { List companies = entityStream // - .of(Company.class) // - .limit(2).collect(Collectors.toList()); + .of(Company.class) // + .limit(2).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSkip() { + @Test + void testSkip() { List companies = entityStream // - .of(Company.class) // - .skip(1).collect(Collectors.toList()); + .of(Company.class) // + .skip(1).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSortDefaultAscending() { + @Test + void testSortDefaultAscending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "RedisInc", "Tesla"); } - @Test void testSortAscending() { + @Test + void testSortAscending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.ASC) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.ASC) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "RedisInc", "Tesla"); } - @Test void testSortDescending() { + @Test + void testSortDescending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "RedisInc", "Microsoft"); } - @Test void testForEachOrdered() { + @Test + void testForEachOrdered() { List companies = new ArrayList<>(); Consumer testConsumer = companies::add; entityStream // - .of(Company.class) // - .forEachOrdered(testConsumer); + .of(Company.class) // + .forEachOrdered(testConsumer); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc", "Microsoft", "Tesla"); } - @Test void testMapToOneProperty() { + @Test + void testMapToOneProperty() { List names = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "RedisInc", "Microsoft"); } - @Test void testMapToTwoProperties() { + @Test + void testMapToTwoProperties() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED)) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED)) // + .collect(Collectors.toList()); assertEquals(3, results.size()); @@ -411,12 +443,13 @@ assertEquals(1975, results.get(2).getSecond()); } - @Test void testMapToThreeProperties() { + @Test + void testMapToThreeProperties() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // + .collect(Collectors.toList()); assertEquals(3, results.size()); @@ -433,12 +466,13 @@ assertEquals(results.get(2).getThird(), new Point(-122.124500, 47.640160)); } - @Test void testMapToFourPropertiesOneNotIndexed() { + @Test + void testMapToFourPropertiesOneNotIndexed() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION, Company$.CREATED_DATE)) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION, Company$.CREATED_DATE)) // + .collect(Collectors.toList()); assertEquals(3, results.size()); @@ -459,72 +493,78 @@ assertNotNull(results.get(2).getFourth()); } - @Test void testGeoNearPredicate() { + @Test + void testGeoNearPredicate() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.near(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.near(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc"); } - @Test void testGeoOutsideOfPredicate() { + @Test + void testGeoOutsideOfPredicate() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.outsideOf(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.outsideOf(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "Microsoft"); } - @Test void testGeoEqPredicateUsingPoint() { + @Test + void testGeoEqPredicateUsingPoint() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq(new Point(-122.066540, 37.377690))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq(new Point(-122.066540, 37.377690))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc"); } - @Test void testGeoEqPredicateUsingCSV() { + @Test + void testGeoEqPredicateUsingCSV() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq("-122.066540, 37.377690")) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq("-122.066540, 37.377690")) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertEquals("RedisInc", names.get(0)); } - @Test void testGeoEqPredicateUsingDoubles() { + @Test + void testGeoEqPredicateUsingDoubles() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq(-122.066540, 37.377690)) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq(-122.066540, 37.377690)) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertEquals("RedisInc", names.get(0)); } - @Test void testGeoNotEqPredicateUsingPoint() { + @Test + void testGeoNotEqPredicateUsingPoint() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq(new Point(-122.066540, 37.377690))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq(new Point(-122.066540, 37.377690))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -532,13 +572,14 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testGeoNotEqPredicateUsingCSV() { + @Test + void testGeoNotEqPredicateUsingCSV() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq("-122.066540, 37.377690")) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq("-122.066540, 37.377690")) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -546,13 +587,14 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testGeoNotEqPredicateUsingDoubles() { + @Test + void testGeoNotEqPredicateUsingDoubles() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq(-122.066540, 37.377690)) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq(-122.066540, 37.377690)) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -560,12 +602,13 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testFindByTextLike() { + @Test + void testFindByTextLike() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.like("Micros")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.like("Micros")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -574,12 +617,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextNotLike() { + @Test + void testFindByTextNotLike() { List names = entityStream // - .of(Company.class) // - .filter(Company$.NAME.notLike("Micros")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.notLike("Micros")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -587,12 +631,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTextContaining() { + @Test + void testFindByTextContaining() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.containing("Micros")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.containing("Micros")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -601,12 +646,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextNotContaining() { + @Test + void testFindByTextNotContaining() { List names = entityStream // - .of(Company.class) // - .filter(Company$.NAME.notContaining("Micros")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.notContaining("Micros")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -614,12 +660,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTextThatStartsWith() { + @Test + void testFindByTextThatStartsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.startsWith("Mic")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.startsWith("Mic")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -628,12 +675,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextThatEndsWith() { + @Test + void testFindByTextThatEndsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.endsWith("soft")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.endsWith("soft")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -642,12 +690,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTagsIn() { + @Test + void testFindByTagsIn() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.in("reliable")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.in("reliable")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -655,12 +704,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTagsIn2() { + @Test + void testFindByTagsIn2() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.in("reliable", "ai")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.in("reliable", "ai")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(3, names.size()); @@ -669,93 +719,101 @@ assertTrue(names.contains("Tesla")); } - @Test void testFindByTagsContainingAll() { + @Test + void testFindByTagsContainingAll() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.containsAll("fast", "scalable", "reliable", "database", "nosql")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.containsAll("fast", "scalable", "reliable", "database", "nosql")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsEquals() { + @Test + void testFindByTagsEquals() { Set tags = Set.of("fast", "scalable", "reliable", "database", "nosql"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.eq(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.eq(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsNotEqualsSingleValue() { + @Test + void testFindByTagsNotEqualsSingleValue() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.notEq("ai")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.notEq("ai")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsNotEquals() { + @Test + void testFindByTagsNotEquals() { Set tags = Set.of("fast", "scalable", "reliable", "database", "nosql"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.notEq(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.notEq(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("Tesla")); } - @Test void testFindByTagsContainsNone() { + @Test + void testFindByTagsContainsNone() { Set tags = Set.of("innovative"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.containsNone(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.containsNone(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindFirst() { + @Test + void testFindFirst() { Optional maybeCompany = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .findFirst(); + .filter(Company$.NAME.eq("RedisInc")) // + .findFirst(); assertTrue(maybeCompany.isPresent()); assertEquals("RedisInc", maybeCompany.get().getName()); } - @Test void testFindAny() { + @Test + void testFindAny() { Optional maybeCompany = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .findAny(); + .filter(Company$.NAME.eq("RedisInc")) // + .findAny(); assertTrue(maybeCompany.isPresent()); assertEquals("RedisInc", maybeCompany.get().getName()); } - @Test void testToggleBooleanFieldInDocuments() { + @Test + void testToggleBooleanFieldInDocuments() { Optional maybeRedisBefore = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertFalse(maybeRedisBefore.get().isPubliclyListed()); entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .forEach(Company$.PUBLICLY_LISTED.toggle()); + .filter(Company$.NAME.eq("RedisInc")) // + .forEach(Company$.PUBLICLY_LISTED.toggle()); Optional maybeRedisAfter = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -763,14 +821,15 @@ flushSearchIndexFor(Company.class); } - @Test void testNumIncrByNumericFieldInDocuments() { + @Test + void testNumIncrByNumericFieldInDocuments() { Optional maybeRedisBefore = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertEquals(2011, maybeRedisBefore.get().getYearFounded()); entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .forEach(Company$.YEAR_FOUNDED.incrBy(5L)); + .filter(Company$.NAME.eq("RedisInc")) // + .forEach(Company$.YEAR_FOUNDED.incrBy(5L)); Optional maybeRedisAfter = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -778,14 +837,15 @@ flushSearchIndexFor(Company.class); } - @Test void testNumDecrByNumericFieldInDocuments() { + @Test + void testNumDecrByNumericFieldInDocuments() { Optional maybeRedisBefore = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertEquals(2011, maybeRedisBefore.get().getYearFounded()); entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .forEach(Company$.YEAR_FOUNDED.decrBy(2L)); + .filter(Company$.NAME.eq("RedisInc")) // + .forEach(Company$.YEAR_FOUNDED.decrBy(2L)); Optional maybeRedisAfter = repository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -793,10 +853,11 @@ flushSearchIndexFor(Company.class); } - @Test void testStrAppendToIndexedTextFieldInDocuments() { + @Test + void testStrAppendToIndexedTextFieldInDocuments() { entityStream.of(Company.class) // - .filter(Company$.NAME.eq("Microsoft")) // - .forEach(Company$.NAME.append(" Corp")); + .filter(Company$.NAME.eq("Microsoft")) // + .forEach(Company$.NAME.append(" Corp")); Optional maybeMicrosoft = repository.findFirstByEmail("research@microsoft.com"); assertTrue(maybeMicrosoft.isPresent()); @@ -804,22 +865,24 @@ flushSearchIndexFor(Company.class); } - @Test void testStrLenToIndexedTextFieldInDocuments() { + @Test + void testStrLenToIndexedTextFieldInDocuments() { List emailLengths = entityStream.of(Company.class) // - .map(Company$.NAME.length()) // - .collect(Collectors.toList()); + .map(Company$.NAME.length()) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(emailLengths).hasSize(3), // - () -> assertThat(emailLengths).containsExactly(8L, 9L, 5L) // + () -> assertThat(emailLengths).hasSize(3), // + () -> assertThat(emailLengths).containsExactly(8L, 9L, 5L) // ); } - @Test void testFindByTagEscapesChars() { + @Test + void testFindByTagEscapesChars() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.eq("stack@redis.com")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.eq("stack@redis.com")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -827,10 +890,11 @@ assertTrue(names.contains("RedisInc")); } - @Test void testArrayAppendToSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayAppendToSimpleIndexedTagFieldInDocuments() { entityStream.of(Company.class) // - .filter(Company$.NAME.eq("Microsoft")) // - .forEach(Company$.TAGS.add("gaming")); + .filter(Company$.NAME.eq("Microsoft")) // + .forEach(Company$.TAGS.add("gaming")); Optional maybeMicrosoft = repository.findFirstByEmail("research@microsoft.com"); assertTrue(maybeMicrosoft.isPresent()); @@ -839,10 +903,11 @@ flushSearchIndexFor(Company.class); } - @Test void testArrayAppendToComplexIndexedTagFieldInDocuments() { + @Test + void testArrayAppendToComplexIndexedTagFieldInDocuments() { entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .forEach(Company$.EMPLOYEES.add(Employee.of("Simon Prickett"))); + .filter(Company$.NAME.eq("RedisInc")) // + .forEach(Company$.EMPLOYEES.add(Employee.of("Simon Prickett"))); Optional maybeRedis = repository.findFirstByEmail("stack@redis.com"); assertTrue(maybeRedis.isPresent()); @@ -853,10 +918,11 @@ flushSearchIndexFor(Company.class); } - @Test void testArrayInsertToSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayInsertToSimpleIndexedTagFieldInDocuments() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.insert("dotnet", 0)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.insert("dotnet", 0)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -865,10 +931,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayPrependToSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayPrependToSimpleIndexedTagFieldInDocuments() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.prepend("dotnet")); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.prepend("dotnet")); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -877,10 +944,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayInsertToSimpleIndexedTagFieldInDocuments2() { + @Test + void testArrayInsertToSimpleIndexedTagFieldInDocuments2() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.insert("dotnet", 1)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.insert("dotnet", 1)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -889,32 +957,35 @@ flushSearchIndexFor(User.class); } - @Test void testArrayLenToSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayLenToSimpleIndexedTagFieldInDocuments() { List rolesLengths = entityStream.of(User.class) // - .map(User$.ROLES.length()) // - .collect(Collectors.toList()); + .map(User$.ROLES.length()) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(rolesLengths).hasSize(4), // - () -> assertThat(rolesLengths).containsExactly(3L, 3L, 3L, 3L) // + () -> assertThat(rolesLengths).hasSize(4), // + () -> assertThat(rolesLengths).containsExactly(3L, 3L, 3L, 3L) // ); } - @Test void testArrayIndexOfOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayIndexOfOnSimpleIndexedTagFieldInDocuments() { List rolesLengths = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.indexOf("guru")) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.indexOf("guru")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(rolesLengths).hasSize(1), // - () -> assertThat(rolesLengths).containsExactly(2L) // + () -> assertThat(rolesLengths).hasSize(1), // + () -> assertThat(rolesLengths).containsExactly(2L) // ); } - @Test void testArrayPopOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayPopOnSimpleIndexedTagFieldInDocuments() { List roles = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.pop()) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.pop()) // + .collect(Collectors.toList()); // contains the last assertThat(roles).containsExactly("guru"); @@ -929,11 +1000,12 @@ flushSearchIndexFor(User.class); } - @Test void testArrayRemoveLastOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveLastOnSimpleIndexedTagFieldInDocuments() { List roles = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.removeLast()) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.removeLast()) // + .collect(Collectors.toList()); // contains the last assertThat(roles).containsExactly("guru"); @@ -947,11 +1019,12 @@ flushSearchIndexFor(User.class); } - @Test void testArrayPopFirstOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayPopFirstOnSimpleIndexedTagFieldInDocuments() { List roles = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.pop(0)) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.pop(0)) // + .collect(Collectors.toList()); // contains the last assertThat(roles).containsExactly("devrel"); @@ -966,11 +1039,12 @@ flushSearchIndexFor(User.class); } - @Test void testArrayRemoveFirstOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveFirstOnSimpleIndexedTagFieldInDocuments() { List roles = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.removeFirst()) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.removeFirst()) // + .collect(Collectors.toList()); // contains the first assertThat(roles).containsExactly("devrel"); @@ -985,11 +1059,12 @@ flushSearchIndexFor(User.class); } - @Test void testArrayRemoveByIndexOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveByIndexOnSimpleIndexedTagFieldInDocuments() { List roles = entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .map(User$.ROLES.remove(0)) // - .collect(Collectors.toList()); + .filter(User$.NAME.eq("Steve Lorello")) // + .map(User$.ROLES.remove(0)) // + .collect(Collectors.toList()); // contains the first assertThat(roles).containsExactly("devrel"); @@ -1004,10 +1079,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments() { + @Test + void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.trimToRange(1, 1)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.trimToRange(1, 1)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -1016,10 +1092,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments2() { + @Test + void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments2() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.trimToRange(0, 0)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.trimToRange(0, 0)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -1028,10 +1105,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments3() { + @Test + void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments3() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.trimToRange(1, 2)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.trimToRange(1, 2)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -1040,10 +1118,11 @@ flushSearchIndexFor(User.class); } - @Test void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments4() { + @Test + void testArrayTrimToRangeOnSimpleIndexedTagFieldInDocuments4() { entityStream.of(User.class) // - .filter(User$.NAME.eq("Steve Lorello")) // - .forEach(User$.ROLES.trimToRange(1, -1)); + .filter(User$.NAME.eq("Steve Lorello")) // + .forEach(User$.ROLES.trimToRange(1, -1)); Optional maybeSteve = userRepository.findFirstByName("Steve Lorello"); assertTrue(maybeSteve.isPresent()); @@ -1052,167 +1131,182 @@ flushSearchIndexFor(User.class); } - @Test void testFindByDatePropertyEquals() { + @Test + void testFindByDatePropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.eq(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.eq(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Tesla"); } - @Test void testFindByDatePropertyNotEquals() { + @Test + void testFindByDatePropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.notEq(LocalDate.of(2021, 5, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.notEq(LocalDate.of(2021, 5, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyIsAfter() { + @Test + void testFindByDatePropertyIsAfter() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.after(LocalDate.of(2021, 5, 2))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.after(LocalDate.of(2021, 5, 2))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyIsOnOrAfter() { + @Test + void testFindByDatePropertyIsOnOrAfter() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.onOrAfter(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.onOrAfter(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyBefore() { + @Test + void testFindByDatePropertyBefore() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.before(LocalDate.of(2021, 6, 15))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.before(LocalDate.of(2021, 6, 15))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc"); } - @Test void testFindByDatePropertyIsOnOrBefore() { + @Test + void testFindByDatePropertyIsOnOrBefore() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.onOrBefore(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.onOrBefore(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc", "Tesla"); } - @Test void testFindByDatePropertyIsBetween() { + @Test + void testFindByDatePropertyIsBetween() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.between(LocalDate.of(2021, 5, 1), LocalDate.of(2022, 8, 15))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.between(LocalDate.of(2021, 5, 1), LocalDate.of(2022, 8, 15))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByDoubleNumericPropertyEquals() { + @Test + void testFindByDoubleNumericPropertyEquals() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.eq(.9999)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.eq(.9999)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Steve Lorello"); } - @Test void testFindByDoubleNumericPropertyNotEquals() { + @Test + void testFindByDoubleNumericPropertyNotEquals() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.notEq(.9999)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.notEq(.9999)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Nava Levy", "Savannah Norem", "Suze Shardlow"); } - @Test void testFindByDoubleNumericPropertyIn() { + @Test + void testFindByDoubleNumericPropertyIn() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.in(1234.5678, 999.99)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.in(1234.5678, 999.99)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Nava Levy", "Savannah Norem"); } - @Test void testFindByDoubleNumericPropertyBetween() { + @Test + void testFindByDoubleNumericPropertyBetween() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.between(1.0, 900.0)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.between(1.0, 900.0)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Suze Shardlow"); } - @Test void testFindByDoubleNumericPropertyGreaterThan() { + @Test + void testFindByDoubleNumericPropertyGreaterThan() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.gt(900.0)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.gt(900.0)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Nava Levy", "Savannah Norem"); } - @Test void testFindByDoubleNumericPropertyGreaterThanOrEqual() { + @Test + void testFindByDoubleNumericPropertyGreaterThanOrEqual() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.ge(899.0)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.ge(899.0)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Nava Levy", "Savannah Norem", "Suze Shardlow"); } - @Test void testFindByDoubleNumericPropertyLessThan() { + @Test + void testFindByDoubleNumericPropertyLessThan() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.lt(1.0)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.lt(1.0)) // + .collect(Collectors.toList()); List names = users.stream().map(User::getName).toList(); assertThat(names).containsExactly("Steve Lorello"); } - @Test void testFindByDoubleNumericPropertyLessThanOrEqual() { + @Test + void testFindByDoubleNumericPropertyLessThanOrEqual() { SearchStream stream = entityStream.of(User.class); List users = stream // - .filter(User$.LOTTERY_WINNINGS.le(899.0)) // - .collect(Collectors.toList()); + .filter(User$.LOTTERY_WINNINGS.le(899.0)) // + .collect(Collectors.toList()); assertEquals(2, users.size()); @@ -1221,75 +1315,85 @@ assertTrue(names.contains("Suze Shardlow")); } - @Test void testEntityWithoutIdThrowsException() { - IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> entityStream.of(DocWithoutId.class)); + @Test + void testEntityWithoutIdThrowsException() { + IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, + () -> entityStream.of(DocWithoutId.class)); String expectedErrorMessage = String.format("%s does not appear to have an ID field", DocWithoutId.class.getName()); Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - @Test void testFilterWithNonSearchFieldPredicateIsNoop() { + @Test + void testFilterWithNonSearchFieldPredicateIsNoop() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(c -> c.toString().equals("foo")) // - .collect(Collectors.toList()); + .filter(c -> c.toString().equals("foo")) // + .collect(Collectors.toList()); assertEquals(repository.count(), companies.size()); } - @Test void testMapToIntOnReturnFields() { + @Test + void testMapToIntOnReturnFields() { IntStream intStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .mapToInt(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .mapToInt(i -> i); assertThat(intStream.boxed().collect(Collectors.toList())).contains(2011, 1975, 2003); } - @Test void testMapToInt() { + @Test + void testMapToInt() { IntStream intStream = entityStream // - .of(Company.class) // - .mapToInt(Company::getYearFounded); + .of(Company.class) // + .mapToInt(Company::getYearFounded); assertThat(intStream.boxed().collect(Collectors.toList())).contains(2011, 1975, 2003); } - @Test void testMapToLongOnReturnFields() { + @Test + void testMapToLongOnReturnFields() { LongStream longStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .mapToLong(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .mapToLong(i -> i); assertThat(longStream.boxed().collect(Collectors.toList())).contains(2011L, 1975L, 2003L); } - @Test void testMapToLong() { + @Test + void testMapToLong() { LongStream longStream = entityStream // - .of(Company.class) // - .mapToLong(Company::getYearFounded); + .of(Company.class) // + .mapToLong(Company::getYearFounded); assertThat(longStream.boxed().collect(Collectors.toList())).contains(2011L, 1975L, 2003L); } - @Test void testMapToDoubleOnReturnFields() { + @Test + void testMapToDoubleOnReturnFields() { DoubleStream doubleStream = entityStream // - .of(User.class) // - .map(User$.LOTTERY_WINNINGS) // - .mapToDouble(w -> w); + .of(User.class) // + .map(User$.LOTTERY_WINNINGS) // + .mapToDouble(w -> w); assertThat(doubleStream.boxed().collect(Collectors.toList())).contains(.9999, 1234.5678, 999.99, 899.0); } - @Test void testMapToDouble() { + @Test + void testMapToDouble() { DoubleStream doubleStream = entityStream // - .of(User.class) // - .mapToDouble(User::getLotteryWinnings); + .of(User.class) // + .mapToDouble(User::getLotteryWinnings); assertThat(doubleStream.boxed().collect(Collectors.toList())).contains(.9999, 1234.5678, 999.99, 899.0); } - @Test void testFlatMapToInt() { + @Test + void testFlatMapToInt() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1300,15 +1404,16 @@ // actual IntStream tagLengthIntStream = entityStream // - .of(Company.class) // - .flatMapToInt(c -> c.getTags().stream().mapToInt(String::length)); + .of(Company.class) // + .flatMapToInt(c -> c.getTags().stream().mapToInt(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToLong() { + @Test + void testFlatMapToLong() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1319,15 +1424,16 @@ // actual LongStream tagLengthIntStream = entityStream // - .of(Company.class) // - .flatMapToLong(c -> c.getTags().stream().mapToLong(String::length)); + .of(Company.class) // + .flatMapToLong(c -> c.getTags().stream().mapToLong(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToDouble() { + @Test + void testFlatMapToDouble() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1338,21 +1444,22 @@ // actual DoubleStream tagLengthDoubleStream = entityStream // - .of(Company.class) // - .flatMapToDouble(c -> c.getTags().stream().mapToDouble(String::length)); + .of(Company.class) // + .flatMapToDouble(c -> c.getTags().stream().mapToDouble(String::length)); List actual = tagLengthDoubleStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testPeek() { + @Test + void testPeek() { final List peekedEmails = new ArrayList<>(); List companies = entityStream // - .of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .peek(c -> peekedEmails.add(c.getEmail())) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.eq("RedisInc")) // + .peek(c -> peekedEmails.add(c.getEmail())) // + .collect(Collectors.toList()); assertThat(peekedEmails).containsExactly("stack@redis.com"); @@ -1362,10 +1469,11 @@ assertTrue(names.contains("RedisInc")); } - @Test void testToArray() { + @Test + void testToArray() { Object[] allCompanies = entityStream // - .of(Company.class) // - .toArray(); + .of(Company.class) // + .toArray(); assertEquals(3, allCompanies.length); @@ -1375,10 +1483,11 @@ assertTrue(names.contains("Tesla")); } - @Test void testToArrayTyped() { + @Test + void testToArrayTyped() { Company[] allCompanies = entityStream // - .of(Company.class) // - .toArray(Company[]::new); + .of(Company.class) // + .toArray(Company[]::new); assertEquals(3, allCompanies.length); @@ -1388,235 +1497,258 @@ assertTrue(names.contains("Tesla")); } - @Test void testReduceWithIdentityBifunctionAndBinaryOperator() { + @Test + void testReduceWithIdentityBifunctionAndBinaryOperator() { Integer firstEstablish = entityStream // - .of(Company.class) // - .reduce(Integer.MAX_VALUE, (minimum, company) -> Integer.min(minimum, company.getYearFounded()), (t, u) -> Integer.min(t, u)); + .of(Company.class) // + .reduce(Integer.MAX_VALUE, (minimum, company) -> Integer.min(minimum, company.getYearFounded()), + (t, u) -> Integer.min(t, u)); assertThat(firstEstablish).isEqualTo(1975); } - @Test void testReduceWithMethodReferenceAndCombiner() { + @Test + void testReduceWithMethodReferenceAndCombiner() { int result = entityStream // - .of(Company.class) // - .reduce(0, (acc, company) -> acc + company.getYearFounded(), (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .reduce(0, (acc, company) -> acc + company.getYearFounded(), (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithCombiner() { + @Test + void testReduceWithCombiner() { BinaryOperator establishedFirst = (c1, c2) -> c1.getYearFounded() < c2.getYearFounded() ? c1 : c2; Optional firstEstablish = entityStream // - .of(Company.class) // - .reduce(establishedFirst); + .of(Company.class) // + .reduce(establishedFirst); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testReduceWithIdAndCombiner() { + @Test + void testReduceWithIdAndCombiner() { BinaryOperator establishedFirst = (c1, c2) -> c1.getYearFounded() < c2.getYearFounded() ? c1 : c2; Company c = new Company(); c.setYearFounded(Integer.MAX_VALUE); Optional firstEstablish = Optional.of(entityStream // - .of(Company.class) // - .reduce(c, establishedFirst)); + .of(Company.class) // + .reduce(c, establishedFirst)); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testReduceWithMethodReferenceOnMappedField() { + @Test + void testReduceWithMethodReferenceOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithLambdaOnMappedField() { + @Test + void testReduceWithLambdaOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithCombinerOnMappedField() { + @Test + void testReduceWithCombinerOnMappedField() { BinaryOperator establishedFirst = (c1, c2) -> c1 < c2 ? c1 : c2; Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(establishedFirst); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(establishedFirst); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } - @Test void testReduceWithIdentityBifunctionAndBinaryOperatorOnMappedField() { + @Test + void testReduceWithIdentityBifunctionAndBinaryOperatorOnMappedField() { Integer firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); assertThat(firstEstablish).isEqualTo(1975); } - @Test void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { + @Test + void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { Supplier supplier = AtomicInteger::new; BiConsumer accumulator = (AtomicInteger a, Integer i) -> a.set(a.get() + i); BiConsumer combiner = (a1, a2) -> a1.set(a1.get() + a2.get()); AtomicInteger result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .collect(supplier, accumulator, combiner); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .collect(supplier, accumulator, combiner); assertThat(result.intValue()).isEqualTo(2011 + 1975 + 2003); } - @Test void testCollectWithIdAndCombiner() { + @Test + void testCollectWithIdAndCombiner() { Supplier supplier = AtomicInteger::new; - BiConsumer accumulator = (AtomicInteger a, Company c) -> a.set(a.get() + c.getYearFounded()); + BiConsumer accumulator = (AtomicInteger a, Company c) -> a.set( + a.get() + c.getYearFounded()); BiConsumer combiner = (a1, a2) -> a1.set(a1.get() + a2.get()); AtomicInteger result = entityStream // - .of(Company.class) // - .collect(supplier, accumulator, combiner); + .of(Company.class) // + .collect(supplier, accumulator, combiner); assertThat(result.intValue()).isEqualTo(2011 + 1975 + 2003); } - @Test void testMinOnMappedField() { + @Test + void testMinOnMappedField() { Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .min(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .min(Integer::compareTo); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } - @Test void testMaxOnMappedField() { + @Test + void testMaxOnMappedField() { Optional lastEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .max(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .max(Integer::compareTo); assertAll( // - () -> assertThat(lastEstablish).isPresent(), // - () -> assertThat(lastEstablish).contains(2011) // + () -> assertThat(lastEstablish).isPresent(), // + () -> assertThat(lastEstablish).contains(2011) // ); } - @Test void testAnyMatchOnMappedField() { + @Test + void testAnyMatchOnMappedField() { boolean c1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .anyMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .anyMatch(c -> c == 1975); boolean c1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .anyMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .anyMatch(c -> c == 1976); assertThat(c1975).isTrue(); assertThat(c1976).isFalse(); } - @Test void testAllMatchOnMappedField() { + @Test + void testAllMatchOnMappedField() { boolean allEstablishedBefore1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .allMatch(c -> c < 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .allMatch(c -> c < 1970); boolean allEstablishedOnOrAfter1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .allMatch(c -> c >= 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .allMatch(c -> c >= 1970); assertThat(allEstablishedOnOrAfter1970).isTrue(); assertThat(allEstablishedBefore1970).isFalse(); } - @Test void testNoneMatchOnMappedField() { + @Test + void testNoneMatchOnMappedField() { boolean noneIn1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .noneMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .noneMatch(c -> c == 1975); boolean noneIn1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .noneMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .noneMatch(c -> c == 1976); assertThat(noneIn1976).isTrue(); assertThat(noneIn1975).isFalse(); } - @Test void testMin() { + @Test + void testMin() { Optional firstEstablish = entityStream // - .of(Company.class) // - .min(Comparator.comparing(Company::getYearFounded)); + .of(Company.class) // + .min(Comparator.comparing(Company::getYearFounded)); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testMax() { + @Test + void testMax() { Optional lastEstablish = entityStream // - .of(Company.class) // - .max(Comparator.comparing(Company::getYearFounded)); + .of(Company.class) // + .max(Comparator.comparing(Company::getYearFounded)); assertThat(lastEstablish).isPresent(); assertThat(lastEstablish.get().getYearFounded()).isEqualTo(2011); } - @Test void testAnyMatch() { + @Test + void testAnyMatch() { boolean c1975 = entityStream // - .of(Company.class) // - .anyMatch(c -> c.getYearFounded() == 1975); + .of(Company.class) // + .anyMatch(c -> c.getYearFounded() == 1975); boolean c1976 = entityStream // - .of(Company.class) // - .anyMatch(c -> c.getYearFounded() == 1976); + .of(Company.class) // + .anyMatch(c -> c.getYearFounded() == 1976); assertThat(c1975).isTrue(); assertThat(c1976).isFalse(); } - @Test void testAllMatch() { + @Test + void testAllMatch() { boolean allEstablishedBefore1970 = entityStream // - .of(Company.class) // - .allMatch(c -> c.getYearFounded() < 1970); + .of(Company.class) // + .allMatch(c -> c.getYearFounded() < 1970); boolean allEstablishedOnOrAfter1970 = entityStream // - .of(Company.class) // - .allMatch(c -> c.getYearFounded() >= 1970); + .of(Company.class) // + .allMatch(c -> c.getYearFounded() >= 1970); assertThat(allEstablishedOnOrAfter1970).isTrue(); assertThat(allEstablishedBefore1970).isFalse(); } - @Test void testNoneMatch() { + @Test + void testNoneMatch() { boolean noneIn1975 = entityStream // - .of(Company.class) // - .noneMatch(c -> c.getYearFounded() == 1975); + .of(Company.class) // + .noneMatch(c -> c.getYearFounded() == 1975); boolean noneIn1976 = entityStream // - .of(Company.class) // - .noneMatch(c -> c.getYearFounded() == 1976); + .of(Company.class) // + .noneMatch(c -> c.getYearFounded() == 1976); assertThat(noneIn1976).isTrue(); assertThat(noneIn1975).isFalse(); } - @Test void testIterator() { + @Test + void testIterator() { List allCompanies = new ArrayList<>(); for (Iterator iterator = entityStream.of(Company.class).iterator(); iterator.hasNext(); ) { allCompanies.add(iterator.next()); @@ -1630,7 +1762,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIterator() { + @Test + void testSplitIterator() { ArrayList allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1646,7 +1779,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testNoops() { + @Test + void testNoops() { SearchStream stream = entityStream.of(Company.class); assertThat(stream.isParallel()).isFalse(); assertThat(stream.parallel()).isEqualTo(stream); @@ -1654,7 +1788,8 @@ assertThat(stream.unordered()).isEqualTo(stream); } - @Test void testCloseHandler() { + @Test + void testCloseHandler() { SearchStream stream = entityStream.of(Company.class); AtomicBoolean wasClosed = new AtomicBoolean(false); //noinspection ResultOfMethodCallIgnored @@ -1663,7 +1798,8 @@ assertThat(wasClosed.get()).isTrue(); } - @Test void testCloseHandlerIsNull() { + @Test + void testCloseHandlerIsNull() { SearchStream stream = entityStream.of(Company.class); stream.close(); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, stream::findAny); @@ -1672,10 +1808,11 @@ Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - @Test void testIteratorOnMappedField() { + @Test + void testIteratorOnMappedField() { List allCompanies = new ArrayList<>(); for (Iterator iterator = entityStream.of(Company.class).map(Company$.NAME) - .iterator(); iterator.hasNext(); ) { + .iterator(); iterator.hasNext(); ) { allCompanies.add(iterator.next()); } @@ -1687,7 +1824,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIteratorOnMappedField() { + @Test + void testSplitIteratorOnMappedField() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1703,12 +1841,14 @@ assertTrue(names.contains("Tesla")); } - @Test void testStreamOnMappedFieldIsNotParallel() { + @Test + void testStreamOnMappedFieldIsNotParallel() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); assertThat(stream.isParallel()).isFalse(); } - @Test void testCloseHandlerOnMappedField() { + @Test + void testCloseHandlerOnMappedField() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); AtomicBoolean wasClosed = new AtomicBoolean(false); //noinspection ResultOfMethodCallIgnored @@ -1717,7 +1857,8 @@ assertThat(wasClosed.get()).isTrue(); } - @Test void testCloseHandlerIsNullOnMappedField() { + @Test + void testCloseHandlerIsNullOnMappedField() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); stream.close(); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, stream::findAny); @@ -1726,18 +1867,20 @@ Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - @Test void testFilterOnMappedField() { + @Test + void testFilterOnMappedField() { Predicate predicate = i -> (i > 2000); List foundedAfter2000 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .filter(predicate) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .filter(predicate) // + .collect(Collectors.toList()); assertThat(foundedAfter2000).contains(2011, 2003); } - @Test void testFlatMapToIntOnMappedField() { + @Test + void testFlatMapToIntOnMappedField() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1748,16 +1891,17 @@ // actual IntStream tagLengthIntStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .flatMapToInt(tags -> tags.stream().mapToInt(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .flatMapToInt(tags -> tags.stream().mapToInt(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToLongOnMappedField() { + @Test + void testFlatMapToLongOnMappedField() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1768,16 +1912,17 @@ // actual LongStream tagLengthIntStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .flatMapToLong(tags -> tags.stream().mapToLong(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .flatMapToLong(tags -> tags.stream().mapToLong(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToDoubleOnMappedField() { + @Test + void testFlatMapToDoubleOnMappedField() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -1788,82 +1933,89 @@ // actual DoubleStream tagLengthDoubleStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .flatMapToDouble(tags -> tags.stream().mapToDouble(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .flatMapToDouble(tags -> tags.stream().mapToDouble(String::length)); List actual = tagLengthDoubleStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testCollectionRetrievalOnMappedField() { + @Test + void testCollectionRetrievalOnMappedField() { List> expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { expected.add(company.getTags()); } List> actual = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.TAGS) // + .collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testMapWithFunctionAgainstMappedField() { + @Test + void testMapWithFunctionAgainstMappedField() { Function, String> mapper = (Set tags) -> String.join("-", new TreeSet<>(tags)); List joinedTags = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .map(mapper) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.TAGS) // + .map(mapper) // + .collect(Collectors.toList()); assertThat(joinedTags).containsExactly( // - "database-fast-nosql-reliable-scalable", // - "ai-innovative-os-reliable", // - "ai-futuristic-innovative" // + "database-fast-nosql-reliable-scalable", // + "ai-innovative-os-reliable", // + "ai-futuristic-innovative" // ); } - @Test void testFlatMap() { - Function, Stream> mapper = (Set tags) -> Stream.of(String.join("-", new TreeSet<>(tags))); + @Test + void testFlatMap() { + Function, Stream> mapper = (Set tags) -> Stream.of( + String.join("-", new TreeSet<>(tags))); List joinedTags = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .flatMap(mapper) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.TAGS) // + .flatMap(mapper) // + .collect(Collectors.toList()); assertThat(joinedTags).containsExactly( // - "database-fast-nosql-reliable-scalable", // - "ai-innovative-os-reliable", // - "ai-futuristic-innovative" // + "database-fast-nosql-reliable-scalable", // + "ai-innovative-os-reliable", // + "ai-futuristic-innovative" // ); } - @Test void testFlatMapOnMappedField() { - Function> mapper = (Company company) -> Stream.of(String.join("-", new TreeSet<>(company.getTags()))); + @Test + void testFlatMapOnMappedField() { + Function> mapper = (Company company) -> Stream.of( + String.join("-", new TreeSet<>(company.getTags()))); List joinedTags = entityStream // - .of(Company.class) // - .flatMap(mapper) // - .collect(Collectors.toList()); + .of(Company.class) // + .flatMap(mapper) // + .collect(Collectors.toList()); assertThat(joinedTags).containsExactly( // - "database-fast-nosql-reliable-scalable", // - "ai-innovative-os-reliable", // - "ai-futuristic-innovative" // + "database-fast-nosql-reliable-scalable", // + "ai-innovative-os-reliable", // + "ai-futuristic-innovative" // ); } - @Test void testForEachOrderedOnMappedField() { + @Test + void testForEachOrderedOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .forEachOrdered(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .forEachOrdered(testConsumer); assertEquals(3, names.size()); @@ -1872,13 +2024,14 @@ assertEquals("Tesla", names.get(2)); } - @Test void testForEachOnMappedField() { + @Test + void testForEachOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .forEach(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .forEach(testConsumer); assertEquals(3, names.size()); @@ -1887,11 +2040,12 @@ assertEquals("Tesla", names.get(2)); } - @Test void testToArrayOnMappedField() { + @Test + void testToArrayOnMappedField() { Object[] allCompanies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .toArray(); + .of(Company.class) // + .map(Company$.NAME) // + .toArray(); assertEquals(3, allCompanies.length); @@ -1902,11 +2056,12 @@ assertTrue(names.contains("Tesla")); } - @Test void testToArrayTypedOnMappedField() { + @Test + void testToArrayTypedOnMappedField() { String[] namesArray = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .toArray(String[]::new); + .of(Company.class) // + .map(Company$.NAME) // + .toArray(String[]::new); assertEquals(3, namesArray.length); @@ -1916,44 +2071,48 @@ assertTrue(names.contains("Tesla")); } - @Test void testCountOnMappedField() { + @Test + void testCountOnMappedField() { long count = entityStream // - .of(Company.class) // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ) // - .map(Company$.NAME) // - .count(); + .of(Company.class) // + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ) // + .map(Company$.NAME) // + .count(); assertEquals(1, count); } - @Test void testLimitOnMappedField() { + @Test + void testLimitOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .limit(2).collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .limit(2).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSkipOnMappedField() { + @Test + void testSkipOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .skip(1) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .skip(1) // + .collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSortOnMappedField() { + @Test + void testSortOnMappedField() { List names = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sorted(Comparator.reverseOrder()) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .sorted(Comparator.reverseOrder()) // + .collect(Collectors.toList()); assertEquals(3, names.size()); @@ -1962,41 +2121,45 @@ assertEquals("Microsoft", names.get(2)); } - @Test void testPeekOnMappedField() { + @Test + void testPeekOnMappedField() { final List peekedEmails = new ArrayList<>(); List emails = entityStream // - .of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .peek(peekedEmails::add) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .peek(peekedEmails::add) // + .collect(Collectors.toList()); assertThat(peekedEmails).containsExactly("stack@redis.com"); assertEquals(1, emails.size()); } - @Test void testFindFirstOnMappedField() { + @Test + void testFindFirstOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .findFirst(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .findFirst(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); } - @Test void testFindAnyOnMappedField() { + @Test + void testFindAnyOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .findAny(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .findAny(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); } - @Test void testNoopsOnMappedField() { + @Test + void testNoopsOnMappedField() { Iterator iter1 = entityStream.of(Company.class).map(Company$.NAME).iterator(); Iterator iter2 = entityStream.of(Company.class).map(Company$.NAME).iterator(); Iterator iter3 = entityStream.of(Company.class).map(Company$.NAME).iterator(); @@ -2008,21 +2171,23 @@ assertThat(Iterators.elementsEqual(iter3, unordered.iterator())).isTrue(); } - @Test void testMapOnMappedField() { + @Test + void testMapOnMappedField() { ToLongFunction func = y -> y - 1; List yearsMinusOne = entityStream.of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .map(func) // - .collect(Collectors.toList()); + .map(Company$.YEAR_FOUNDED) // + .map(func) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(yearsMinusOne).hasSize(3), // - () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // + () -> assertThat(yearsMinusOne).hasSize(3), // + () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // ); } - @Test void testSplitIteratorOnMappedFieldParallelStream() { + @Test + void testSplitIteratorOnMappedFieldParallelStream() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).parallel().spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -2038,7 +2203,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIteratorOnMappedFieldSequentialStream() { + @Test + void testSplitIteratorOnMappedFieldSequentialStream() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).sequential().spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -2058,34 +2224,37 @@ // Non-indexed Fields // - @Test void testStrAppendToNonIndexedTextFieldInDocuments() { + @Test + void testStrAppendToNonIndexedTextFieldInDocuments() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.EMAIL.append("zzz")); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.EMAIL.append("zzz")); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); assertThat(maybeMicrosoft.get().getEmail()).endsWith("zzz"); } - @Test void testStrLenToNonIndexedTagFieldInDocuments() { + @Test + void testStrLenToNonIndexedTagFieldInDocuments() { List emailLengths = entityStream.of(NiCompany.class) // - .map(NiCompany$.EMAIL.length()) // - .collect(Collectors.toList()); + .map(NiCompany$.EMAIL.length()) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(emailLengths).hasSize(3), // - () -> assertThat(emailLengths).containsExactly(15L, 22L, 14L) // + () -> assertThat(emailLengths).hasSize(3), // + () -> assertThat(emailLengths).containsExactly(15L, 22L, 14L) // ); } - @Test void testToggleToNonIndexedBooleanFieldInDocuments() { + @Test + void testToggleToNonIndexedBooleanFieldInDocuments() { Optional maybeRedisBefore = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertFalse(maybeRedisBefore.get().isPubliclyListed()); entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("RedisInc")) // - .forEach(NiCompany$.PUBLICLY_LISTED.toggle()); + .filter(NiCompany$.NAME.eq("RedisInc")) // + .forEach(NiCompany$.PUBLICLY_LISTED.toggle()); Optional maybeRedisAfter = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -2093,14 +2262,15 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testNumIncrByToNonIndexedNumericFieldInDocuments() { + @Test + void testNumIncrByToNonIndexedNumericFieldInDocuments() { Optional maybeRedisBefore = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertEquals(2011, maybeRedisBefore.get().getYearFounded()); entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("RedisInc")) // - .forEach(NiCompany$.YEAR_FOUNDED.incrBy(5L)); + .filter(NiCompany$.NAME.eq("RedisInc")) // + .forEach(NiCompany$.YEAR_FOUNDED.incrBy(5L)); Optional maybeRedisAfter = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -2108,14 +2278,15 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testNumDecrByToNonIndexedNumericFieldInDocuments() { + @Test + void testNumDecrByToNonIndexedNumericFieldInDocuments() { Optional maybeRedisBefore = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisBefore.isPresent()); assertEquals(2011, maybeRedisBefore.get().getYearFounded()); entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("RedisInc")) // - .forEach(NiCompany$.YEAR_FOUNDED.decrBy(2L)); + .filter(NiCompany$.NAME.eq("RedisInc")) // + .forEach(NiCompany$.YEAR_FOUNDED.decrBy(2L)); Optional maybeRedisAfter = nicRepository.findFirstByName("RedisInc"); assertTrue(maybeRedisAfter.isPresent()); @@ -2123,10 +2294,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayAppendToNonIndexedTagFieldInDocuments() { + @Test + void testArrayAppendToNonIndexedTagFieldInDocuments() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.add("gaming")); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.add("gaming")); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2135,10 +2307,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayInsertToNonIndexedTagFieldInDocuments() { + @Test + void testArrayInsertToNonIndexedTagFieldInDocuments() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.insert("gaming", 2)); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.insert("gaming", 2)); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2147,10 +2320,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayPrependToNonIndexedTagFieldInDocuments() { + @Test + void testArrayPrependToNonIndexedTagFieldInDocuments() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.prepend("gaming")); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.prepend("gaming")); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2159,43 +2333,47 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testStrLenToNonIndexedTextFieldInDocuments() { + @Test + void testStrLenToNonIndexedTextFieldInDocuments() { List emailLengths = entityStream.of(NiCompany.class) // - .map(NiCompany$.NAME.length()) // - .collect(Collectors.toList()); + .map(NiCompany$.NAME.length()) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(emailLengths).hasSize(3), // - () -> assertThat(emailLengths).containsExactly(8L, 9L, 5L) // + () -> assertThat(emailLengths).hasSize(3), // + () -> assertThat(emailLengths).containsExactly(8L, 9L, 5L) // ); } - @Test void testArrayLengthOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayLengthOnNonIndexedTagFieldInDocuments() { List tagsLengths = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.length()) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.length()) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(tagsLengths).hasSize(1), // - () -> assertThat(tagsLengths).containsExactly(4L) // + () -> assertThat(tagsLengths).hasSize(1), // + () -> assertThat(tagsLengths).containsExactly(4L) // ); } - @Test void testArrayIndexOfOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayIndexOfOnNonIndexedTagFieldInDocuments() { List tagsLengths = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.indexOf("os")) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.indexOf("os")) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(tagsLengths).hasSize(1), // - () -> assertThat(tagsLengths).containsExactly(2L) // + () -> assertThat(tagsLengths).hasSize(1), // + () -> assertThat(tagsLengths).containsExactly(2L) // ); } - @Test void testArrayPopOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayPopOnNonIndexedTagFieldInDocuments() { List tags = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.pop()) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.pop()) // + .collect(Collectors.toList()); // contains the last assertThat(tags).containsExactly("ai"); @@ -2210,11 +2388,12 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayRemoveLastOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveLastOnNonIndexedTagFieldInDocuments() { List tags = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.removeLast()) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.removeLast()) // + .collect(Collectors.toList()); // contains the last assertThat(tags).containsExactly("ai"); @@ -2229,11 +2408,12 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayPopFirstOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayPopFirstOnNonIndexedTagFieldInDocuments() { List tags = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.pop(0)) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.pop(0)) // + .collect(Collectors.toList()); // contains the last assertThat(tags).containsExactly("innovative"); @@ -2248,11 +2428,12 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayRemoveFirstOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveFirstOnNonIndexedTagFieldInDocuments() { List tags = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.removeFirst()) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.removeFirst()) // + .collect(Collectors.toList()); // contains the last assertThat(tags).containsExactly("innovative"); @@ -2267,11 +2448,12 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayRemoveByIndexOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayRemoveByIndexOnNonIndexedTagFieldInDocuments() { List tags = entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .map(NiCompany$.TAGS.remove(0)) // - .collect(Collectors.toList()); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .map(NiCompany$.TAGS.remove(0)) // + .collect(Collectors.toList()); // contains the last assertThat(tags).containsExactly("innovative"); @@ -2286,10 +2468,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments() { + @Test + void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.trimToRange(1, 1)); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.trimToRange(1, 1)); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2299,10 +2482,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments2() { + @Test + void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments2() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.trimToRange(0, 0)); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.trimToRange(0, 0)); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2312,10 +2496,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments3() { + @Test + void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments3() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.trimToRange(1, 2)); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.trimToRange(1, 2)); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2325,10 +2510,11 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments4() { + @Test + void testArrayTrimToRangeOnNonIndexedTagFieldInDocuments4() { entityStream.of(NiCompany.class) // - .filter(NiCompany$.NAME.eq("Microsoft")) // - .forEach(NiCompany$.TAGS.trimToRange(1, -1)); + .filter(NiCompany$.NAME.eq("Microsoft")) // + .forEach(NiCompany$.TAGS.trimToRange(1, -1)); Optional maybeMicrosoft = nicRepository.findFirstByName("Microsoft"); assertTrue(maybeMicrosoft.isPresent()); @@ -2338,47 +2524,50 @@ flushSearchIndexFor(NiCompany.class); } - @Test void testTupleResultWithLabels() { + @Test + void testTupleResultWithLabels() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // - .mapToLabelledMaps().toList(); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // + .mapToLabelledMaps().toList(); assertEquals(3, results.size()); assertThat(results.get(0)) // - .containsEntry("name", "Tesla") // - .containsEntry("yearFounded", 2003) // - .containsEntry("location", new Point(-97.6208903, 30.2210767)); + .containsEntry("name", "Tesla") // + .containsEntry("yearFounded", 2003) // + .containsEntry("location", new Point(-97.6208903, 30.2210767)); assertThat(results.get(1)) // - .containsEntry("name", "RedisInc") // - .containsEntry("yearFounded", 2011) // - .containsEntry("location", new Point(-122.066540, 37.377690)); + .containsEntry("name", "RedisInc") // + .containsEntry("yearFounded", 2011) // + .containsEntry("location", new Point(-122.066540, 37.377690)); assertThat(results.get(2)) // - .containsEntry("name", "Microsoft") // - .containsEntry("yearFounded", 1975) // - .containsEntry("location", new Point(-122.124500, 47.640160)); + .containsEntry("name", "Microsoft") // + .containsEntry("yearFounded", 1975) // + .containsEntry("location", new Point(-122.124500, 47.640160)); } - @Test void testMapToIdProperty() { + @Test + void testMapToIdProperty() { List ids = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.ID) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.ID) // + .collect(Collectors.toList()); assertThat(ids).containsExactly(teslaId, redisId, microsoftId); } - @Test void testFindByTagStartsWith() { + @Test + void testFindByTagStartsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.startsWith("sta")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.startsWith("sta")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -2386,12 +2575,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagEndsWith() { + @Test + void testFindByTagEndsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.endsWith("sla.com")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.endsWith("sla.com")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -2399,24 +2589,26 @@ assertTrue(names.contains("Tesla")); } - @Test void testIgnorePredicatesWithNullParamsAnded() { + @Test + void testIgnorePredicatesWithNullParamsAnded() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.eq("RedisInc")) // - .filter(Company$.YEAR_FOUNDED.eq(null)) // - .collect(Collectors.toList()); + .filter(Company$.NAME.eq("RedisInc")) // + .filter(Company$.YEAR_FOUNDED.eq(null)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testProjectProperties() { + @Test + void testProjectProperties() { List docs = entityStream // - .of(Doc3.class) // - .sorted(Doc3$.FIRST, SortOrder.DESC) // - .project(Fields.of(Doc3$.FIRST, Doc3$.THIRD)) // - .collect(Collectors.toList()); + .of(Doc3.class) // + .sorted(Doc3$.FIRST, SortOrder.DESC) // + .project(Fields.of(Doc3$.FIRST, Doc3$.THIRD)) // + .collect(Collectors.toList()); assertEquals(4, docs.size()); @@ -2431,17 +2623,17 @@ }); } - @Test void testMapAgainstEmptyResults() { + @Test + void testMapAgainstEmptyResults() { List names = entityStream // .of(Company.class) // - .filter(Company$.NAME.startsWith("Open")) - .map(Company$.ID) - .collect(Collectors.toList()); + .filter(Company$.NAME.startsWith("Open")).map(Company$.ID).collect(Collectors.toList()); assertThat(names).isEmpty(); } - @Test void testContainingPredicateOnFreeFormTextStartMatches() { + @Test + void testContainingPredicateOnFreeFormTextStartMatches() { doc3Repository.deleteAll(); var doc = Doc3.of("someDoc"); doc.setSecond("some text about nothing"); @@ -2449,9 +2641,7 @@ doc3Repository.save(doc); - var docs = entityStream.of(Doc3.class) - .filter(Doc3$.SECOND.containing("some text")) - .collect(Collectors.toList()); + var docs = entityStream.of(Doc3.class).filter(Doc3$.SECOND.containing("some text")).collect(Collectors.toList()); assertEquals(1, docs.size()); assertThat(docs.get(0).getSecond()).isEqualTo("some text about nothing"); @@ -2459,7 +2649,8 @@ doc3Repository.delete(doc); } - @Test void testContainingPredicateOnFreeFormTextMiddleMatches() { + @Test + void testContainingPredicateOnFreeFormTextMiddleMatches() { doc3Repository.deleteAll(); var doc = Doc3.of("someDoc"); doc.setSecond("some text about nothing"); @@ -2467,9 +2658,7 @@ doc3Repository.save(doc); - var docs = entityStream.of(Doc3.class) - .filter(Doc3$.SECOND.containing("text about")) - .collect(Collectors.toList()); + var docs = entityStream.of(Doc3.class).filter(Doc3$.SECOND.containing("text about")).collect(Collectors.toList()); assertEquals(1, docs.size()); assertThat(docs.get(0).getSecond()).isEqualTo("some text about nothing"); @@ -2477,7 +2666,8 @@ doc3Repository.delete(doc); } - @Test void testContainingPredicateOnFreeFormTextEndMatches() { + @Test + void testContainingPredicateOnFreeFormTextEndMatches() { doc3Repository.deleteAll(); var doc = Doc3.of("someDoc"); doc.setSecond("some text about nothing"); @@ -2485,8 +2675,7 @@ doc3Repository.save(doc); - var docs = entityStream.of(Doc3.class) - .filter(Doc3$.SECOND.containing("about nothing")) + var docs = entityStream.of(Doc3.class).filter(Doc3$.SECOND.containing("about nothing")) .collect(Collectors.toList()); assertEquals(1, docs.size()); @@ -2495,16 +2684,15 @@ doc3Repository.delete(doc); } - @Test void testContainingPredicateOnFreeFormTextMiddleIncompleteWords() { + @Test + void testContainingPredicateOnFreeFormTextMiddleIncompleteWords() { doc3Repository.deleteAll(); var doc = Doc3.of("someDoc"); doc.setSecond("some text about nothing"); doc.setThird("some other text"); doc3Repository.save(doc); - var docs = entityStream.of(Doc3.class) - .filter(Doc3$.SECOND.containing("ext abou")) - .collect(Collectors.toList()); + var docs = entityStream.of(Doc3.class).filter(Doc3$.SECOND.containing("ext abou")).collect(Collectors.toList()); assertEquals(1, docs.size()); assertThat(docs.get(0).getSecond()).isEqualTo("some text about nothing"); @@ -2517,14 +2705,11 @@ void testOrElseAndUpdate() { String name = "NewCompany"; String email = "info@newcompany.com"; - entityStream.of(Company.class) - .filter(Company$.NAME.eq(name)) - .findFirstOrElse(() -> { - Company newCompany = Company.of(name, 2023, LocalDate.now(), new Point(0, 0), email); - newCompany.setTags(Collections.emptySet()); - return repository.save(newCompany); - }) - .forEach(Company$.TAGS.add("innovative")); + entityStream.of(Company.class).filter(Company$.NAME.eq(name)).findFirstOrElse(() -> { + Company newCompany = Company.of(name, 2023, LocalDate.now(), new Point(0, 0), email); + newCompany.setTags(Collections.emptySet()); + return repository.save(newCompany); + }).forEach(Company$.TAGS.add("innovative")); Optional maybeCompany = repository.findFirstByName(name); assertTrue(maybeCompany.isPresent()); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHashTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHashTest.java index 6b769daf..ec23d2d1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHashTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHashTest.java @@ -25,36 +25,40 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class EntityStreamHashTest extends AbstractBaseEnhancedRedisTest { - @Autowired CompanyRepository repository; +@SuppressWarnings("SpellCheckingInspection") +class EntityStreamHashTest extends AbstractBaseEnhancedRedisTest { + @Autowired + CompanyRepository repository; @Autowired ASimpleHashRepository aSimpleHashRepository; - @Autowired EntityStream entityStream; + @Autowired + EntityStream entityStream; String redisId; String microsoftId; String teslaId; - @BeforeEach void cleanUp() { + @BeforeEach + void cleanUp() { if (repository.count() == 0) { Company redis = repository.save(Company.of( // - "RedisInc", 2011, // - LocalDate.of(2021, 5, 1), // - new Point(-122.066540, 37.377690), "stack@redis.com" // + "RedisInc", 2011, // + LocalDate.of(2021, 5, 1), // + new Point(-122.066540, 37.377690), "stack@redis.com" // )); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Company microsoft = repository.save(Company.of(// - "Microsoft", 1975, // - LocalDate.of(2022, 8, 15), // - new Point(-122.124500, 47.640160), "research@microsoft.com" // + "Microsoft", 1975, // + LocalDate.of(2022, 8, 15), // + new Point(-122.124500, 47.640160), "research@microsoft.com" // )); microsoft.setTags(Set.of("innovative", "reliable", "os", "ai")); Company tesla = repository.save(Company.of( // - "Tesla", 2003, // - LocalDate.of(2022, 1, 1), // - new Point(-97.6208903, 30.2210767), "elon@tesla.com" // + "Tesla", 2003, // + LocalDate.of(2022, 1, 1), // + new Point(-97.6208903, 30.2210767), "elon@tesla.com" // )); tesla.setTags(Set.of("innovative", "futuristic", "ai")); @@ -67,7 +71,8 @@ teslaId = saved.get(2).getId(); } - @Test void testStreamSelectAll() { + @Test + void testStreamSelectAll() { SearchStream stream = entityStream.of(Company.class); List allCompanies = stream.collect(Collectors.toList()); @@ -75,264 +80,288 @@ assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByOnePropertyEquals() { + @Test + void testFindByOnePropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.eq("RedisInc")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.eq("RedisInc")) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByOnePropertyNotEquals() { + @Test + void testFindByOnePropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.notEq("RedisInc")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.notEq("RedisInc")) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft", "Tesla"); } - @Test void testFindByTwoPropertiesOredEquals() { + @Test + void testFindByTwoPropertiesOredEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.eq("RedisInc") // - .or(Company$.NAME.eq("Microsoft")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.eq("RedisInc") // + .or(Company$.NAME.eq("Microsoft")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft"); } - @Test void testFindByThreePropertiesOredEquals() { + @Test + void testFindByThreePropertiesOredEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.eq("RedisInc") // - .or(Company$.NAME.eq("Microsoft")) // - .or(Company$.NAME.eq("Tesla")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.eq("RedisInc") // + .or(Company$.NAME.eq("Microsoft")) // + .or(Company$.NAME.eq("Tesla")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByThreePropertiesOrList() { + @Test + void testFindByThreePropertiesOrList() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.in("RedisInc", "Microsoft", "Tesla")).collect(Collectors.toList()); + .filter(Company$.NAME.in("RedisInc", "Microsoft", "Tesla")).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByThreePropertiesOrList2() { + @Test + void testFindByThreePropertiesOrList2() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.in("RedisInc", "Tesla")).collect(Collectors.toList()); + .filter(Company$.NAME.in("RedisInc", "Tesla")).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Tesla"); } - @Test void testFindByThreeNumericPropertiesOrList() { + @Test + void testFindByThreeNumericPropertiesOrList() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.in(2011, 1975, 2003)).collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.in(2011, 1975, 2003)).collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Microsoft", "Tesla"); } - @Test void testFindByTwoPropertiesAndedNotEquals() { + @Test + void testFindByTwoPropertiesAndedNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ) // - .collect(Collectors.toList()); + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla"); } - @Test void testFindByNumericPropertyEquals() { + @Test + void testFindByNumericPropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.eq(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.eq(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByNumericPropertyNotEquals() { + @Test + void testFindByNumericPropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.notEq(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.notEq(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla", "Microsoft"); } - @Test void testFindByNumericPropertyGreaterThan() { + @Test + void testFindByNumericPropertyGreaterThan() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.gt(2000)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.gt(2000)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc", "Tesla"); } - @Test void testFindByNumericPropertyGreaterThanOrEqual() { + @Test + void testFindByNumericPropertyGreaterThanOrEqual() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.ge(2011)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.ge(2011)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testFindByNumericPropertyLessThan() { + @Test + void testFindByNumericPropertyLessThan() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.lt(2000)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.lt(2000)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft"); } - @Test void testFindByNumericPropertyLessThanOrEqual() { + @Test + void testFindByNumericPropertyLessThanOrEqual() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.le(1975)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.le(1975)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Microsoft"); } - @Test void testFindByNumericPropertyBetween() { + @Test + void testFindByNumericPropertyBetween() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.YEAR_FOUNDED.between(1976, 2010)) // - .collect(Collectors.toList()); + .filter(Company$.YEAR_FOUNDED.between(1976, 2010)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("Tesla"); } - @Test void testCount() { + @Test + void testCount() { long count = entityStream // - .of(Company.class) // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ).count(); + .of(Company.class) // + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ).count(); assertEquals(1, count); } - @Test void testLimit() { + @Test + void testLimit() { List companies = entityStream // - .of(Company.class) // - .limit(2).collect(Collectors.toList()); + .of(Company.class) // + .limit(2).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSkip() { + @Test + void testSkip() { List companies = entityStream // - .of(Company.class) // - .skip(1).collect(Collectors.toList()); + .of(Company.class) // + .skip(1).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSortDefaultAscending() { + @Test + void testSortDefaultAscending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "RedisInc", "Tesla"); } - @Test void testSortAscending() { + @Test + void testSortAscending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.ASC) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.ASC) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "RedisInc", "Tesla"); } - @Test void testSortDescending() { + @Test + void testSortDescending() { List companies = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "RedisInc", "Microsoft"); } - @Test void testForEachOrdered() { + @Test + void testForEachOrdered() { List companies = new ArrayList<>(); Consumer testConsumer = companies::add; entityStream // - .of(Company.class) // - .forEachOrdered(testConsumer); + .of(Company.class) // + .forEachOrdered(testConsumer); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc", "Microsoft", "Tesla"); } - @Test void testMapToOneProperty() { + @Test + void testMapToOneProperty() { List names = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "RedisInc", "Microsoft"); } - @Test void testMapToTwoProperties() { + @Test + void testMapToTwoProperties() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED)) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED)) // + .collect(Collectors.toList()); assertEquals(3, results.size()); @@ -345,12 +374,13 @@ assertEquals(1975, results.get(2).getSecond()); } - @Test void testMapToThreeProperties() { + @Test + void testMapToThreeProperties() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // + .collect(Collectors.toList()); assertEquals(3, results.size()); @@ -367,72 +397,78 @@ assertEquals(results.get(2).getThird(), new Point(-122.124500, 47.640160)); } - @Test void testGeoNearPredicate() { + @Test + void testGeoNearPredicate() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.near(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.near(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc"); } - @Test void testGeoOutsideOfPredicate() { + @Test + void testGeoOutsideOfPredicate() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.outsideOf(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.outsideOf(new Point(-122.064, 37.384), new Distance(30, Metrics.MILES))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("Tesla", "Microsoft"); } - @Test void testGeoEqPredicateUsingPoint() { + @Test + void testGeoEqPredicateUsingPoint() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq(new Point(-122.066540, 37.377690))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq(new Point(-122.066540, 37.377690))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertThat(names).containsExactly("RedisInc"); } - @Test void testGeoEqPredicateUsingCSV() { + @Test + void testGeoEqPredicateUsingCSV() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq("-122.066540, 37.377690")) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq("-122.066540, 37.377690")) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertEquals("RedisInc", names.get(0)); } - @Test void testGeoEqPredicateUsingDoubles() { + @Test + void testGeoEqPredicateUsingDoubles() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.eq(-122.066540, 37.377690)) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.eq(-122.066540, 37.377690)) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertEquals("RedisInc", names.get(0)); } - @Test void testGeoNotEqPredicateUsingPoint() { + @Test + void testGeoNotEqPredicateUsingPoint() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq(new Point(-122.066540, 37.377690))) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq(new Point(-122.066540, 37.377690))) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -440,13 +476,14 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testGeoNotEqPredicateUsingCSV() { + @Test + void testGeoNotEqPredicateUsingCSV() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq("-122.066540, 37.377690")) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq("-122.066540, 37.377690")) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -454,13 +491,14 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testGeoNotEqPredicateUsingDoubles() { + @Test + void testGeoNotEqPredicateUsingDoubles() { List names = entityStream // - .of(Company.class) // - .filter(Company$.LOCATION.notEq(-122.066540, 37.377690)) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.LOCATION.notEq(-122.066540, 37.377690)) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -468,12 +506,13 @@ assertEquals("Microsoft", names.get(1)); } - @Test void testFindByTextLike() { + @Test + void testFindByTextLike() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.like("Micros")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.like("Micros")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -482,12 +521,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextNotLike() { + @Test + void testFindByTextNotLike() { List names = entityStream // - .of(Company.class) // - .filter(Company$.NAME.notLike("Micros")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.notLike("Micros")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -495,12 +535,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTextContaining() { + @Test + void testFindByTextContaining() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.containing("Micros")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.containing("Micros")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -509,12 +550,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextNotContaining() { + @Test + void testFindByTextNotContaining() { List names = entityStream // - .of(Company.class) // - .filter(Company$.NAME.notContaining("Micros")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.notContaining("Micros")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -522,12 +564,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTextThatStartsWith() { + @Test + void testFindByTextThatStartsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.startsWith("Mic")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.startsWith("Mic")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -536,12 +579,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTextThatEndsWith() { + @Test + void testFindByTextThatEndsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.endsWith("soft")) // - .collect(Collectors.toList()); + .filter(Company$.NAME.endsWith("soft")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -550,12 +594,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTagsIn() { + @Test + void testFindByTagsIn() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.in("reliable")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.in("reliable")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(2, names.size()); @@ -563,12 +608,13 @@ assertTrue(names.contains("Microsoft")); } - @Test void testFindByTagsIn2() { + @Test + void testFindByTagsIn2() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.in("reliable", "ai")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.in("reliable", "ai")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(3, names.size()); @@ -577,91 +623,99 @@ assertTrue(names.contains("Tesla")); } - @Test void testFindByTagsContainingAll() { + @Test + void testFindByTagsContainingAll() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.containsAll("fast", "scalable", "reliable", "database", "nosql")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.containsAll("fast", "scalable", "reliable", "database", "nosql")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsEquals() { + @Test + void testFindByTagsEquals() { Set tags = Set.of("fast", "scalable", "reliable", "database", "nosql"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.eq(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.eq(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsNotEqualsSingleValue() { + @Test + void testFindByTagsNotEqualsSingleValue() { List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.notEq("ai")) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.notEq("ai")) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagsNotEquals() { + @Test + void testFindByTagsNotEquals() { Set tags = Set.of("fast", "scalable", "reliable", "database", "nosql"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.notEq(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.notEq(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("Tesla")); } - @Test void testFindByTagsContainsNone() { + @Test + void testFindByTagsContainsNone() { Set tags = Set.of("innovative"); List names = entityStream // - .of(Company.class) // - .filter(Company$.TAGS.containsNone(tags)) // - .map(Company$.NAME) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.TAGS.containsNone(tags)) // + .map(Company$.NAME) // + .collect(Collectors.toList()); assertEquals(1, names.size()); assertTrue(names.contains("RedisInc")); } - @Test void testFindFirst() { + @Test + void testFindFirst() { Optional maybeCompany = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .findFirst(); + .filter(Company$.NAME.eq("RedisInc")) // + .findFirst(); assertTrue(maybeCompany.isPresent()); assertEquals("RedisInc", maybeCompany.get().getName()); } - @Test void testFindAny() { + @Test + void testFindAny() { Optional maybeCompany = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .findAny(); + .filter(Company$.NAME.eq("RedisInc")) // + .findAny(); assertTrue(maybeCompany.isPresent()); assertEquals("RedisInc", maybeCompany.get().getName()); } - @Test void testFindByTagEscapesChars() { + @Test + void testFindByTagEscapesChars() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.eq("stack@redis.com")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.eq("stack@redis.com")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -669,128 +723,141 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByDatePropertyEquals() { + @Test + void testFindByDatePropertyEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.eq(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.eq(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Tesla"); } - @Test void testFindByDatePropertyNotEquals() { + @Test + void testFindByDatePropertyNotEquals() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.notEq(LocalDate.of(2021, 5, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.notEq(LocalDate.of(2021, 5, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyIsAfter() { + @Test + void testFindByDatePropertyIsAfter() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.after(LocalDate.of(2021, 5, 2))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.after(LocalDate.of(2021, 5, 2))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyIsOnOrAfter() { + @Test + void testFindByDatePropertyIsOnOrAfter() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.onOrAfter(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.onOrAfter(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("Microsoft", "Tesla"); } - @Test void testFindByDatePropertyBefore() { + @Test + void testFindByDatePropertyBefore() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.before(LocalDate.of(2021, 6, 15))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.before(LocalDate.of(2021, 6, 15))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc"); } - @Test void testFindByDatePropertyIsOnOrBefore() { + @Test + void testFindByDatePropertyIsOnOrBefore() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.onOrBefore(LocalDate.of(2022, 1, 1))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.onOrBefore(LocalDate.of(2022, 1, 1))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc", "Tesla"); } - @Test void testFindByDatePropertyIsBetween() { + @Test + void testFindByDatePropertyIsBetween() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.LAST_VALUATION.between(LocalDate.of(2021, 5, 1), LocalDate.of(2022, 8, 15))) // - .collect(Collectors.toList()); + .filter(Company$.LAST_VALUATION.between(LocalDate.of(2021, 5, 1), LocalDate.of(2022, 8, 15))) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).toList(); assertThat(names).containsExactly("RedisInc", "Microsoft", "Tesla"); } - @Test void testFilterWithNonSearchFieldPredicateIsNoop() { + @Test + void testFilterWithNonSearchFieldPredicateIsNoop() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(c -> c.toString().equals("foo")) // - .collect(Collectors.toList()); + .filter(c -> c.toString().equals("foo")) // + .collect(Collectors.toList()); assertEquals(repository.count(), companies.size()); } - @Test void testMapToIntOnReturnFields() { + @Test + void testMapToIntOnReturnFields() { IntStream intStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .mapToInt(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .mapToInt(i -> i); assertThat(intStream.boxed().collect(Collectors.toList())).contains(2011, 1975, 2003); } - @Test void testMapToInt() { + @Test + void testMapToInt() { IntStream intStream = entityStream // - .of(Company.class) // - .mapToInt(Company::getYearFounded); + .of(Company.class) // + .mapToInt(Company::getYearFounded); assertThat(intStream.boxed().collect(Collectors.toList())).contains(2011, 1975, 2003); } - @Test void testMapToLongOnReturnFields() { + @Test + void testMapToLongOnReturnFields() { LongStream longStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .mapToLong(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .mapToLong(i -> i); assertThat(longStream.boxed().collect(Collectors.toList())).contains(2011L, 1975L, 2003L); } - @Test void testMapToLong() { + @Test + void testMapToLong() { LongStream longStream = entityStream // - .of(Company.class) // - .mapToLong(Company::getYearFounded); + .of(Company.class) // + .mapToLong(Company::getYearFounded); assertThat(longStream.boxed().collect(Collectors.toList())).contains(2011L, 1975L, 2003L); } - @Test void testFlatMapToInt() { + @Test + void testFlatMapToInt() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -801,15 +868,16 @@ // actual IntStream tagLengthIntStream = entityStream // - .of(Company.class) // - .flatMapToInt(c -> c.getTags().stream().mapToInt(String::length)); + .of(Company.class) // + .flatMapToInt(c -> c.getTags().stream().mapToInt(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToLong() { + @Test + void testFlatMapToLong() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -820,15 +888,16 @@ // actual LongStream tagLengthIntStream = entityStream // - .of(Company.class) // - .flatMapToLong(c -> c.getTags().stream().mapToLong(String::length)); + .of(Company.class) // + .flatMapToLong(c -> c.getTags().stream().mapToLong(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testFlatMapToDouble() { + @Test + void testFlatMapToDouble() { // expected List expected = new ArrayList<>(); for (Company company : entityStream.of(Company.class).collect(Collectors.toList())) { @@ -839,21 +908,22 @@ // actual DoubleStream tagLengthDoubleStream = entityStream // - .of(Company.class) // - .flatMapToDouble(c -> c.getTags().stream().mapToDouble(String::length)); + .of(Company.class) // + .flatMapToDouble(c -> c.getTags().stream().mapToDouble(String::length)); List actual = tagLengthDoubleStream.boxed().collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } - @Test void testPeek() { + @Test + void testPeek() { final List peekedEmails = new ArrayList<>(); List companies = entityStream // - .of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .peek(c -> peekedEmails.add(c.getEmail())) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.eq("RedisInc")) // + .peek(c -> peekedEmails.add(c.getEmail())) // + .collect(Collectors.toList()); assertThat(peekedEmails).containsExactly("stack@redis.com"); @@ -863,10 +933,11 @@ assertTrue(names.contains("RedisInc")); } - @Test void testToArray() { + @Test + void testToArray() { Object[] allCompanies = entityStream // - .of(Company.class) // - .toArray(); + .of(Company.class) // + .toArray(); assertEquals(3, allCompanies.length); @@ -876,10 +947,11 @@ assertTrue(names.contains("Tesla")); } - @Test void testToArrayTyped() { + @Test + void testToArrayTyped() { Company[] allCompanies = entityStream // - .of(Company.class) // - .toArray(Company[]::new); + .of(Company.class) // + .toArray(Company[]::new); assertEquals(3, allCompanies.length); @@ -889,235 +961,258 @@ assertTrue(names.contains("Tesla")); } - @Test void testReduceWithIdentityBifunctionAndBinaryOperator() { + @Test + void testReduceWithIdentityBifunctionAndBinaryOperator() { Integer firstEstablish = entityStream // - .of(Company.class) // - .reduce(Integer.MAX_VALUE, (minimum, company) -> Integer.min(minimum, company.getYearFounded()), (t, u) -> Integer.min(t, u)); + .of(Company.class) // + .reduce(Integer.MAX_VALUE, (minimum, company) -> Integer.min(minimum, company.getYearFounded()), + (t, u) -> Integer.min(t, u)); assertThat(firstEstablish).isEqualTo(1975); } - @Test void testReduceWithMethodReferenceAndCombiner() { + @Test + void testReduceWithMethodReferenceAndCombiner() { int result = entityStream // - .of(Company.class) // - .reduce(0, (acc, company) -> acc + company.getYearFounded(), (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .reduce(0, (acc, company) -> acc + company.getYearFounded(), (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithCombiner() { + @Test + void testReduceWithCombiner() { BinaryOperator establishedFirst = (c1, c2) -> c1.getYearFounded() < c2.getYearFounded() ? c1 : c2; Optional firstEstablish = entityStream // - .of(Company.class) // - .reduce(establishedFirst); + .of(Company.class) // + .reduce(establishedFirst); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testReduceWithIdAndCombiner() { + @Test + void testReduceWithIdAndCombiner() { BinaryOperator establishedFirst = (c1, c2) -> c1.getYearFounded() < c2.getYearFounded() ? c1 : c2; Company c = new Company(); c.setYearFounded(Integer.MAX_VALUE); Optional firstEstablish = Optional.of(entityStream // - .of(Company.class) // - .reduce(c, establishedFirst)); + .of(Company.class) // + .reduce(c, establishedFirst)); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testReduceWithMethodReferenceOnMappedField() { + @Test + void testReduceWithMethodReferenceOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithLambdaOnMappedField() { + @Test + void testReduceWithLambdaOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } - @Test void testReduceWithCombinerOnMappedField() { + @Test + void testReduceWithCombinerOnMappedField() { BinaryOperator establishedFirst = (c1, c2) -> c1 < c2 ? c1 : c2; Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(establishedFirst); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(establishedFirst); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } - @Test void testReduceWithIdentityBifunctionAndBinaryOperatorOnMappedField() { + @Test + void testReduceWithIdentityBifunctionAndBinaryOperatorOnMappedField() { Integer firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); assertThat(firstEstablish).isEqualTo(1975); } - @Test void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { + @Test + void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { Supplier supplier = AtomicInteger::new; BiConsumer accumulator = (AtomicInteger a, Integer i) -> a.set(a.get() + i); BiConsumer combiner = (a1, a2) -> a1.set(a1.get() + a2.get()); AtomicInteger result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .collect(supplier, accumulator, combiner); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .collect(supplier, accumulator, combiner); assertThat(result.intValue()).isEqualTo(2011 + 1975 + 2003); } - @Test void testCollectWithIdAndCombiner() { + @Test + void testCollectWithIdAndCombiner() { Supplier supplier = AtomicInteger::new; - BiConsumer accumulator = (AtomicInteger a, Company c) -> a.set(a.get() + c.getYearFounded()); + BiConsumer accumulator = (AtomicInteger a, Company c) -> a.set( + a.get() + c.getYearFounded()); BiConsumer combiner = (a1, a2) -> a1.set(a1.get() + a2.get()); AtomicInteger result = entityStream // - .of(Company.class) // - .collect(supplier, accumulator, combiner); + .of(Company.class) // + .collect(supplier, accumulator, combiner); assertThat(result.intValue()).isEqualTo(2011 + 1975 + 2003); } - @Test void testMinOnMappedField() { + @Test + void testMinOnMappedField() { Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .min(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .min(Integer::compareTo); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } - @Test void testMaxOnMappedField() { + @Test + void testMaxOnMappedField() { Optional lastEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .max(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .max(Integer::compareTo); assertAll( // - () -> assertThat(lastEstablish).isPresent(), // - () -> assertThat(lastEstablish).contains(2011) // + () -> assertThat(lastEstablish).isPresent(), // + () -> assertThat(lastEstablish).contains(2011) // ); } - @Test void testAnyMatchOnMappedField() { + @Test + void testAnyMatchOnMappedField() { boolean c1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .anyMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .anyMatch(c -> c == 1975); boolean c1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .anyMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .anyMatch(c -> c == 1976); assertThat(c1975).isTrue(); assertThat(c1976).isFalse(); } - @Test void testAllMatchOnMappedField() { + @Test + void testAllMatchOnMappedField() { boolean allEstablishedBefore1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .allMatch(c -> c < 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .allMatch(c -> c < 1970); boolean allEstablishedOnOrAfter1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .allMatch(c -> c >= 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .allMatch(c -> c >= 1970); assertThat(allEstablishedOnOrAfter1970).isTrue(); assertThat(allEstablishedBefore1970).isFalse(); } - @Test void testNoneMatchOnMappedField() { + @Test + void testNoneMatchOnMappedField() { boolean noneIn1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .noneMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .noneMatch(c -> c == 1975); boolean noneIn1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .noneMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .noneMatch(c -> c == 1976); assertThat(noneIn1976).isTrue(); assertThat(noneIn1975).isFalse(); } - @Test void testMin() { + @Test + void testMin() { Optional firstEstablish = entityStream // - .of(Company.class) // - .min(Comparator.comparing(Company::getYearFounded)); + .of(Company.class) // + .min(Comparator.comparing(Company::getYearFounded)); assertThat(firstEstablish).isPresent(); assertThat(firstEstablish.get().getYearFounded()).isEqualTo(1975); } - @Test void testMax() { + @Test + void testMax() { Optional lastEstablish = entityStream // - .of(Company.class) // - .max(Comparator.comparing(Company::getYearFounded)); + .of(Company.class) // + .max(Comparator.comparing(Company::getYearFounded)); assertThat(lastEstablish).isPresent(); assertThat(lastEstablish.get().getYearFounded()).isEqualTo(2011); } - @Test void testAnyMatch() { + @Test + void testAnyMatch() { boolean c1975 = entityStream // - .of(Company.class) // - .anyMatch(c -> c.getYearFounded() == 1975); + .of(Company.class) // + .anyMatch(c -> c.getYearFounded() == 1975); boolean c1976 = entityStream // - .of(Company.class) // - .anyMatch(c -> c.getYearFounded() == 1976); + .of(Company.class) // + .anyMatch(c -> c.getYearFounded() == 1976); assertThat(c1975).isTrue(); assertThat(c1976).isFalse(); } - @Test void testAllMatch() { + @Test + void testAllMatch() { boolean allEstablishedBefore1970 = entityStream // - .of(Company.class) // - .allMatch(c -> c.getYearFounded() < 1970); + .of(Company.class) // + .allMatch(c -> c.getYearFounded() < 1970); boolean allEstablishedOnOrAfter1970 = entityStream // - .of(Company.class) // - .allMatch(c -> c.getYearFounded() >= 1970); + .of(Company.class) // + .allMatch(c -> c.getYearFounded() >= 1970); assertThat(allEstablishedOnOrAfter1970).isTrue(); assertThat(allEstablishedBefore1970).isFalse(); } - @Test void testNoneMatch() { + @Test + void testNoneMatch() { boolean noneIn1975 = entityStream // - .of(Company.class) // - .noneMatch(c -> c.getYearFounded() == 1975); + .of(Company.class) // + .noneMatch(c -> c.getYearFounded() == 1975); boolean noneIn1976 = entityStream // - .of(Company.class) // - .noneMatch(c -> c.getYearFounded() == 1976); + .of(Company.class) // + .noneMatch(c -> c.getYearFounded() == 1976); assertThat(noneIn1976).isTrue(); assertThat(noneIn1975).isFalse(); } - @Test void testIterator() { + @Test + void testIterator() { List allCompanies = new ArrayList<>(); for (Iterator iterator = entityStream.of(Company.class).iterator(); iterator.hasNext(); ) { allCompanies.add(iterator.next()); @@ -1131,7 +1226,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIterator() { + @Test + void testSplitIterator() { ArrayList allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1147,7 +1243,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testNoops() { + @Test + void testNoops() { SearchStream stream = entityStream.of(Company.class); assertThat(stream.isParallel()).isFalse(); assertThat(stream.parallel()).isEqualTo(stream); @@ -1155,7 +1252,8 @@ assertThat(stream.unordered()).isEqualTo(stream); } - @Test void testCloseHandler() { + @Test + void testCloseHandler() { SearchStream stream = entityStream.of(Company.class); AtomicBoolean wasClosed = new AtomicBoolean(false); //noinspection ResultOfMethodCallIgnored @@ -1164,7 +1262,8 @@ assertThat(wasClosed.get()).isTrue(); } - @Test void testCloseHandlerIsNull() { + @Test + void testCloseHandlerIsNull() { SearchStream stream = entityStream.of(Company.class); stream.close(); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, stream::findAny); @@ -1173,10 +1272,11 @@ Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - @Test void testIteratorOnMappedField() { + @Test + void testIteratorOnMappedField() { List allCompanies = new ArrayList<>(); for (Iterator iterator = entityStream.of(Company.class).map(Company$.NAME) - .iterator(); iterator.hasNext(); ) { + .iterator(); iterator.hasNext(); ) { allCompanies.add(iterator.next()); } @@ -1188,7 +1288,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIteratorOnMappedField() { + @Test + void testSplitIteratorOnMappedField() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1204,12 +1305,14 @@ assertTrue(names.contains("Tesla")); } - @Test void testStreamOnMappedFieldIsNotParallel() { + @Test + void testStreamOnMappedFieldIsNotParallel() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); assertThat(stream.isParallel()).isFalse(); } - @Test void testCloseHandlerOnMappedField() { + @Test + void testCloseHandlerOnMappedField() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); AtomicBoolean wasClosed = new AtomicBoolean(false); //noinspection ResultOfMethodCallIgnored @@ -1218,7 +1321,8 @@ assertThat(wasClosed.get()).isTrue(); } - @Test void testCloseHandlerIsNullOnMappedField() { + @Test + void testCloseHandlerIsNullOnMappedField() { SearchStream stream = entityStream.of(Company.class).map(Company$.NAME); stream.close(); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, stream::findAny); @@ -1227,39 +1331,43 @@ Assertions.assertEquals(expectedErrorMessage, exception.getMessage()); } - @Test void testFilterOnMappedField() { + @Test + void testFilterOnMappedField() { Predicate predicate = i -> (i > 2000); List foundedAfter2000 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .filter(predicate) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .filter(predicate) // + .collect(Collectors.toList()); assertThat(foundedAfter2000).contains(2011, 2003); } - @Test void testFlatMapOnMappedField() { - Function> mapper = (Company company) -> Stream.of(String.join("-", new TreeSet<>(company.getTags()))); + @Test + void testFlatMapOnMappedField() { + Function> mapper = (Company company) -> Stream.of( + String.join("-", new TreeSet<>(company.getTags()))); List joinedTags = entityStream // - .of(Company.class) // - .flatMap(mapper) // - .collect(Collectors.toList()); + .of(Company.class) // + .flatMap(mapper) // + .collect(Collectors.toList()); assertThat(joinedTags).containsExactly( // - "database-fast-nosql-reliable-scalable", // - "ai-innovative-os-reliable", // - "ai-futuristic-innovative" // + "database-fast-nosql-reliable-scalable", // + "ai-innovative-os-reliable", // + "ai-futuristic-innovative" // ); } - @Test void testForEachOrderedOnMappedField() { + @Test + void testForEachOrderedOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .forEachOrdered(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .forEachOrdered(testConsumer); assertEquals(3, names.size()); @@ -1268,13 +1376,14 @@ assertEquals("Tesla", names.get(2)); } - @Test void testForEachOnMappedField() { + @Test + void testForEachOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .forEach(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .forEach(testConsumer); assertEquals(3, names.size()); @@ -1283,11 +1392,12 @@ assertEquals("Tesla", names.get(2)); } - @Test void testToArrayOnMappedField() { + @Test + void testToArrayOnMappedField() { Object[] allCompanies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .toArray(); + .of(Company.class) // + .map(Company$.NAME) // + .toArray(); assertEquals(3, allCompanies.length); @@ -1298,11 +1408,12 @@ assertTrue(names.contains("Tesla")); } - @Test void testToArrayTypedOnMappedField() { + @Test + void testToArrayTypedOnMappedField() { String[] namesArray = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .toArray(String[]::new); + .of(Company.class) // + .map(Company$.NAME) // + .toArray(String[]::new); assertEquals(3, namesArray.length); @@ -1312,44 +1423,48 @@ assertTrue(names.contains("Tesla")); } - @Test void testCountOnMappedField() { + @Test + void testCountOnMappedField() { long count = entityStream // - .of(Company.class) // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ) // - .map(Company$.NAME) // - .count(); + .of(Company.class) // + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ) // + .map(Company$.NAME) // + .count(); assertEquals(1, count); } - @Test void testLimitOnMappedField() { + @Test + void testLimitOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .limit(2).collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .limit(2).collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSkipOnMappedField() { + @Test + void testSkipOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .skip(1) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .skip(1) // + .collect(Collectors.toList()); assertEquals(2, companies.size()); } - @Test void testSortOnMappedField() { + @Test + void testSortOnMappedField() { List names = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sorted(Comparator.reverseOrder()) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .sorted(Comparator.reverseOrder()) // + .collect(Collectors.toList()); assertEquals(3, names.size()); @@ -1358,41 +1473,45 @@ assertEquals("Microsoft", names.get(2)); } - @Test void testPeekOnMappedField() { + @Test + void testPeekOnMappedField() { final List peekedEmails = new ArrayList<>(); List emails = entityStream // - .of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .peek(peekedEmails::add) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .peek(peekedEmails::add) // + .collect(Collectors.toList()); assertThat(peekedEmails).containsExactly("stack@redis.com"); assertEquals(1, emails.size()); } - @Test void testFindFirstOnMappedField() { + @Test + void testFindFirstOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .findFirst(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .findFirst(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); } - @Test void testFindAnyOnMappedField() { + @Test + void testFindAnyOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .findAny(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .findAny(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); } - @Test void testNoopsOnMappedField() { + @Test + void testNoopsOnMappedField() { Iterator iter1 = entityStream.of(Company.class).map(Company$.NAME).iterator(); Iterator iter2 = entityStream.of(Company.class).map(Company$.NAME).iterator(); Iterator iter3 = entityStream.of(Company.class).map(Company$.NAME).iterator(); @@ -1404,21 +1523,23 @@ assertThat(Iterators.elementsEqual(iter3, unordered.iterator())).isTrue(); } - @Test void testMapOnMappedField() { + @Test + void testMapOnMappedField() { ToLongFunction func = y -> y - 1; List yearsMinusOne = entityStream.of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .map(func) // - .collect(Collectors.toList()); + .map(Company$.YEAR_FOUNDED) // + .map(func) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(yearsMinusOne).hasSize(3), // - () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // + () -> assertThat(yearsMinusOne).hasSize(3), // + () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // ); } - @Test void testSplitIteratorOnMappedFieldParallelStream() { + @Test + void testSplitIteratorOnMappedFieldParallelStream() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).parallel().spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1434,7 +1555,8 @@ assertTrue(names.contains("Tesla")); } - @Test void testSplitIteratorOnMappedFieldSequentialStream() { + @Test + void testSplitIteratorOnMappedFieldSequentialStream() { List allCompanies = new ArrayList<>(); Spliterator iter1 = entityStream.of(Company.class).map(Company$.NAME).sequential().spliterator(); Spliterator iter2 = iter1.trySplit(); @@ -1450,47 +1572,50 @@ assertTrue(names.contains("Tesla")); } - @Test void testTupleResultWithLabels() { + @Test + void testTupleResultWithLabels() { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // - .mapToLabelledMaps().toList(); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // + .mapToLabelledMaps().toList(); assertEquals(3, results.size()); assertThat(results.get(0)) // - .containsEntry("name", "Tesla") // - .containsEntry("yearFounded", 2003) // - .containsEntry("location", new Point(-97.6208903, 30.2210767)); + .containsEntry("name", "Tesla") // + .containsEntry("yearFounded", 2003) // + .containsEntry("location", new Point(-97.6208903, 30.2210767)); assertThat(results.get(1)) // - .containsEntry("name", "RedisInc") // - .containsEntry("yearFounded", 2011) // - .containsEntry("location", new Point(-122.066540, 37.377690)); + .containsEntry("name", "RedisInc") // + .containsEntry("yearFounded", 2011) // + .containsEntry("location", new Point(-122.066540, 37.377690)); assertThat(results.get(2)) // - .containsEntry("name", "Microsoft") // - .containsEntry("yearFounded", 1975) // - .containsEntry("location", new Point(-122.124500, 47.640160)); + .containsEntry("name", "Microsoft") // + .containsEntry("yearFounded", 1975) // + .containsEntry("location", new Point(-122.124500, 47.640160)); } - @Test void testMapToIdProperty() { + @Test + void testMapToIdProperty() { List ids = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Company$.ID) // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Company$.ID) // + .collect(Collectors.toList()); assertThat(ids).containsExactly(teslaId, redisId, microsoftId); } - @Test void testFindByTagStartsWith() { + @Test + void testFindByTagStartsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.startsWith("sta")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.startsWith("sta")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -1498,12 +1623,13 @@ assertTrue(names.contains("RedisInc")); } - @Test void testFindByTagEndsWith() { + @Test + void testFindByTagEndsWith() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.EMAIL.endsWith("sla.com")) // - .collect(Collectors.toList()); + .filter(Company$.EMAIL.endsWith("sla.com")) // + .collect(Collectors.toList()); assertEquals(1, companies.size()); @@ -1511,37 +1637,37 @@ assertTrue(names.contains("Tesla")); } - @Test void testIgnorePredicatesWithNullParamsAnded() { + @Test + void testIgnorePredicatesWithNullParamsAnded() { SearchStream stream = entityStream.of(Company.class); List companies = stream // - .filter(Company$.NAME.eq("RedisInc")) // - .filter(Company$.YEAR_FOUNDED.eq(null)) // - .collect(Collectors.toList()); + .filter(Company$.NAME.eq("RedisInc")) // + .filter(Company$.YEAR_FOUNDED.eq(null)) // + .collect(Collectors.toList()); List names = companies.stream().map(Company::getName).collect(Collectors.toList()); assertThat(names).contains("RedisInc"); } - @Test void testMapAgainstEmptyResults() { + @Test + void testMapAgainstEmptyResults() { List names = entityStream // .of(Company.class) // - .filter(Company$.NAME.startsWith("Open")) - .map(Company$.ID) - .collect(Collectors.toList()); + .filter(Company$.NAME.startsWith("Open")).map(Company$.ID).collect(Collectors.toList()); assertThat(names).isEmpty(); } - @Test void testContainingPredicateOnFreeFormTextStartMatches() { + @Test + void testContainingPredicateOnFreeFormTextStartMatches() { var hash = ASimpleHash.of("someDoc"); hash.setSecond("some text about nothing"); hash.setThird("some other text"); aSimpleHashRepository.save(hash); - var hashes = entityStream.of(ASimpleHash.class) - .filter(ASimpleHash$.SECOND.containing("some text")) + var hashes = entityStream.of(ASimpleHash.class).filter(ASimpleHash$.SECOND.containing("some text")) .collect(Collectors.toList()); assertEquals(1, hashes.size()); @@ -1550,15 +1676,15 @@ aSimpleHashRepository.delete(hash); } - @Test void testContainingPredicateOnFreeFormTextMiddleMatches() { + @Test + void testContainingPredicateOnFreeFormTextMiddleMatches() { var hash = ASimpleHash.of("someDoc"); hash.setSecond("some text about nothing"); hash.setThird("some other text"); aSimpleHashRepository.save(hash); - var hashes = entityStream.of(ASimpleHash.class) - .filter(ASimpleHash$.SECOND.containing("text about")) + var hashes = entityStream.of(ASimpleHash.class).filter(ASimpleHash$.SECOND.containing("text about")) .collect(Collectors.toList()); assertEquals(1, hashes.size()); @@ -1567,15 +1693,15 @@ aSimpleHashRepository.delete(hash); } - @Test void testContainingPredicateOnFreeFormTextEndMatches() { + @Test + void testContainingPredicateOnFreeFormTextEndMatches() { var hash = ASimpleHash.of("someDoc"); hash.setSecond("some text about nothing"); hash.setThird("some other text"); aSimpleHashRepository.save(hash); - var hashes = entityStream.of(ASimpleHash.class) - .filter(ASimpleHash$.SECOND.containing("about nothing")) + var hashes = entityStream.of(ASimpleHash.class).filter(ASimpleHash$.SECOND.containing("about nothing")) .collect(Collectors.toList()); assertEquals(1, hashes.size()); @@ -1584,15 +1710,15 @@ aSimpleHashRepository.delete(hash); } - @Test void testContainingPredicateOnFreeFormTextMiddleIncompleteWords() { + @Test + void testContainingPredicateOnFreeFormTextMiddleIncompleteWords() { var hash = ASimpleHash.of("someDoc"); hash.setSecond("some text about nothing"); hash.setThird("some other text"); aSimpleHashRepository.save(hash); - var hashes = entityStream.of(ASimpleHash.class) - .filter(ASimpleHash$.SECOND.containing("ext abou")) + var hashes = entityStream.of(ASimpleHash.class).filter(ASimpleHash$.SECOND.containing("ext abou")) .collect(Collectors.toList()); assertEquals(1, hashes.size()); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHighlightHashTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHighlightHashTest.java index 5c68c129..645bb22d 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHighlightHashTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamHighlightHashTest.java @@ -36,10 +36,10 @@ void loadText(@Value("classpath:/data/genesis.txt") File dataFile) throws IOExce /** * "FT.SEARCH" "com.redis.om.spring.annotations.hash.fixtures.TextIdx" "abraham isaac jacob" - * "LIMIT" "0" "10000" - * "HIGHLIGHT" "FIELDS" "1" "body" - * "SUMMARIZE" "FIELDS" "1" "body" - * "DIALECT" "1" + * "LIMIT" "0" "10000" + * "HIGHLIGHT" "FIELDS" "1" "body" + * "SUMMARIZE" "FIELDS" "1" "body" + * "DIALECT" "1" */ @Test void testHighlightSummarize() { @@ -56,15 +56,14 @@ void testHighlightSummarize() { assertAll( // () -> assertThat(result).contains("Abraham"), // () -> assertThat(result).contains("Isaac"), // - () -> assertThat(result).contains("Jacob") - ); + () -> assertThat(result).contains("Jacob")); } /** * "FT.SEARCH" "com.redis.om.spring.annotations.hash.fixtures.TextIdx" "abraham isaac jacob" - * "LIMIT" "0" "10000" - * "HIGHLIGHT" "FIELDS" "1" "body" "TAGS" "" "" - * "SUMMARIZE" "FIELDS" "1" "body" "DIALECT" "1" + * "LIMIT" "0" "10000" + * "HIGHLIGHT" "FIELDS" "1" "body" "TAGS" "" "" + * "SUMMARIZE" "FIELDS" "1" "body" "DIALECT" "1" */ @Test void testHighlightSummarizeWithCustomTags() { @@ -81,14 +80,13 @@ void testHighlightSummarizeWithCustomTags() { assertAll( // () -> assertThat(result).contains("Abraham"), // () -> assertThat(result).contains("Isaac"), // - () -> assertThat(result).contains("Jacob") - ); + () -> assertThat(result).contains("Jacob")); } /** * "FT.SEARCH" "com.redis.om.spring.annotations.hash.fixtures.TextIdx" "abraham isaac jacob" "LIMIT" "0" "10000" - * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "100" "LEN" "20" "SEPARATOR" "" - * "DIALECT" "1" + * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "100" "LEN" "20" "SEPARATOR" "" + * "DIALECT" "1" */ @Test void testHighlightSummarizeWithFragmentSizeAndSeparator() { @@ -99,14 +97,15 @@ void testHighlightSummarizeWithFragmentSizeAndSeparator() { .summarize(Text$.BODY, SummarizeParams.instance().fragments(100).separator("")) // .collect(Collectors.toList()); - List fragments = Arrays.stream(texts.stream().findFirst().map(Text::getBody).get().split("")).toList(); + List fragments = Arrays.stream(texts.stream().findFirst().map(Text::getBody).get().split("")) + .toList(); assertThat(fragments).hasSize(100); } /** * "FT.SEARCH" "com.redis.om.spring.annotations.hash.fixtures.TextIdx" "isaac" - * "LIMIT" "0" "10000" - * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "4" "LEN" "3" "SEPARATOR" "\r\n" "DIALECT" "1" + * "LIMIT" "0" "10000" + * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "4" "LEN" "3" "SEPARATOR" "\r\n" "DIALECT" "1" */ @Test void testHighlightSummarizeWithCustomSeparator() { @@ -118,14 +117,15 @@ void testHighlightSummarizeWithCustomSeparator() { .collect(Collectors.toList()); String result = texts.stream().findFirst().map(Text::getBody).get(); - assertThat(result).isEqualTo("name Isaac: and\r\nwith Isaac,\r\nIsaac. {21:4} And Abraham circumcised his son Isaac\r\nson Isaac was\r\n"); + assertThat(result).isEqualTo( + "name Isaac: and\r\nwith Isaac,\r\nIsaac. {21:4} And Abraham circumcised his son Isaac\r\nson Isaac was\r\n"); } /** * "FT.SEARCH" "com.redis.om.spring.annotations.hash.fixtures.TextIdx" "-blah" - * "LIMIT" "0" "10000" - * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "3" "LEN" "3" "SEPARATOR" "..." - * "DIALECT" "1" + * "LIMIT" "0" "10000" + * "SUMMARIZE" "FIELDS" "1" "body" "FRAGS" "3" "LEN" "3" "SEPARATOR" "..." + * "DIALECT" "1" */ @Test void testAttemptQueryWithNoCorrespondingMatchedTerm() { diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsPagingTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsPagingTest.java index 8e118ee9..5f280a75 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsPagingTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsPagingTest.java @@ -21,12 +21,16 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings({ "SpellCheckingInspection" }) class EntityStreamsAggregationsDocsPagingTest extends AbstractBaseDocumentTest { - @Autowired EntityStream entityStream; +@SuppressWarnings({ "SpellCheckingInspection" }) +class EntityStreamsAggregationsDocsPagingTest extends AbstractBaseDocumentTest { + @Autowired + EntityStream entityStream; - @Autowired GameRepository repository; + @Autowired + GameRepository repository; - @BeforeEach void beforeEach() throws IOException { + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (repository.count() == 0) { repository.bulkLoad("src/test/resources/data/games.json"); @@ -40,12 +44,10 @@ * "LIMIT" "0" "100" * */ - @Test void testLoadAllWithEntityReturn() { - List result = entityStream - .of(Game.class) // - .loadAll() - .limit(100) - .toList(Game.class); + @Test + void testLoadAllWithEntityReturn() { + List result = entityStream.of(Game.class) // + .loadAll().limit(100).toList(Game.class); assertThat(result).hasSize(100); } @@ -61,15 +63,13 @@ * "FT.CURSOR" "READ" "com.redis.om.spring.annotations.document.fixtures.GameIdx" "17284697" "45" * */ - @Test void testBasicExplicitCursorSession() { + @Test + void testBasicExplicitCursorSession() { int pageSize = 45; SearchStream searchStream = entityStream.of(Game.class); AggregationResult result = searchStream // - .cursor(pageSize, Duration.ofSeconds(300)) - .loadAll() - .limit(300) - .aggregate(); + .cursor(pageSize, Duration.ofSeconds(300)).loadAll().limit(300).aggregate(); // get the cursor id long cursorId = result.getCursorId(); @@ -86,15 +86,10 @@ } // assert the page counts - assertAll("page counts", - () -> assertEquals(6, pageCounts.size()), - () -> assertEquals(45, pageCounts.get(0)), - () -> assertEquals(45, pageCounts.get(1)), - () -> assertEquals(45, pageCounts.get(2)), - () -> assertEquals(45, pageCounts.get(3)), - () -> assertEquals(45, pageCounts.get(4)), - () -> assertEquals(30, pageCounts.get(5)) - ); + assertAll("page counts", () -> assertEquals(6, pageCounts.size()), () -> assertEquals(45, pageCounts.get(0)), + () -> assertEquals(45, pageCounts.get(1)), () -> assertEquals(45, pageCounts.get(2)), + () -> assertEquals(45, pageCounts.get(3)), () -> assertEquals(45, pageCounts.get(4)), + () -> assertEquals(30, pageCounts.get(5))); } /** @@ -108,14 +103,13 @@ * "FT.CURSOR" "READ" "com.redis.om.spring.annotations.document.fixtures.GameIdx" "17284697" "45" * */ - @Test void testManagedCursorSession() { + @Test + void testManagedCursorSession() { int pageSize = 45; SearchStream searchStream = entityStream.of(Game.class); Slice page = searchStream // - .loadAll() - .limit(300) - .toList(PageRequest.ofSize(pageSize), Game.class); + .loadAll().limit(300).toList(PageRequest.ofSize(pageSize), Game.class); // loop through the slices using the SearchStream.getSlice method passing the next page request // obtained from the current page @@ -128,16 +122,10 @@ } // assert the page counts - assertAll("page counts", - () -> assertEquals(pageSize, pageCounts.get(0)), - () -> assertEquals(pageSize, pageCounts.get(1)), - () -> assertEquals(pageSize, pageCounts.get(2)), - () -> assertEquals(pageSize, pageCounts.get(3)), - () -> assertEquals(pageSize, pageCounts.get(4)), - () -> assertEquals(pageSize, pageCounts.get(5)), - () -> assertEquals(30, pageCounts.get(6)) - ); + assertAll("page counts", () -> assertEquals(pageSize, pageCounts.get(0)), + () -> assertEquals(pageSize, pageCounts.get(1)), () -> assertEquals(pageSize, pageCounts.get(2)), + () -> assertEquals(pageSize, pageCounts.get(3)), () -> assertEquals(pageSize, pageCounts.get(4)), + () -> assertEquals(pageSize, pageCounts.get(5)), () -> assertEquals(30, pageCounts.get(6))); } - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsTest.java index 156aadd0..20740e18 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsDocsTest.java @@ -23,16 +23,24 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings({ "unchecked", "SpellCheckingInspection" }) class EntityStreamsAggregationsDocsTest extends AbstractBaseDocumentTest { - @Autowired EntityStream entityStream; - - @Autowired GameRepository repository; - @Autowired PersonRepository personRepository; - @Autowired PizzaOrderRepository pizzaOrderRepository; - @Autowired FilmRepository filmRepository; - @Autowired LanguageRepository languageRepository; - - @BeforeEach void beforeEach() throws IOException { +@SuppressWarnings({ "unchecked", "SpellCheckingInspection" }) +class EntityStreamsAggregationsDocsTest extends AbstractBaseDocumentTest { + @Autowired + EntityStream entityStream; + + @Autowired + GameRepository repository; + @Autowired + PersonRepository personRepository; + @Autowired + PizzaOrderRepository pizzaOrderRepository; + @Autowired + FilmRepository filmRepository; + @Autowired + LanguageRepository languageRepository; + + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (repository.count() == 0) { repository.bulkLoad("src/test/resources/data/games.json"); @@ -91,14 +99,22 @@ } // Create Sample Orders if (pizzaOrderRepository.count() == 0) { - var order0 = PizzaOrder.of(0, "Pepperoni", "small", 19, 10, Instant.parse("2021-03-13T08:14:30Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order1 = PizzaOrder.of(1, "Pepperoni", "medium", 20, 20, Instant.parse("2021-03-13T09:13:24Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order2 = PizzaOrder.of(2, "Pepperoni", "large", 21, 30, Instant.parse("2021-03-17T09:22:12Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order3 = PizzaOrder.of(3, "Cheese", "small", 12, 15, Instant.parse("2021-03-13T11:21:39.736Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order4 = PizzaOrder.of(4, "Cheese", "medium", 13, 50, Instant.parse("2022-01-12T21:23:13.331Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order5 = PizzaOrder.of(5, "Cheese", "large", 14, 10, Instant.parse("2022-01-12T05:08:13Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order6 = PizzaOrder.of(6, "Vegan", "small", 17, 10, Instant.parse("2021-01-13T05:08:13Z"), LocalDateTime.parse("2021-03-13T00:00:00.000")); - var order7 = PizzaOrder.of(7, "Vegan", "medium", 18, 10, Instant.parse("2021-01-13T05:10:13Z"), LocalDateTime.parse("2021-03-13T00:00:00.001")); + var order0 = PizzaOrder.of(0, "Pepperoni", "small", 19, 10, Instant.parse("2021-03-13T08:14:30Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order1 = PizzaOrder.of(1, "Pepperoni", "medium", 20, 20, Instant.parse("2021-03-13T09:13:24Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order2 = PizzaOrder.of(2, "Pepperoni", "large", 21, 30, Instant.parse("2021-03-17T09:22:12Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order3 = PizzaOrder.of(3, "Cheese", "small", 12, 15, Instant.parse("2021-03-13T11:21:39.736Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order4 = PizzaOrder.of(4, "Cheese", "medium", 13, 50, Instant.parse("2022-01-12T21:23:13.331Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order5 = PizzaOrder.of(5, "Cheese", "large", 14, 10, Instant.parse("2022-01-12T05:08:13Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order6 = PizzaOrder.of(6, "Vegan", "small", 17, 10, Instant.parse("2021-01-13T05:08:13Z"), + LocalDateTime.parse("2021-03-13T00:00:00.000")); + var order7 = PizzaOrder.of(7, "Vegan", "medium", 18, 10, Instant.parse("2021-01-13T05:10:13Z"), + LocalDateTime.parse("2021-03-13T00:00:00.001")); pizzaOrderRepository.saveAll(List.of(order0, order1, order2, order3, order4, order5, order6, order7)); } @@ -110,7 +126,7 @@ var es = Language.of(2, "Spanish"); es.setLastUpdate(LocalDate.of(2022, 1, 1)); - languageRepository.saveAll(List.of(en,es)); + languageRepository.saveAll(List.of(en, es)); var film1 = Film.of(1, "Breakfast with Morty"); film1.setReleaseYear(LocalDate.of(2020, 1, 1)); @@ -135,21 +151,21 @@ * "LIMIT" "0" "5" * */ - @Test void testCountAggregation() { + @Test + void testCountAggregation() { List> expectedData = List.of( // - Tuples.of("", 1498L), Tuples.of("Mad Catz", 43L), Tuples.of("Generic", 40L), Tuples.of("SteelSeries", 37L), - Tuples.of("Logitech", 35L) // + Tuples.of("", 1498L), Tuples.of("Mad Catz", 43L), Tuples.of("Generic", 40L), Tuples.of("SteelSeries", 37L), + Tuples.of("Logitech", 35L) // ); - List> countsPerBrand = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT).as("count") // - .sorted(Order.desc("@count")) // - .limit(5) // - .toList(String.class, Long.class); + List> countsPerBrand = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT).as("count") // + .sorted(Order.desc("@count")) // + .limit(5) // + .toList(String.class, Long.class); - assertThat(countsPerBrand).hasSize(5); + assertThat(countsPerBrand).hasSize(5); IntStream.range(0, expectedData.size() - 1).forEach(i -> { var actual = countsPerBrand.get(i); @@ -169,34 +185,34 @@ * "SORTBY" "2" "@minPrice" "DESC" * */ - @Test void testMinPrice() { - List> expectedData = List.of( // - Tuples.of("Genius", 1L, 88.54), Tuples.of("Logitech", 1L, 78.98), Tuples.of("Monster", 1L, 69.95), // - Tuples.of("Goliton", 1L, 15.69), Tuples.of("Lenmar", 1L, 15.41), Tuples.of("Oceantree(TM)", 1L, 12.29), // - Tuples.of("Oceantree", 4L, 11.39), Tuples.of("oooo", 1L, 10.11), Tuples.of("Case Logic", 1L, 9.99), // - Tuples.of("Neewer", 3L, 9.71) // - ); - - List> minPrices = entityStream - .of(Game.class) // - .filter("sony") // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT) // - .reduce(ReducerFunction.MIN, Game$.PRICE).as("minPrice") // - .sorted(Order.desc("@minPrice")) // - .toList(String.class, Long.class, Double.class); - - assertThat(minPrices).hasSize(27); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = minPrices.get(i); - var expected = expectedData.get(i); - - assertEquals(actual.getFirst(), expected.getFirst()); - assertEquals(actual.getSecond(), expected.getSecond()); - assertEquals(actual.getThird(), expected.getThird()); - }); - } + @Test + void testMinPrice() { + List> expectedData = List.of( // + Tuples.of("Genius", 1L, 88.54), Tuples.of("Logitech", 1L, 78.98), Tuples.of("Monster", 1L, 69.95), // + Tuples.of("Goliton", 1L, 15.69), Tuples.of("Lenmar", 1L, 15.41), Tuples.of("Oceantree(TM)", 1L, 12.29), // + Tuples.of("Oceantree", 4L, 11.39), Tuples.of("oooo", 1L, 10.11), Tuples.of("Case Logic", 1L, 9.99), // + Tuples.of("Neewer", 3L, 9.71) // + ); + + List> minPrices = entityStream.of(Game.class) // + .filter("sony") // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT) // + .reduce(ReducerFunction.MIN, Game$.PRICE).as("minPrice") // + .sorted(Order.desc("@minPrice")) // + .toList(String.class, Long.class, Double.class); + + assertThat(minPrices).hasSize(27); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = minPrices.get(i); + var expected = expectedData.get(i); + + assertEquals(actual.getFirst(), expected.getFirst()); + assertEquals(actual.getSecond(), expected.getSecond()); + assertEquals(actual.getThird(), expected.getThird()); + }); + } /** *
@@ -207,35 +223,35 @@
    *   "SORTBY" "2" "@maxPrice" "DESC"
    * 
*/ - @Test void testMaxPrice() { - List> expectedData = List.of( // - Tuples.of("Sony", 14L, 695.8), Tuples.of("", 119L, 303.59), Tuples.of("Genius", 1L, 88.54), // - Tuples.of("Logitech", 1L, 78.98), Tuples.of("Monster", 1L, 69.95), Tuples.of("Playstation", 2L, 33.6), // - Tuples.of("Neewer", 3L, 15.95), Tuples.of("Goliton", 1L, 15.69), Tuples.of("Lenmar", 1L, 15.41), // - Tuples.of("Oceantree", 4L, 12.45) // - ); - - List> maxPrices = entityStream - .of(Game.class) // - .filter("sony") // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT) // - .reduce(ReducerFunction.MAX, Game$.PRICE) // - .as("maxPrice") // - .sorted(Order.desc("@maxPrice")) // - .toList(String.class, Long.class, Double.class); - - assertThat(maxPrices).hasSize(27); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = maxPrices.get(i); - var expected = expectedData.get(i); - - assertEquals(actual.getFirst(), expected.getFirst()); - assertEquals(actual.getSecond(), expected.getSecond()); - assertEquals(actual.getThird(), expected.getThird()); - }); - } + @Test + void testMaxPrice() { + List> expectedData = List.of( // + Tuples.of("Sony", 14L, 695.8), Tuples.of("", 119L, 303.59), Tuples.of("Genius", 1L, 88.54), // + Tuples.of("Logitech", 1L, 78.98), Tuples.of("Monster", 1L, 69.95), Tuples.of("Playstation", 2L, 33.6), // + Tuples.of("Neewer", 3L, 15.95), Tuples.of("Goliton", 1L, 15.69), Tuples.of("Lenmar", 1L, 15.41), // + Tuples.of("Oceantree", 4L, 12.45) // + ); + + List> maxPrices = entityStream.of(Game.class) // + .filter("sony") // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT) // + .reduce(ReducerFunction.MAX, Game$.PRICE) // + .as("maxPrice") // + .sorted(Order.desc("@maxPrice")) // + .toList(String.class, Long.class, Double.class); + + assertThat(maxPrices).hasSize(27); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = maxPrices.get(i); + var expected = expectedData.get(i); + + assertEquals(actual.getFirst(), expected.getFirst()); + assertEquals(actual.getSecond(), expected.getSecond()); + assertEquals(actual.getThird(), expected.getThird()); + }); + } /** *
@@ -247,30 +263,30 @@
    *   "LIMIT" "0" "5"
    * 
*/ - @Test void testCountDistinctByBrandHardcodedLimit() { - List> expectedData = List.of( // - Tuples.of("", 1466L, 1498L), Tuples.of("Generic", 39L, 40L), Tuples.of("SteelSeries", 37L, 37L), // - Tuples.of("Mad Catz", 36L, 43L), Tuples.of("Logitech", 34L, 35L) // - ); - - List> distinctCounts = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT_DISTINCT, Game$.TITLE).as("count_distinct(title)") // - .reduce(ReducerFunction.COUNT) // - .sorted(Order.desc("@count_distinct(title)")) // - .limit(5) // - .toList(String.class, Long.class, Long.class); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = distinctCounts.get(i); - var expected = expectedData.get(i); - - assertEquals(actual.getFirst(), expected.getFirst()); - assertEquals(actual.getSecond(), expected.getSecond()); - assertEquals(actual.getThird(), expected.getThird()); - }); - } + @Test + void testCountDistinctByBrandHardcodedLimit() { + List> expectedData = List.of( // + Tuples.of("", 1466L, 1498L), Tuples.of("Generic", 39L, 40L), Tuples.of("SteelSeries", 37L, 37L), // + Tuples.of("Mad Catz", 36L, 43L), Tuples.of("Logitech", 34L, 35L) // + ); + + List> distinctCounts = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT_DISTINCT, Game$.TITLE).as("count_distinct(title)") // + .reduce(ReducerFunction.COUNT) // + .sorted(Order.desc("@count_distinct(title)")) // + .limit(5) // + .toList(String.class, Long.class, Long.class); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = distinctCounts.get(i); + var expected = expectedData.get(i); + + assertEquals(actual.getFirst(), expected.getFirst()); + assertEquals(actual.getSecond(), expected.getSecond()); + assertEquals(actual.getThird(), expected.getThird()); + }); + } /** *
@@ -284,29 +300,30 @@
    *   "SORTBY" "2" "@rowcount" "DESC" "MAX" "1"
    * 
*/ - @Test void testQuantiles() { - Hextuple expected = Tuples.of("", 19.22, 95.91, 144.96, 29.7105941255, 1498L); - - List> quantiles = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.50").as("q50") // - .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.90").as("q90") // - .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.95").as("q95") // - .reduce(ReducerFunction.AVG, Game$.PRICE) // - .reduce(ReducerFunction.COUNT).as("rowcount") // - .sorted(1, Order.desc("@rowcount")) // - .toList(String.class, Double.class, Double.class, Double.class, Double.class, Long.class); - - var actual = quantiles.get(0); - - assertEquals(expected.getFirst(), actual.getFirst()); - assertEquals(expected.getSecond(), actual.getSecond()); - assertEquals(expected.getThird(), actual.getThird()); - assertEquals(expected.getFourth(), actual.getFourth()); - assertEquals(expected.getFifth(), actual.getFifth()); - assertEquals(expected.getSixth(), actual.getSixth()); - } + @Test + void testQuantiles() { + Hextuple expected = Tuples.of("", 19.22, 95.91, 144.96, 29.7105941255, + 1498L); + + List> quantiles = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.50").as("q50") // + .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.90").as("q90") // + .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.95").as("q95") // + .reduce(ReducerFunction.AVG, Game$.PRICE) // + .reduce(ReducerFunction.COUNT).as("rowcount") // + .sorted(1, Order.desc("@rowcount")) // + .toList(String.class, Double.class, Double.class, Double.class, Double.class, Long.class); + + var actual = quantiles.get(0); + + assertEquals(expected.getFirst(), actual.getFirst()); + assertEquals(expected.getSecond(), actual.getSecond()); + assertEquals(expected.getThird(), actual.getThird()); + assertEquals(expected.getFourth(), actual.getFourth()); + assertEquals(expected.getFifth(), actual.getFifth()); + assertEquals(expected.getSixth(), actual.getSixth()); + } /** *
@@ -320,42 +337,42 @@
    *   "LIMIT" "0" "10"
    * 
*/ - @Test void testPriceStdDev() { - List> expectedData = List.of( // - Tuples.of("", 58.0682859441, 29.7105941255, 19.22, 1498L), // - Tuples.of("Mad Catz", 63.3626941047, 92.4065116279, 84.99, 43L), // - Tuples.of("Generic", 13.0528444292, 12.439, 6.69, 40L), // - Tuples.of("SteelSeries", 44.5684434629, 50.0302702703, 39.69, 37L), // - Tuples.of("Logitech", 48.016387201, 66.5488571429, 55.0, 35L), // - Tuples.of("Razer", 49.0284634692, 98.4069230769,80.49, 26L), // - Tuples.of("", 11.6611915524, 13.711, 10.0, 20L), // - Tuples.of("ROCCAT", 71.1336876222, 86.231, 58.72, 20L), // - Tuples.of("Sony", 195.848045202, 109.536428571,44.95, 14L), // - Tuples.of("Nintendo", 71.1987671314, 53.2792307692, 17.99, 13L) // - ); - - List> priceStdDev = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.STDDEV, Game$.PRICE).as("stddev(price)") // - .reduce(ReducerFunction.AVG, Game$.PRICE).as("avgPrice") // - .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.50").as("q50Price") // - .reduce(ReducerFunction.COUNT).as("rowcount") // - .sorted(Order.desc("@rowcount")) // - .limit(10) // - .toList(String.class, Double.class, Double.class, Double.class, Long.class); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = priceStdDev.get(i); - var expected = expectedData.get(i); - - assertEquals(expected.getFirst(), actual.getFirst()); - assertEquals(expected.getSecond(), actual.getSecond()); - assertEquals(expected.getThird(), actual.getThird()); - assertEquals(expected.getFourth(), actual.getFourth()); - assertEquals(expected.getFifth(), actual.getFifth()); - }); - } + @Test + void testPriceStdDev() { + List> expectedData = List.of( // + Tuples.of("", 58.0682859441, 29.7105941255, 19.22, 1498L), // + Tuples.of("Mad Catz", 63.3626941047, 92.4065116279, 84.99, 43L), // + Tuples.of("Generic", 13.0528444292, 12.439, 6.69, 40L), // + Tuples.of("SteelSeries", 44.5684434629, 50.0302702703, 39.69, 37L), // + Tuples.of("Logitech", 48.016387201, 66.5488571429, 55.0, 35L), // + Tuples.of("Razer", 49.0284634692, 98.4069230769, 80.49, 26L), // + Tuples.of("", 11.6611915524, 13.711, 10.0, 20L), // + Tuples.of("ROCCAT", 71.1336876222, 86.231, 58.72, 20L), // + Tuples.of("Sony", 195.848045202, 109.536428571, 44.95, 14L), // + Tuples.of("Nintendo", 71.1987671314, 53.2792307692, 17.99, 13L) // + ); + + List> priceStdDev = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.STDDEV, Game$.PRICE).as("stddev(price)") // + .reduce(ReducerFunction.AVG, Game$.PRICE).as("avgPrice") // + .reduce(ReducerFunction.QUANTILE, Game$.PRICE, "0.50").as("q50Price") // + .reduce(ReducerFunction.COUNT).as("rowcount") // + .sorted(Order.desc("@rowcount")) // + .limit(10) // + .toList(String.class, Double.class, Double.class, Double.class, Long.class); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = priceStdDev.get(i); + var expected = expectedData.get(i); + + assertEquals(expected.getFirst(), actual.getFirst()); + assertEquals(expected.getSecond(), actual.getSecond()); + assertEquals(expected.getThird(), actual.getThird()); + assertEquals(expected.getFourth(), actual.getFourth()); + assertEquals(expected.getFifth(), actual.getFifth()); + }); + } /** *
@@ -367,24 +384,24 @@
    *   "LIMIT" "0" "1"
    * 
*/ - @Test void testParseTime() { - Quad expected = Tuples.of("", 20L, "2018-01-31T16:45:44Z", 1517417144L); - - List> parseTime = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT).as("count") // - .apply("timefmt(1517417144)","dt") // - .apply("parsetime(@dt, \"%FT%TZ\")","parsed_dt") // - .limit(1) // - .toList(String.class, Long.class, String.class, Long.class); - - var actual = parseTime.get(0); - assertEquals(expected.getFirst(), actual.getFirst()); - assertEquals(expected.getSecond(), actual.getSecond()); - assertEquals(expected.getThird(), actual.getThird()); - assertEquals(expected.getFourth(), actual.getFourth()); - } + @Test + void testParseTime() { + Quad expected = Tuples.of("", 20L, "2018-01-31T16:45:44Z", 1517417144L); + + List> parseTime = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT).as("count") // + .apply("timefmt(1517417144)", "dt") // + .apply("parsetime(@dt, \"%FT%TZ\")", "parsed_dt") // + .limit(1) // + .toList(String.class, Long.class, String.class, Long.class); + + var actual = parseTime.get(0); + assertEquals(expected.getFirst(), actual.getFirst()); + assertEquals(expected.getSecond(), actual.getSecond()); + assertEquals(expected.getThird(), actual.getThird()); + assertEquals(expected.getFourth(), actual.getFourth()); + } /** *
@@ -395,18 +412,18 @@
    *   "SORTBY" "2" "@num" "DESC" "MAX" "10"
    * 
*/ - @Test void testRandomSample() { - List>> randomSample = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT).as("num") // - .reduce(ReducerFunction.RANDOM_SAMPLE, Game$.PRICE, "10").as("sample") // - .sorted(10, Order.desc("@num")) // - .limit(10) // - .toList(String.class, Long.class, List.class); - - randomSample.forEach(row -> assertThat(row.getThird()).hasSize(10)); - } + @Test + void testRandomSample() { + List>> randomSample = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT).as("num") // + .reduce(ReducerFunction.RANDOM_SAMPLE, Game$.PRICE, "10").as("sample") // + .sorted(10, Order.desc("@num")) // + .limit(10) // + .toList(String.class, Long.class, List.class); + + randomSample.forEach(row -> assertThat(row.getThird()).hasSize(10)); + } /** *
@@ -424,38 +441,39 @@
    *   "LIMIT" "0" "1"
    * 
*/ - @Test void testTimeFunctions() { - Decuple expected = Tuples.of( - 1517417144L, "2018-01-31T16:45:44Z", 1517356800L, 1517414400L, 1517417100L, 1514764800L, 3L, 31L, 30L, 2018L - ); - - List> parseTime = entityStream - .of(Game.class) // - .apply("1517417144", "dt") // - .apply("timefmt(@dt)", "timefmt") // - .apply("day(@dt)", "day") // - .apply("hour(@dt)", "hour") // - .apply("minute(@dt)", "minute") // - .apply("month(@dt)", "month") // - .apply("dayofweek(@dt)", "dayofweek") // - .apply("dayofmonth(@dt)", "dayofmonth") // - .apply("dayofyear(@dt)", "dayofyear") // - .apply("year(@dt)", "year") // - .limit(1) // - .toList(Long.class, String.class, Long.class, Long.class, Long.class, Long.class, Long.class, Long.class, Long.class, Long.class); - - var actual = parseTime.get(0); - assertEquals(expected.getFirst(), actual.getFirst()); - assertEquals(expected.getSecond(), actual.getSecond()); - assertEquals(expected.getThird(), actual.getThird()); - assertEquals(expected.getFourth(), actual.getFourth()); - assertEquals(expected.getFifth(), actual.getFifth()); - assertEquals(expected.getSixth(), actual.getSixth()); - assertEquals(expected.getSeventh(), actual.getSeventh()); - assertEquals(expected.getEighth(), actual.getEighth()); - assertEquals(expected.getNinth(), actual.getNinth()); - assertEquals(expected.getTenth(), actual.getTenth()); - } + @Test + void testTimeFunctions() { + Decuple expected = Tuples.of(1517417144L, + "2018-01-31T16:45:44Z", 1517356800L, 1517414400L, 1517417100L, 1514764800L, 3L, 31L, 30L, 2018L); + + List> parseTime = entityStream.of( + Game.class) // + .apply("1517417144", "dt") // + .apply("timefmt(@dt)", "timefmt") // + .apply("day(@dt)", "day") // + .apply("hour(@dt)", "hour") // + .apply("minute(@dt)", "minute") // + .apply("month(@dt)", "month") // + .apply("dayofweek(@dt)", "dayofweek") // + .apply("dayofmonth(@dt)", "dayofmonth") // + .apply("dayofyear(@dt)", "dayofyear") // + .apply("year(@dt)", "year") // + .limit(1) // + .toList(Long.class, String.class, Long.class, Long.class, Long.class, Long.class, Long.class, Long.class, + Long.class, Long.class); + + var actual = parseTime.get(0); + assertEquals(expected.getFirst(), actual.getFirst()); + assertEquals(expected.getSecond(), actual.getSecond()); + assertEquals(expected.getThird(), actual.getThird()); + assertEquals(expected.getFourth(), actual.getFourth()); + assertEquals(expected.getFifth(), actual.getFifth()); + assertEquals(expected.getSixth(), actual.getSixth()); + assertEquals(expected.getSeventh(), actual.getSeventh()); + assertEquals(expected.getEighth(), actual.getEighth()); + assertEquals(expected.getNinth(), actual.getNinth()); + assertEquals(expected.getTenth(), actual.getTenth()); + } /** *
@@ -466,37 +484,35 @@
    *   "SORTBY" "2" "@num" "DESC" "MAX" "10"
    * 
*/ - @Test void testStringFormat() { - List expectedData = List.of( // - "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg|Hellermann Tyton|Mark|4.95", // - "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader|(null)|Mark|51.79", - "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology|(null)|Mark|19.66", - "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC|Mad Catz|Mark|193.26", // - "iConcepts THE SHOCK MASTER For Use With PC|(null)|Mark|9.99", // - "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel|Mad Catz|Mark|47.02", // - "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)|(null)|Mark|34.98", - "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod" - + " Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc|iiMash®|Mark|35.98", - "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE|Meco|Mark|3.99", // - "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device|(null)|Mark|14.99" - ); - - List> stringFormat = entityStream - .of(Game.class) // - .groupBy(Game$.TITLE, Game$.BRAND) // - .reduce(ReducerFunction.COUNT) // - .reduce(ReducerFunction.MAX, Game$.PRICE).as("price") // - .apply("format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", "titleBrand") // - .limit(10) // - .toList(String.class, String.class, Long.class, Double.class, String.class); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = stringFormat.get(i); - var expected = expectedData.get(i); - - assertEquals(expected, actual.getFifth()); - }); - } + @Test + void testStringFormat() { + List expectedData = List.of( // + "Standard Single Gang 4 Port Faceplate, ABS 94V-0, Black, 1/pkg|Hellermann Tyton|Mark|4.95", // + "250G HDD Hard Disk Drive For Microsoft Xbox 360 E Slim with USB 2.0 AGPtek All-in-One Card Reader|(null)|Mark|51.79", + "Portable Emergency AA Battery Charger Extender suitable for the Sony PSP - with Gomadic Brand TipExchange Technology|(null)|Mark|19.66", + "Mad Catz S.T.R.I.K.E.5 Gaming Keyboard for PC|Mad Catz|Mark|193.26", // + "iConcepts THE SHOCK MASTER For Use With PC|(null)|Mark|9.99", // + "Saitek CES432110002/06/1 Pro Flight Cessna Trim Wheel|Mad Catz|Mark|47.02", // + "Noppoo Choc Mini 84 USB NKRO Mechanical Gaming Keyboard Cherry MX Switches (BLUE switch + Black body + POM key cap)|(null)|Mark|34.98", + "iiMash® Ipega Universal Wireless Bluetooth 3.0 Game Controller Gamepad Joypad for Apple Ios Iphone 5 4 4s Ipad 4 3 2 New Mini Ipod" + " Android Phone HTC One X Samsung Galaxy S3 2 Note 2 N7100 N8000 Tablet Google Nexus 7" 10" Pc|iiMash®|Mark|35.98", + "16 in 1 Plastic Game Card Case Holder Box For Nintendo 3DS DSi DSi XL DS LITE|Meco|Mark|3.99", // + "Apocalypse Red Design Protective Decal Skin Sticker (High Gloss Coating) for Nintendo DSi XL Game Device|(null)|Mark|14.99"); + + List> stringFormat = entityStream.of(Game.class) // + .groupBy(Game$.TITLE, Game$.BRAND) // + .reduce(ReducerFunction.COUNT) // + .reduce(ReducerFunction.MAX, Game$.PRICE).as("price") // + .apply("format(\"%s|%s|%s|%s\", @title, @brand, \"Mark\", @price)", "titleBrand") // + .limit(10) // + .toList(String.class, String.class, Long.class, Double.class, String.class); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = stringFormat.get(i); + var expected = expectedData.get(i); + + assertEquals(expected, actual.getFifth()); + }); + } /** *
@@ -508,33 +524,33 @@
    *   "LIMIT" "0" "5"
    * 
*/ - @Test void testSumPrice() { - List> expectedData = List.of( // - Tuples.of("", 1498L, 44506.47), // - Tuples.of("Mad Catz", 43L, 3973.48), // - Tuples.of("Razer", 26L, 2558.58), // - Tuples.of("Logitech", 35L, 2329.21), // - Tuples.of("SteelSeries",37L, 1851.12) // - ); - - List> sumPrice = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT).as("count") // - .reduce(ReducerFunction.SUM, Game$.PRICE).as("sum(price)") // - .sorted(Order.desc("@sum(price)")) // - .limit(5) // - .toList(String.class, Long.class, Double.class); - - IntStream.range(0, expectedData.size() - 1).forEach(i -> { - var actual = sumPrice.get(i); - var expected = expectedData.get(i); - - assertEquals(expected.getFirst(), actual.getFirst()); - assertEquals(expected.getSecond(), actual.getSecond()); - assertEquals(expected.getThird(), actual.getThird()); - }); - } + @Test + void testSumPrice() { + List> expectedData = List.of( // + Tuples.of("", 1498L, 44506.47), // + Tuples.of("Mad Catz", 43L, 3973.48), // + Tuples.of("Razer", 26L, 2558.58), // + Tuples.of("Logitech", 35L, 2329.21), // + Tuples.of("SteelSeries", 37L, 1851.12) // + ); + + List> sumPrice = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT).as("count") // + .reduce(ReducerFunction.SUM, Game$.PRICE).as("sum(price)") // + .sorted(Order.desc("@sum(price)")) // + .limit(5) // + .toList(String.class, Long.class, Double.class); + + IntStream.range(0, expectedData.size() - 1).forEach(i -> { + var actual = sumPrice.get(i); + var expected = expectedData.get(i); + + assertEquals(expected.getFirst(), actual.getFirst()); + assertEquals(expected.getSecond(), actual.getSecond()); + assertEquals(expected.getThird(), actual.getThird()); + }); + } /** *
@@ -545,20 +561,19 @@
    *   "FILTER" "@count > 2 && @brand != \"\""
    * 
*/ - @Test void testFilters() { - List> filtered = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT).as("count") // - .filter("@count < 5") // - .filter("@count > 2 && @brand != \"\"") - .toList(String.class, Long.class); - - assertAll( // - () -> assertThat(filtered).isNotEmpty(), // - () -> assertThat(filtered).allSatisfy(e -> assertThat(e.getSecond()).isGreaterThan(2).isLessThan(5)) // - ); - } + @Test + void testFilters() { + List> filtered = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT).as("count") // + .filter("@count < 5") // + .filter("@count > 2 && @brand != \"\"").toList(String.class, Long.class); + + assertAll( // + () -> assertThat(filtered).isNotEmpty(), // + () -> assertThat(filtered).allSatisfy(e -> assertThat(e.getSecond()).isGreaterThan(2).isLessThan(5)) // + ); + } /** *
@@ -570,18 +585,18 @@
    *   "LIMIT" "0" "5"
    * 
*/ - @Test void testToList() { - List>> toList = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.COUNT_DISTINCT, Game$.PRICE).as("count") // - .reduce(ReducerFunction.TOLIST, Game$.PRICE).as("prices") // - .sorted(Order.desc("@count")) // - .limit(5) // - .toList(String.class, Long.class, List.class); - - assertThat(toList).isNotEmpty().allSatisfy(e -> assertThat(e.getThird()).hasSize(Math.toIntExact(e.getSecond()))); - } + @Test + void testToList() { + List>> toList = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.COUNT_DISTINCT, Game$.PRICE).as("count") // + .reduce(ReducerFunction.TOLIST, Game$.PRICE).as("prices") // + .sorted(Order.desc("@count")) // + .limit(5) // + .toList(String.class, Long.class, List.class); + + assertThat(toList).isNotEmpty().allSatisfy(e -> assertThat(e.getThird()).hasSize(Math.toIntExact(e.getSecond()))); + } /** *
@@ -592,27 +607,27 @@
    *   "SORTBY" "4" "@price" "ASC" "@brand" "DESC" "MAX" "10"
    * 
*/ - @Test void testSortByMany() { + @Test + void testSortByMany() { List> expectedData = List.of( // - Tuples.of("yooZoo", 0L), // - Tuples.of("oooo", 0L), // - Tuples.of("iWin", 0L), // - Tuples.of("Zalman", 0L), // - Tuples.of("ZPS", 0L), // - Tuples.of("White Label", 0L), // - Tuples.of("Stinky", 0L), // - Tuples.of("Polaroid", 0L), // - Tuples.of("Plantronics", 0L), // - Tuples.of("Ozone", 0L) // + Tuples.of("yooZoo", 0L), // + Tuples.of("oooo", 0L), // + Tuples.of("iWin", 0L), // + Tuples.of("Zalman", 0L), // + Tuples.of("ZPS", 0L), // + Tuples.of("White Label", 0L), // + Tuples.of("Stinky", 0L), // + Tuples.of("Polaroid", 0L), // + Tuples.of("Plantronics", 0L), // + Tuples.of("Ozone", 0L) // ); - List> sumPrice = entityStream - .of(Game.class) // - .groupBy(Game$.BRAND) // - .reduce(ReducerFunction.SUM, Game$.PRICE).as("price") // - .apply("(@price % 10)", "price") // - .sorted(10, Order.asc("@price"), Order.desc("@brand")) // - .toList(String.class, Long.class); + List> sumPrice = entityStream.of(Game.class) // + .groupBy(Game$.BRAND) // + .reduce(ReducerFunction.SUM, Game$.PRICE).as("price") // + .apply("(@price % 10)", "price") // + .sorted(10, Order.asc("@price"), Order.desc("@brand")) // + .toList(String.class, Long.class); IntStream.range(0, expectedData.size() - 1).forEach(i -> { var actual = sumPrice.get(i); @@ -631,18 +646,18 @@ * "LIMIT" "0" "2" * */ - @Test void testLoadWithSort() { + @Test + void testLoadWithSort() { List> expectedData = List.of( // - Tuples.of("MADCATZ 8241 DVD 2 Wireless Remote for PlayStation 2", 0.01), // - Tuples.of("INNOVATIONS 7-38012-24010-6 NES AC Adapter (Discontinued by Manufacturer)", 0.01) // + Tuples.of("MADCATZ 8241 DVD 2 Wireless Remote for PlayStation 2", 0.01), // + Tuples.of("INNOVATIONS 7-38012-24010-6 NES AC Adapter (Discontinued by Manufacturer)", 0.01) // ); - List> sumPrice = entityStream - .of(Game.class) // - .load(Game$.TITLE) // - .sorted(Game$.PRICE.asc()) // - .limit(2) // - .toList(String.class, Double.class); + List> sumPrice = entityStream.of(Game.class) // + .load(Game$.TITLE) // + .sorted(Game$.PRICE.asc()) // + .limit(2) // + .toList(String.class, Double.class); IntStream.range(0, expectedData.size() - 1).forEach(i -> { var actual = sumPrice.get(i); @@ -661,19 +676,19 @@ * "MAX" "4" * */ - @Test void testLoadWithDocId() { + @Test + void testLoadWithDocId() { List> expectedData = List.of( // - Tuples.of("", 759.12, "games:B00006JJIC"), // - Tuples.of("Sony", 695.8, "games:B000F6W1AG"), // - Tuples.of("", 599.99, "games:B00002JXBD"), // - Tuples.of("Matias", 759.12, "games:B00006IZIL") // + Tuples.of("", 759.12, "games:B00006JJIC"), // + Tuples.of("Sony", 695.8, "games:B000F6W1AG"), // + Tuples.of("", 599.99, "games:B00002JXBD"), // + Tuples.of("Matias", 759.12, "games:B00006IZIL") // ); - List> loadWithDocId = entityStream - .of(Game.class) // - .load(Game$.BRAND, Game$.PRICE, Game$._KEY) // - .sorted(4, Game$.PRICE.desc()) // - .toList(String.class, Double.class, String.class); + List> loadWithDocId = entityStream.of(Game.class) // + .load(Game$.BRAND, Game$.PRICE, Game$._KEY) // + .sorted(4, Game$.PRICE.desc()) // + .toList(String.class, Double.class, String.class); IntStream.range(0, expectedData.size() - 1).forEach(i -> { var actual = loadWithDocId.get(i); @@ -685,50 +700,48 @@ }); } - @Test void testEntityStreamMin() { + @Test + void testEntityStreamMin() { // The long way... List> minAggregation = entityStream.of(Game.class) // - .load(Game$._KEY) // - .sorted(Game$.PRICE.asc()) - .limit(1) // - .toList(String.class, Double.class); + .load(Game$._KEY) // + .sorted(Game$.PRICE.asc()).limit(1) // + .toList(String.class, Double.class); - Pair expected = minAggregation.get(0); + Pair expected = minAggregation.get(0); // The short way... Optional actual = entityStream.of(Game.class).min(Game$.PRICE); assertThat(actual) // - .isPresent() // - .map(Game::getAsin) // - .hasValue(expected.getFirst().split(":")[1]); + .isPresent() // + .map(Game::getAsin) // + .hasValue(expected.getFirst().split(":")[1]); assertThat(actual) // - .map(Game::getPrice) - .hasValue(expected.getSecond()); + .map(Game::getPrice).hasValue(expected.getSecond()); } - @Test void testEntityStreamMax() { + @Test + void testEntityStreamMax() { // The long way... List> maxAggregation = entityStream.of(Game.class) // - .load(Game$._KEY) // - .sorted(Game$.PRICE.desc()) - .limit(1) // - .toList(String.class, Double.class); + .load(Game$._KEY) // + .sorted(Game$.PRICE.desc()).limit(1) // + .toList(String.class, Double.class); - Pair expected = maxAggregation.get(0); + Pair expected = maxAggregation.get(0); // The short way... Optional actual = entityStream.of(Game.class).max(Game$.PRICE); assertThat(actual) // - .isPresent() // - .map(Game::getAsin) // - .hasValue(expected.getFirst().split(":")[1]); + .isPresent() // + .map(Game::getAsin) // + .hasValue(expected.getFirst().split(":")[1]); assertThat(actual) // - .map(Game::getPrice) - .hasValue(expected.getSecond()); + .map(Game::getPrice).hasValue(expected.getSecond()); } // @@ -737,90 +750,88 @@ /** * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PersonIdx" "*" - * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" - * "GROUPBY" "1" "@departmentNumber" - * "REDUCE" "SUM" "1" "AdjustedSales" "AS" "AdjustedSales_SUM" - * "SORTBY" "2" "@AdjustedSales_SUM" "DESC" + * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" + * "GROUPBY" "1" "@departmentNumber" + * "REDUCE" "SUM" "1" "AdjustedSales" "AS" "AdjustedSales_SUM" + * "SORTBY" "2" "@AdjustedSales_SUM" "DESC" */ - @Test void testGetDepartmentBySales() { + @Test + void testGetDepartmentBySales() { var stream = entityStream.of(Person.class); - List> departments = stream // - .apply("@sales * @salesAdjustment", "AdjustedSales") - .groupBy(Person$.DEPARTMENT_NUMBER) // - .reduce(ReducerFunction.SUM, "AdjustedSales").as("AdjustedSales_SUM") // - .sorted(Order.desc("@AdjustedSales_SUM")) // - .toList(Integer.class, Double.class); - - assertAll( - () -> assertThat(departments).map(Pair::getFirst).containsExactly(1, 4, 3, 2), - () -> assertThat(departments).map(Pair::getSecond).containsExactly(1200000.0, 1120000.0, 600000.0, 245000.0) - ); + List> departments = stream // + .apply("@sales * @salesAdjustment", "AdjustedSales").groupBy(Person$.DEPARTMENT_NUMBER) // + .reduce(ReducerFunction.SUM, "AdjustedSales").as("AdjustedSales_SUM") // + .sorted(Order.desc("@AdjustedSales_SUM")) // + .toList(Integer.class, Double.class); + + assertAll(() -> assertThat(departments).map(Pair::getFirst).containsExactly(1, 4, 3, 2), + () -> assertThat(departments).map(Pair::getSecond).containsExactly(1200000.0, 1120000.0, 600000.0, 245000.0)); } /** * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PersonIdx" "*" - * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" - * "SORTBY" "2" "@AdjustedSales" "DESC" + * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" + * "SORTBY" "2" "@AdjustedSales" "DESC" */ - @Test void testGetHandicappedSales() { + @Test + void testGetHandicappedSales() { var stream = entityStream.of(Person.class); List> employees = stream // - .apply("@sales * @salesAdjustment", "AdjustedSales") - .sorted(Order.desc("@AdjustedSales")) // - .toList(Double.class); + .apply("@sales * @salesAdjustment", "AdjustedSales").sorted(Order.desc("@AdjustedSales")) // + .toList(Double.class); assertThat(employees).map(Single::getFirst).isSortedAccordingTo(Comparator.reverseOrder()); } /** * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PersonIdx" "*" - * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" - * "GROUPBY" "0" - * "REDUCE" "STDDEV" "1" "@AdjustedSales" "AS" "stddev" + * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" + * "GROUPBY" "0" + * "REDUCE" "STDDEV" "1" "@AdjustedSales" "AS" "stddev" */ @Test void testGetAdjustedSalesStandardDeviation() { var stream = entityStream.of(Person.class); List> stddev = stream // - .apply("@sales * @salesAdjustment", "AdjustedSales") // - .groupBy() // - .reduce(ReducerFunction.STDDEV, "@AdjustedSales").as("stddev") // - .toList(Double.class); + .apply("@sales * @salesAdjustment", "AdjustedSales") // + .groupBy() // + .reduce(ReducerFunction.STDDEV, "@AdjustedSales").as("stddev") // + .toList(Double.class); assertThat(stddev).first().extracting("first").isEqualTo(358018.854252); } /** * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PersonIdx" "*" - * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" - * "GROUPBY" "0" - * "REDUCE" "STDDEV" "1" "@AdjustedSales" "AS" "stddev" + * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" + * "GROUPBY" "0" + * "REDUCE" "STDDEV" "1" "@AdjustedSales" "AS" "stddev" */ @Test void testGetAdjustedSalesStandardDeviationImplicitGroupByZero() { var stream = entityStream.of(Person.class); List> stddev = stream // - .apply("@sales * @salesAdjustment", "AdjustedSales") // - .reduce(ReducerFunction.STDDEV, "@AdjustedSales").as("stddev") // - .toList(Double.class); + .apply("@sales * @salesAdjustment", "AdjustedSales") // + .reduce(ReducerFunction.STDDEV, "@AdjustedSales").as("stddev") // + .toList(Double.class); assertThat(stddev).first().extracting("first").isEqualTo(358018.854252); } /** * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PersonIdx" "*" - * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" - * "GROUPBY" "0" - * "REDUCE" "AVG" "1" "@AdjustedSales" "AS" "avg" + * "APPLY" "@sales * @salesAdjustment" "AS" "AdjustedSales" + * "GROUPBY" "0" + * "REDUCE" "AVG" "1" "@AdjustedSales" "AS" "avg" */ @Test void testGetAverageAdjustedSales() { var stream = entityStream.of(Person.class); List> stddev = stream // - .apply("@sales * @salesAdjustment", "AdjustedSales") // - .reduce(ReducerFunction.AVG, "@AdjustedSales").as("avg") // - .toList(Double.class); + .apply("@sales * @salesAdjustment", "AdjustedSales") // + .reduce(ReducerFunction.AVG, "@AdjustedSales").as("avg") // + .toList(Double.class); assertThat(stddev).first().extracting("first").isEqualTo(527500.0); } @@ -837,26 +848,21 @@ void testGetAverageAdjustedSales() { *

* In Mongo: * db.orders.aggregate( [ - * // Stage 1: Filter pizza order documents by pizza size - * { $match: { size: "medium" } }, - * // Stage 2: Group remaining documents by pizza name and calculate total quantity - * { $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } } } + * // Stage 1: Filter pizza order documents by pizza size + * { $match: { size: "medium" } }, + * // Stage 2: Group remaining documents by pizza name and calculate total quantity + * { $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } } } * ] ) */ @Test void testCalculateTotalOrderQuantity() { var stream = entityStream.of(PizzaOrder.class); - List> totalOrderQuanties = stream // - .filter(PizzaOrder$.SIZE.eq("medium")) - .groupBy(PizzaOrder$.NAME) - .reduce(ReducerFunction.SUM, PizzaOrder$.QUANTITY) - .as("sum") - .toList(String.class, Integer.class); - - assertAll( - () -> assertThat(totalOrderQuanties).map(Pair::getFirst).containsExactly("Pepperoni", "Cheese", "Vegan"), - () -> assertThat(totalOrderQuanties).map(Pair::getSecond).containsExactly(20, 50, 10) - ); + List> totalOrderQuanties = stream // + .filter(PizzaOrder$.SIZE.eq("medium")).groupBy(PizzaOrder$.NAME).reduce(ReducerFunction.SUM, PizzaOrder$.QUANTITY) + .as("sum").toList(String.class, Integer.class); + + assertAll(() -> assertThat(totalOrderQuanties).map(Pair::getFirst).containsExactly("Pepperoni", "Cheese", "Vegan"), + () -> assertThat(totalOrderQuanties).map(Pair::getSecond).containsExactly(20, 50, 10)); } /** @@ -865,46 +871,45 @@ void testCalculateTotalOrderQuantity() { *

* In Mongo: * db.orders.aggregate( [ - * // Stage 1: Filter pizza order documents by date range - * { $match: { "date": { $gte: new ISODate( "2020-01-30" ), $lt: new ISODate( "2022-01-30" ) } } }, - * // Stage 2: Group remaining documents by date and calculate results - * { $group: { - * _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }, - * totalOrderValue: { $sum: { $multiply: [ "$price", "$quantity" ] } }, - * averageOrderQuantity: { $avg: "$quantity" } } }, - * // Stage 3: Sort documents by totalOrderValue in descending order - * { $sort: { totalOrderValue: -1 }} - * ] ) + * // Stage 1: Filter pizza order documents by date range + * { $match: { "date": { $gte: new ISODate( "2020-01-30" ), $lt: new ISODate( "2022-01-30" ) } } }, + * // Stage 2: Group remaining documents by date and calculate results + * { $group: { + * _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }, + * totalOrderValue: { $sum: { $multiply: [ "$price", "$quantity" ] } }, + * averageOrderQuantity: { $avg: "$quantity" } } }, + * // Stage 3: Sort documents by totalOrderValue in descending order + * { $sort: { totalOrderValue: -1 }} + * ] ) *

* Equivalent RediSearch Aggregation: *

* "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.PizzaOrderIdx" - * "(( @date:[1.5803424E9 inf]) @date:[-inf (1.6435008E9])" - * "APPLY" "timefmt(@date, '%Y-%m-%d') " "AS" "_id" - * "APPLY" "@price * @quantity" "AS" "total" - * "GROUPBY" "1" "@_id" - * "REDUCE" "SUM" "1" "@total" "AS" "totalOrderValue" - * "REDUCE" "AVG" "1" "@quantity" "AS" "averageOrderQuantity" + * "(( @date:[1.5803424E9 inf]) @date:[-inf (1.6435008E9])" + * "APPLY" "timefmt(@date, '%Y-%m-%d') " "AS" "_id" + * "APPLY" "@price * @quantity" "AS" "total" + * "GROUPBY" "1" "@_id" + * "REDUCE" "SUM" "1" "@total" "AS" "totalOrderValue" + * "REDUCE" "AVG" "1" "@quantity" "AS" "averageOrderQuantity" */ @Test void testCalculateTotalOrderValueandAverageOrderQuantity() { var stream = entityStream.of(PizzaOrder.class); - List> totalOrderQuanties = stream // - .filter(PizzaOrder$.DATE.onOrAfter(Instant.parse("2020-01-30T00:00:00.00Z"))) // - .filter(PizzaOrder$.DATE.before(Instant.parse("2022-01-30T00:00:00.00Z"))) // - .apply("timefmt(@date / 1000, '%Y-%m-%d') ", "_id") // - .apply("@price * @quantity", "total") // - .groupBy(Alias.of("_id")) // - .reduce(ReducerFunction.SUM, "@total").as("totalOrderValue") // - .reduce(ReducerFunction.AVG, "@quantity").as("averageOrderQuantity") // - .sorted(Order.desc("@totalOrderValue")) // - .toList(String.class, Double.class, Integer.class); - - assertAll( - () -> assertThat(totalOrderQuanties).map(Triple::getFirst).containsExactly("2022-01-12", "2021-03-13", "2021-03-17", "2021-01-13"), - () -> assertThat(totalOrderQuanties).map(Triple::getSecond).containsExactly(790.0, 770.0, 630.0, 350.0), - () -> assertThat(totalOrderQuanties).map(Triple::getThird).containsExactly(30, 15, 30, 10) - ); + List> totalOrderQuanties = stream // + .filter(PizzaOrder$.DATE.onOrAfter(Instant.parse("2020-01-30T00:00:00.00Z"))) // + .filter(PizzaOrder$.DATE.before(Instant.parse("2022-01-30T00:00:00.00Z"))) // + .apply("timefmt(@date / 1000, '%Y-%m-%d') ", "_id") // + .apply("@price * @quantity", "total") // + .groupBy(Alias.of("_id")) // + .reduce(ReducerFunction.SUM, "@total").as("totalOrderValue") // + .reduce(ReducerFunction.AVG, "@quantity").as("averageOrderQuantity") // + .sorted(Order.desc("@totalOrderValue")) // + .toList(String.class, Double.class, Integer.class); + + assertAll(() -> assertThat(totalOrderQuanties).map(Triple::getFirst) + .containsExactly("2022-01-12", "2021-03-13", "2021-03-17", "2021-01-13"), + () -> assertThat(totalOrderQuanties).map(Triple::getSecond).containsExactly(790.0, 770.0, 630.0, 350.0), + () -> assertThat(totalOrderQuanties).map(Triple::getThird).containsExactly(30, 15, 30, 10)); } /** @@ -912,30 +917,19 @@ void testCalculateTotalOrderValueandAverageOrderQuantity() { */ @Test void testSearchBetweenDates() { - List> byCreated = entityStream.of(PizzaOrder.class) - .filter(PizzaOrder$.CREATED.between( - LocalDateTime.parse("2021-03-13T00:00:00.000000"), - LocalDateTime.parse("2021-03-13T00:00:00.000000") - )) - .load(PizzaOrder$.ID) - .sorted(PizzaOrder$.ID.asc()) - .toList(Integer.class); + List> byCreated = entityStream.of(PizzaOrder.class).filter( + PizzaOrder$.CREATED.between(LocalDateTime.parse("2021-03-13T00:00:00.000000"), + LocalDateTime.parse("2021-03-13T00:00:00.000000"))).load(PizzaOrder$.ID).sorted(PizzaOrder$.ID.asc()) + .toList(Integer.class); List> byDate = entityStream.of(PizzaOrder.class) - .filter(PizzaOrder$.DATE.between( - Instant.parse("2021-01-12T05:08:13Z"), - Instant.parse("2021-03-30T00:00:00.00Z") - )) - .load(PizzaOrder$.ID) - .sorted(PizzaOrder$.ID.asc()) - .toList(Integer.class); - - assertAll( - () -> assertEquals(7, byCreated.size()), - () -> assertThat(byCreated).map(Single::getFirst).containsAll(List.of(0,1,2,3,4,5,6)), - () -> assertEquals(6, byDate.size()), - () -> assertThat(byDate).map(Single::getFirst).containsAll(List.of(0,1,2,3,6,7)) - ); + .filter(PizzaOrder$.DATE.between(Instant.parse("2021-01-12T05:08:13Z"), Instant.parse("2021-03-30T00:00:00.00Z"))) + .load(PizzaOrder$.ID).sorted(PizzaOrder$.ID.asc()).toList(Integer.class); + + assertAll(() -> assertEquals(7, byCreated.size()), + () -> assertThat(byCreated).map(Single::getFirst).containsAll(List.of(0, 1, 2, 3, 4, 5, 6)), + () -> assertEquals(6, byDate.size()), + () -> assertThat(byDate).map(Single::getFirst).containsAll(List.of(0, 1, 2, 3, 6, 7))); } @Test diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsHashPagingTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsHashPagingTest.java index 1131dd9d..0ae6b9e1 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsHashPagingTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsAggregationsHashPagingTest.java @@ -26,15 +26,19 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings({ "SpellCheckingInspection" }) class EntityStreamsAggregationsHashPagingTest - extends AbstractBaseEnhancedRedisTest { - @Autowired EntityStream entityStream; +@SuppressWarnings({ "SpellCheckingInspection" }) +class EntityStreamsAggregationsHashPagingTest extends AbstractBaseEnhancedRedisTest { + @Autowired + EntityStream entityStream; - @Autowired GameRepository repository; + @Autowired + GameRepository repository; - @Autowired Gson gson; + @Autowired + Gson gson; - @BeforeEach void beforeEach() throws IOException { + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (repository.count() == 0) { try (Reader reader = Files.newBufferedReader(Paths.get("src/test/resources/data/games.json"))) { @@ -52,12 +56,10 @@ * "LIMIT" "0" "100" * */ - @Test void testLoadAllWithEntityReturn() { - List result = entityStream - .of(Game.class) // - .loadAll() - .limit(100) - .toList(Game.class); + @Test + void testLoadAllWithEntityReturn() { + List result = entityStream.of(Game.class) // + .loadAll().limit(100).toList(Game.class); assertThat(result).hasSize(100); } @@ -73,15 +75,13 @@ * "FT.CURSOR" "READ" "com.redis.om.spring.annotations.document.fixtures.GameIdx" "17284697" "45" * */ - @Test void testBasicExplicitCursorSession() { + @Test + void testBasicExplicitCursorSession() { int pageSize = 45; SearchStream searchStream = entityStream.of(Game.class); AggregationResult result = searchStream // - .cursor(pageSize, Duration.ofSeconds(300)) - .loadAll() - .limit(300) - .aggregate(); + .cursor(pageSize, Duration.ofSeconds(300)).loadAll().limit(300).aggregate(); // get the cursor id long cursorId = result.getCursorId(); @@ -98,15 +98,10 @@ } // assert the page counts - assertAll("page counts", - () -> assertEquals(6, pageCounts.size()), - () -> assertEquals(45, pageCounts.get(0)), - () -> assertEquals(45, pageCounts.get(1)), - () -> assertEquals(45, pageCounts.get(2)), - () -> assertEquals(45, pageCounts.get(3)), - () -> assertEquals(45, pageCounts.get(4)), - () -> assertEquals(30, pageCounts.get(5)) - ); + assertAll("page counts", () -> assertEquals(6, pageCounts.size()), () -> assertEquals(45, pageCounts.get(0)), + () -> assertEquals(45, pageCounts.get(1)), () -> assertEquals(45, pageCounts.get(2)), + () -> assertEquals(45, pageCounts.get(3)), () -> assertEquals(45, pageCounts.get(4)), + () -> assertEquals(30, pageCounts.get(5))); } /** @@ -120,14 +115,13 @@ * "FT.CURSOR" "READ" "com.redis.om.spring.annotations.document.fixtures.GameIdx" "17284697" "45" * */ - @Test void testManagedCursorSession() { + @Test + void testManagedCursorSession() { int pageSize = 45; SearchStream searchStream = entityStream.of(Game.class); Slice page = searchStream // - .loadAll() - .limit(300) - .toList(PageRequest.ofSize(pageSize), Game.class); + .loadAll().limit(300).toList(PageRequest.ofSize(pageSize), Game.class); // loop through the slices using the SearchStream.getSlice method passing the next page request // obtained from the current page @@ -140,16 +134,10 @@ } // assert the page counts - assertAll("page counts", - () -> assertEquals(pageSize, pageCounts.get(0)), - () -> assertEquals(pageSize, pageCounts.get(1)), - () -> assertEquals(pageSize, pageCounts.get(2)), - () -> assertEquals(pageSize, pageCounts.get(3)), - () -> assertEquals(pageSize, pageCounts.get(4)), - () -> assertEquals(pageSize, pageCounts.get(5)), - () -> assertEquals(30, pageCounts.get(6)) - ); + assertAll("page counts", () -> assertEquals(pageSize, pageCounts.get(0)), + () -> assertEquals(pageSize, pageCounts.get(1)), () -> assertEquals(pageSize, pageCounts.get(2)), + () -> assertEquals(pageSize, pageCounts.get(3)), () -> assertEquals(pageSize, pageCounts.get(4)), + () -> assertEquals(pageSize, pageCounts.get(5)), () -> assertEquals(30, pageCounts.get(6))); } - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsHashVSSTests.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsHashVSSTests.java index f4ed8759..cbf3a885 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsHashVSSTests.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsHashVSSTests.java @@ -18,12 +18,16 @@ import static org.assertj.core.api.Assertions.withPrecision; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings("SpellCheckingInspection") class EntityStreamsHashVSSTests extends AbstractBaseEnhancedRedisTest { - @Autowired HashWithByteArrayHNSWVectorRepository hnswRepository; - @Autowired HashWithByteArrayFlatVectorRepository flatRepository; +@SuppressWarnings("SpellCheckingInspection") +class EntityStreamsHashVSSTests extends AbstractBaseEnhancedRedisTest { + @Autowired + HashWithByteArrayHNSWVectorRepository hnswRepository; + @Autowired + HashWithByteArrayFlatVectorRepository flatRepository; + + @Autowired + EntityStream entityStream; - @Autowired EntityStream entityStream; - @BeforeEach void cleanUp() { if (hnswRepository.count() == 0 && flatRepository.count() == 0) { @@ -38,8 +42,10 @@ void cleanUp() { float[] vec = new float[dimension]; float val = (float) i / (dimension + i); Arrays.fill(vec, val); - hashWithByteArrayHNSWVectors.add(HashWithByteArrayHNSWVector.of("doc:" + i, ObjectUtils.floatArrayToByteArray(vec), i)); - hashWithByteArrayFlatVectors.add(HashWithByteArrayFlatVector.of("doc:" + i, ObjectUtils.floatArrayToByteArray(vec), i)); + hashWithByteArrayHNSWVectors.add( + HashWithByteArrayHNSWVector.of("doc:" + i, ObjectUtils.floatArrayToByteArray(vec), i)); + hashWithByteArrayFlatVectors.add( + HashWithByteArrayFlatVector.of("doc:" + i, ObjectUtils.floatArrayToByteArray(vec), i)); } hnswRepository.saveAll(hashWithByteArrayHNSWVectors); flatRepository.saveAll(hashWithByteArrayFlatVectors); @@ -49,7 +55,7 @@ void cleanUp() { /** * A simple FT.SEARCH (only vector similarity) * Get top 4 documents where the vector field is closest to [1.4e-30f, 1.4e-30f,...] - * + *

* FT.SEARCH QUERY = `"(*)=>[KNN $K @vector $vector_blob]"` */ @Test @@ -62,18 +68,17 @@ void testPureKNNSearchWithHNSWVectorIndex() { SearchStream stream = entityStream.of(HashWithByteArrayHNSWVector.class); List results = stream // - .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // - .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE) - .limit(K) - .collect(Collectors.toList()); + .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // + .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE).limit(K).collect(Collectors.toList()); - assertThat(results).hasSize(4).map(HashWithByteArrayHNSWVector::getId).containsExactly("doc:0", "doc:1", "doc:2", "doc:3"); + assertThat(results).hasSize(4).map(HashWithByteArrayHNSWVector::getId) + .containsExactly("doc:0", "doc:1", "doc:2", "doc:3"); } /** * A simple FT.SEARCH (only vector similarity) * Get top 4 documents where the vector field is closest to [1.4e-30f, 1.4e-30f,...] - * + *

* FT.SEARCH QUERY = `"(*)=>[KNN $K @vector $vector_blob]"` */ @Test @@ -85,20 +90,20 @@ void testPureKNNSearchWithHNSWVectorIndexOnlyNumberAndDistances() { SearchStream stream = entityStream.of(HashWithByteArrayHNSWVector.class); - List> results = stream // - .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // - .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE) // - .limit(K) // - .map(Fields.of(HashWithByteArrayHNSWVector$.NUMBER, HashWithByteArrayHNSWVector$._VECTOR_SCORE)) // - .collect(Collectors.toList()); + List> results = stream // + .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // + .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE) // + .limit(K) // + .map(Fields.of(HashWithByteArrayHNSWVector$.NUMBER, HashWithByteArrayHNSWVector$._VECTOR_SCORE)) // + .collect(Collectors.toList()); double[] expected = new double[] { 0.0, 0.00980296079069, 0.0384467579424, 0.0848336219788 }; assertAll( // - () -> assertThat(results).hasSize(4), // - () -> assertThat(results).map(Pair::getFirst).containsExactly(0, 1, 2, 3), // - () -> assertThat(results.stream().mapToDouble(Pair::getSecond).toArray()).containsExactly(expected, withPrecision(0.001)) - ); + () -> assertThat(results).hasSize(4), // + () -> assertThat(results).map(Pair::getFirst).containsExactly(0, 1, 2, 3), // + () -> assertThat(results.stream().mapToDouble(Pair::getSecond).toArray()).containsExactly(expected, + withPrecision(0.001))); } /** @@ -118,22 +123,22 @@ void testHybridKNNSearch() { SearchStream stream = entityStream.of(HashWithByteArrayHNSWVector.class); - List> results = stream // - .filter(HashWithByteArrayFlatVector$.NUMBER.between(0, 20) // - .or(HashWithByteArrayFlatVector$.NUMBER.between(NUMBER_ARTICLES - 20, NUMBER_ARTICLES))) // - .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // - .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE) // - .limit(K) // - .map(Fields.of(HashWithByteArrayHNSWVector$.NUMBER, HashWithByteArrayHNSWVector$._VECTOR_SCORE)) // - .collect(Collectors.toList()); + List> results = stream // + .filter(HashWithByteArrayFlatVector$.NUMBER.between(0, 20) // + .or(HashWithByteArrayFlatVector$.NUMBER.between(NUMBER_ARTICLES - 20, NUMBER_ARTICLES))) // + .filter(HashWithByteArrayHNSWVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // + .sorted(HashWithByteArrayHNSWVector$._VECTOR_SCORE) // + .limit(K) // + .map(Fields.of(HashWithByteArrayHNSWVector$.NUMBER, HashWithByteArrayHNSWVector$._VECTOR_SCORE)) // + .collect(Collectors.toList()); double[] expected = new double[] { 0.0, 0.00980296079069, 0.0384467579424, 0.0848336219788, 0.147929027677 }; assertAll( // - () -> assertThat(results).hasSize(5), // - () -> assertThat(results).map(Pair::getFirst).containsExactly(0, 1, 2, 3, 4), // - () -> assertThat(results.stream().mapToDouble(Pair::getSecond).toArray()).containsExactly(expected, withPrecision(0.001)) - ); + () -> assertThat(results).hasSize(5), // + () -> assertThat(results).map(Pair::getFirst).containsExactly(0, 1, 2, 3, 4), // + () -> assertThat(results.stream().mapToDouble(Pair::getSecond).toArray()).containsExactly(expected, + withPrecision(0.001))); } /** @@ -150,14 +155,12 @@ void testHybridKNNSearchWithFlatVectorIndex() { SearchStream stream = entityStream.of(HashWithByteArrayFlatVector.class); List results = stream // - .filter(HashWithByteArrayFlatVector$.NUMBER.between(0, 100)) // - .filter(HashWithByteArrayFlatVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // - .sorted(HashWithByteArrayFlatVector$._VECTOR_SCORE) - .limit(K) - .collect(Collectors.toList()); + .filter(HashWithByteArrayFlatVector$.NUMBER.between(0, 100)) // + .filter(HashWithByteArrayFlatVector$.VECTOR.knn(K, ObjectUtils.floatArrayToByteArray(e))) // + .sorted(HashWithByteArrayFlatVector$._VECTOR_SCORE).limit(K).collect(Collectors.toList()); - assertThat(results).hasSize(5).map(HashWithByteArrayFlatVector::getId).containsExactly("doc:0", "doc:1", "doc:2", "doc:3", "doc:4"); + assertThat(results).hasSize(5).map(HashWithByteArrayFlatVector::getId) + .containsExactly("doc:0", "doc:1", "doc:2", "doc:3", "doc:4"); } - } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsIssuesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsIssuesTest.java index 3d1c3fec..38f3a9ca 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsIssuesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsIssuesTest.java @@ -24,20 +24,33 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings("SpellCheckingInspection") class EntityStreamsIssuesTest extends AbstractBaseDocumentTest { - @Autowired SomeDocumentRepository someDocumentRepository; - @Autowired DeepNestRepository deepNestRepository; - @Autowired DeepNestNonIndexedRepository deepNestNonIndexedRepository; - @Autowired DocRepository docRepository; - @Autowired Doc2Repository doc2Repository; - @Autowired DeepListRepository deepListRepository; - @Autowired DocWithLongRepository docWithLongRepository; - @Autowired PersonRepository personRepository; - @Autowired DocWithBooleanRepository docWithBooleanRepository; - @Autowired DocWithDateRepository docWithDateRepository; - @Autowired KitchenSinkRepository kitchenSinkRepository; - - @Autowired EntityStream entityStream; +@SuppressWarnings("SpellCheckingInspection") +class EntityStreamsIssuesTest extends AbstractBaseDocumentTest { + @Autowired + SomeDocumentRepository someDocumentRepository; + @Autowired + DeepNestRepository deepNestRepository; + @Autowired + DeepNestNonIndexedRepository deepNestNonIndexedRepository; + @Autowired + DocRepository docRepository; + @Autowired + Doc2Repository doc2Repository; + @Autowired + DeepListRepository deepListRepository; + @Autowired + DocWithLongRepository docWithLongRepository; + @Autowired + PersonRepository personRepository; + @Autowired + DocWithBooleanRepository docWithBooleanRepository; + @Autowired + DocWithDateRepository docWithDateRepository; + @Autowired + KitchenSinkRepository kitchenSinkRepository; + + @Autowired + EntityStream entityStream; private LocalDate localDate; private LocalDateTime localDateTime; @@ -49,48 +62,56 @@ private List listThings; private Instant instant; - @BeforeEach void beforeEach() throws IOException { + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (someDocumentRepository.count() == 0) { someDocumentRepository.bulkLoad("src/test/resources/data/some_documents.json"); } if (deepNestRepository.count() == 0) { - DeepNest dn1 = DeepNest.of("dn-1", NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", NestLevel2.of("nl-2-1", "Here's looking at you, kid."))); - DeepNest dn2 = DeepNest.of("dn-2", NestLevel1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", NestLevel2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); - DeepNest dn3 = DeepNest.of("dn-3", NestLevel1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", NestLevel2.of("nl-2-3", "I'm Spartacus!"))); - deepNestRepository.saveAll(List.of(dn1, dn2, dn3)); + DeepNest dn1 = DeepNest.of("dn-1", + NestLevel1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", + NestLevel2.of("nl-2-1", "Here's looking at you, kid."))); + DeepNest dn2 = DeepNest.of("dn-2", + NestLevel1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", + NestLevel2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); + DeepNest dn3 = DeepNest.of("dn-3", + NestLevel1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", + NestLevel2.of("nl-2-3", "I'm Spartacus!"))); + deepNestRepository.saveAll(List.of(dn1, dn2, dn3)); } if (deepNestNonIndexedRepository.count() == 0) { - DeepNestNonIndexed dnni1 = DeepNestNonIndexed.of("dn-1", NestLevelNonIndexed1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", NestLevelNonIndexed2.of("nl-2-1", "Here's looking at you, kid."))); - DeepNestNonIndexed dnni2 = DeepNestNonIndexed.of("dn-2", NestLevelNonIndexed1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", NestLevelNonIndexed2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); - DeepNestNonIndexed dnni3 = DeepNestNonIndexed.of("dn-3", NestLevelNonIndexed1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", NestLevelNonIndexed2.of("nl-2-3", "I'm Spartacus!"))); + DeepNestNonIndexed dnni1 = DeepNestNonIndexed.of("dn-1", + NestLevelNonIndexed1.of("nl-1-1", "Louis, I think this is the beginning of a beautiful friendship.", + NestLevelNonIndexed2.of("nl-2-1", "Here's looking at you, kid."))); + DeepNestNonIndexed dnni2 = DeepNestNonIndexed.of("dn-2", + NestLevelNonIndexed1.of("nl-1-2", "Whoever you are, I have always depended on the kindness of strangers.", + NestLevelNonIndexed2.of("nl-2-2", "Hey, you hens! Cut out the cackling in there!"))); + DeepNestNonIndexed dnni3 = DeepNestNonIndexed.of("dn-3", + NestLevelNonIndexed1.of("nl-1-3", "A good body with a dull brain is as cheap as life itself.", + NestLevelNonIndexed2.of("nl-2-3", "I'm Spartacus!"))); deepNestNonIndexedRepository.saveAll(List.of(dnni1, dnni2, dnni3)); } if (doc2Repository.count() == 0) { List doc2s = new ArrayList<>(); - IntStream.range(0, 31).forEach(i -> doc2s.add(Doc2.of(String.format("Marca%s Modelo %s", i, i), String.format("COLOR %s", i)))); + IntStream.range(0, 31) + .forEach(i -> doc2s.add(Doc2.of(String.format("Marca%s Modelo %s", i, i), String.format("COLOR %s", i)))); doc2Repository.saveAll(doc2s); } if (deepListRepository.count() == 0) { - List list1 = List.of( - NestLevel2.of("nl-1-1", "It's just a flesh wound!"), - NestLevel2.of("nl-1-2", "Nobody expects the Spanish Inquisition!"), - NestLevel2.of("nl-1-3", "I fart in your general direction!") - ); - List list2 = List.of( - NestLevel2.of("nl-2-1", "We are the knights who say 'Ni!"), - NestLevel2.of("nl-2-2", "And now for something completely different."), - NestLevel2.of("nl-2-3", "What have the Romans ever done for us?") - ); - List list3 = List.of( - NestLevel2.of("nl-3-1", "I have a very silly job and I take it very seriously."), - NestLevel2.of("nl-3-2", "What's brown and sticky? A stick!"), - NestLevel2.of("nl-3-3", "I have a theory that the truth is never told during the nine-to-five hours.") - ); + List list1 = List.of(NestLevel2.of("nl-1-1", "It's just a flesh wound!"), + NestLevel2.of("nl-1-2", "Nobody expects the Spanish Inquisition!"), + NestLevel2.of("nl-1-3", "I fart in your general direction!")); + List list2 = List.of(NestLevel2.of("nl-2-1", "We are the knights who say 'Ni!"), + NestLevel2.of("nl-2-2", "And now for something completely different."), + NestLevel2.of("nl-2-3", "What have the Romans ever done for us?")); + List list3 = List.of(NestLevel2.of("nl-3-1", "I have a very silly job and I take it very seriously."), + NestLevel2.of("nl-3-2", "What's brown and sticky? A stick!"), + NestLevel2.of("nl-3-3", "I have a theory that the truth is never told during the nine-to-five hours.")); DeepList dl1 = DeepList.of("dn-1", list1); DeepList dl2 = DeepList.of("dn-2", list2); DeepList dl3 = DeepList.of("dn-3", list3); @@ -119,42 +140,42 @@ instant = Instant.now(); KitchenSink ks = KitchenSink.builder() // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .setThings(setThings) // - .listThings(listThings) // - .instant(instant) // - .build(); + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .setThings(setThings) // + .listThings(listThings) // + .instant(instant) // + .build(); ks.setId("ks0"); KitchenSink ks1 = KitchenSink.builder() // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .setThings(Set.of()) // - .listThings(List.of()) // - .instant(instant) // - .build(); + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .setThings(Set.of()) // + .listThings(List.of()) // + .instant(instant) // + .build(); ks1.setId("ks1"); KitchenSink ks2 = KitchenSink.builder() // - .localDate(localDate) // - .localDateTime(localDateTime) // - .localOffsetDateTime(localOffsetDateTime) // - .date(date) // - .point(point) // - .ulid(ulid) // - .instant(instant) // - .build(); + .localDate(localDate) // + .localDateTime(localDateTime) // + .localOffsetDateTime(localOffsetDateTime) // + .date(date) // + .point(point) // + .ulid(ulid) // + .instant(instant) // + .build(); ks2.setId("ks2"); ks2.setSetThings(null); @@ -164,30 +185,29 @@ } // issue gh-124 - return fields of type String with target String cause GSON MalformedJsonException - @Test void testReturnFieldsOfTypeStringAreProperlyReturned() { + @Test + void testReturnFieldsOfTypeStringAreProperlyReturned() { List results = entityStream.of(SomeDocument.class) // - .filter(SomeDocument$.NAME.eq("LRAWMRENZY")) // - .limit(1000) // - .map(SomeDocument$.DESCRIPTION) // - .collect(Collectors.toList()); + .filter(SomeDocument$.NAME.eq("LRAWMRENZY")) // + .limit(1000) // + .map(SomeDocument$.DESCRIPTION) // + .collect(Collectors.toList()); assertThat(results).contains("nsw fifth pens geo buffalo"); } @Test void testFilterEntityStreamsByNestedField() { var results = entityStream.of(DeepNest.class) // - .filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME.eq("nl-2-2")) - .map(DeepNest$.NAME) // - .collect(Collectors.toList()); + .filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME.eq("nl-2-2")).map(DeepNest$.NAME) // + .collect(Collectors.toList()); assertThat(results).containsOnly("dn-2"); } @Test void testFilterEntityStreamsByNestedField2() { var results = entityStream.of(DeepNest.class) // - .filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_BLOCK.containing("Spartacus")) - .map(DeepNest$.NAME) // - .collect(Collectors.toList()); + .filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_BLOCK.containing("Spartacus")).map(DeepNest$.NAME) // + .collect(Collectors.toList()); assertThat(results).containsOnly("dn-3"); } @@ -200,179 +220,174 @@ void testFreeFormTextSearchOrderIssue() { Doc microsoft1 = docRepository.save(Doc.of("Microsoft", "wwwabcnet")); Doc microsoft2 = docRepository.save(Doc.of("Microsoft", "wwwxyzcom")); - var withFreeTextFirst = entityStream.of(Doc.class) - .filter("*co*") - .filter(Doc$.FIRST.eq("Microsoft")) - .collect(Collectors.toList()); + var withFreeTextFirst = entityStream.of(Doc.class).filter("*co*").filter(Doc$.FIRST.eq("Microsoft")) + .collect(Collectors.toList()); - var withFreeTextLast = entityStream.of(Doc.class) - .filter(Doc$.FIRST.eq("Microsoft")) - .filter("*co*") - .collect(Collectors.toList()); + var withFreeTextLast = entityStream.of(Doc.class).filter(Doc$.FIRST.eq("Microsoft")).filter("*co*") + .collect(Collectors.toList()); assertAll( // - () -> assertThat(withFreeTextLast).containsExactly(microsoft2), - () -> assertThat(withFreeTextFirst).containsExactly(microsoft2) - ); + () -> assertThat(withFreeTextLast).containsExactly(microsoft2), + () -> assertThat(withFreeTextFirst).containsExactly(microsoft2)); } // issue gh-184 - @Test void testPrefixAgainstTextFieldWithSpaces() { + @Test + void testPrefixAgainstTextFieldWithSpaces() { var startingWithMarca2 = entityStream.of(Doc2.class) // - .filter(Doc2$.TEXT.startsWith("Marca2")) // - .collect(Collectors.toList()); + .filter(Doc2$.TEXT.startsWith("Marca2")) // + .collect(Collectors.toList()); assertThat(startingWithMarca2).map(Doc2::getText).allMatch(t -> t.startsWith("Marca2")); } - @Test void testPrefixAgainstTagFieldWithSpaces() { + @Test + void testPrefixAgainstTagFieldWithSpaces() { var startingWithColor1 = entityStream.of(Doc2.class) // - .filter(Doc2$.TAG.startsWith("Color 1")) // - .collect(Collectors.toList()); + .filter(Doc2$.TAG.startsWith("Color 1")) // + .collect(Collectors.toList()); assertThat(startingWithColor1).map(Doc2::getTag).allMatch(t -> t.startsWith("COLOR 1")); } - @Test void testSuffixAgainstTextFieldWithSpaces() { + @Test + void testSuffixAgainstTextFieldWithSpaces() { var startingWithMarca2 = entityStream.of(Doc2.class) // - .filter(Doc2$.TEXT.endsWith("o 11")) // - .collect(Collectors.toList()); + .filter(Doc2$.TEXT.endsWith("o 11")) // + .collect(Collectors.toList()); String regex = ".*o 11$"; assertThat(startingWithMarca2).map(Doc2::getText).allMatch(t -> t.matches(regex)); } - @Test void testSuffixAgainstTagFieldWithSpaces() { + @Test + void testSuffixAgainstTagFieldWithSpaces() { var startingWithMarca2 = entityStream.of(Doc2.class) // - .filter(Doc2$.TAG.endsWith("LOR 12")) // - .collect(Collectors.toList()); + .filter(Doc2$.TAG.endsWith("LOR 12")) // + .collect(Collectors.toList()); String regex = ".*LOR 12$"; assertThat(startingWithMarca2).map(Doc2::getTag).allMatch(t -> t.matches(regex)); } - @Test void testSearchInsideListOfObjects() { + @Test + void testSearchInsideListOfObjects() { var results = entityStream.of(DeepList.class) // - .filter(DeepList_nestLevels$.NAME.eq("nl-2-2")) // - .map(DeepList$.NAME) // - .collect(Collectors.toList()); + .filter(DeepList_nestLevels$.NAME.eq("nl-2-2")) // + .map(DeepList$.NAME) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(1), - () -> assertThat(results).containsExactly("dn-2") - ); + () -> assertThat(results).hasSize(1), () -> assertThat(results).containsExactly("dn-2")); } - @Test void testSearchInsideListOfObjects2() { + @Test + void testSearchInsideListOfObjects2() { var results = entityStream.of(DeepList.class) // - .filter(DeepList_nestLevels$.NAME.startsWith("nl-2")) // - .map(DeepList$.NAME) // - .collect(Collectors.toList()); + .filter(DeepList_nestLevels$.NAME.startsWith("nl-2")) // + .map(DeepList$.NAME) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(1), - () -> assertThat(results).containsExactly("dn-2") - ); + () -> assertThat(results).hasSize(1), () -> assertThat(results).containsExactly("dn-2")); } - @Test void testSearchInsideListOfObjects3() { + @Test + void testSearchInsideListOfObjects3() { var results = entityStream.of(DeepList.class) // - .filter(DeepList_nestLevels$.BLOCK.eq("have")) // - .map(DeepList$.NAME) // - .collect(Collectors.toList()); + .filter(DeepList_nestLevels$.BLOCK.eq("have")) // + .map(DeepList$.NAME) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(2), - () -> assertThat(results).containsExactlyInAnyOrder("dn-2", "dn-3") - ); + () -> assertThat(results).hasSize(2), () -> assertThat(results).containsExactlyInAnyOrder("dn-2", "dn-3")); } - @Test void testLongEqPredicate() { + @Test + void testLongEqPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.eq(3L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.eq(3L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(1), - () -> assertThat(results).extracting("id").containsExactly("doc-3") - ); + () -> assertThat(results).hasSize(1), () -> assertThat(results).extracting("id").containsExactly("doc-3")); } - @Test void testLongGePredicate() { + @Test + void testLongGePredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.ge(3L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.ge(3L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(4), - () -> assertThat(results).extracting("id").containsExactly("doc-3", "doc-4", "doc-5", "doc-6") - ); + () -> assertThat(results).hasSize(4), + () -> assertThat(results).extracting("id").containsExactly("doc-3", "doc-4", "doc-5", "doc-6")); } - @Test void testLongGtPredicate() { + @Test + void testLongGtPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.gt(3L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.gt(3L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(3), - () -> assertThat(results).extracting("id").containsExactly("doc-4", "doc-5", "doc-6") - ); + () -> assertThat(results).hasSize(3), + () -> assertThat(results).extracting("id").containsExactly("doc-4", "doc-5", "doc-6")); } - @Test void testLongInPredicate() { + @Test + void testLongInPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.in(2L, 4L, 6L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.in(2L, 4L, 6L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(3), - () -> assertThat(results).extracting("id").containsExactly("doc-2", "doc-4", "doc-6") - ); + () -> assertThat(results).hasSize(3), + () -> assertThat(results).extracting("id").containsExactly("doc-2", "doc-4", "doc-6")); } - @Test void testLongLePredicate() { + @Test + void testLongLePredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.le(3L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.le(3L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(3), - () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2", "doc-3") - ); + () -> assertThat(results).hasSize(3), + () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2", "doc-3")); } - @Test void testLongLtPredicate() { + @Test + void testLongLtPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.lt(3L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.lt(3L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(2), - () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2") - ); + () -> assertThat(results).hasSize(2), + () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2")); } - @Test void testLongBetweenPredicate() { + @Test + void testLongBetweenPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.between(2L, 5L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.between(2L, 5L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(4), - () -> assertThat(results).extracting("id").containsExactly("doc-2", "doc-3", "doc-4", "doc-5") - ); + () -> assertThat(results).hasSize(4), + () -> assertThat(results).extracting("id").containsExactly("doc-2", "doc-3", "doc-4", "doc-5")); } - @Test void testLongNotEqPredicate() { + @Test + void testLongNotEqPredicate() { var results = entityStream.of(DocWithLong.class) // - .filter(DocWithLong$.THE_LONG.notEq(5L)) // - .collect(Collectors.toList()); + .filter(DocWithLong$.THE_LONG.notEq(5L)) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(results).hasSize(5), - () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2", "doc-3", "doc-4", "doc-6") - ); + () -> assertThat(results).hasSize(5), + () -> assertThat(results).extracting("id").containsExactly("doc-1", "doc-2", "doc-3", "doc-4", "doc-6")); } // issue gh-264 SCENARIO 1 @@ -383,10 +398,9 @@ void testMapEntityStreamsReturnNullValue() { personWithoutEmail.setEmail(null); personRepository.save(personWithoutEmail); - var result = entityStream.of(Person.class) - .filter(Person$.NAME.eq("PersonWithoutEmail")) - .map(Fields.of(Person$.NAME, Person$.EMAIL)) // should handle empty email as mapped return value - .collect(Collectors.toList()).stream().findFirst().get(); + var result = entityStream.of(Person.class).filter(Person$.NAME.eq("PersonWithoutEmail")) + .map(Fields.of(Person$.NAME, Person$.EMAIL)) // should handle empty email as mapped return value + .collect(Collectors.toList()).stream().findFirst().get(); assertThat(result.getFirst()).isEqualTo("PersonWithoutEmail"); assertThat(result.getSecond()).isEqualTo(null); } @@ -394,10 +408,9 @@ void testMapEntityStreamsReturnNullValue() { // issue gh-264 SCENARIO 2 @Test void testMapEntityStreamsReturnNestedField() { - var results = entityStream.of(DeepNest.class) - .filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME.eq("nl-2-2")) - .map(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME) // should handle nested property as mapped return value - .collect(Collectors.toList()); + var results = entityStream.of(DeepNest.class).filter(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME.eq("nl-2-2")) + .map(DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME) // should handle nested property as mapped return value + .collect(Collectors.toList()); assertThat(results).containsOnly("nl-2-2"); } @@ -408,10 +421,9 @@ void testMapEntityStreamsReturnIndexedBooleanValue() { docWithBoolean.setIndexedBoolean(true); docWithBooleanRepository.save(docWithBoolean); - var result = entityStream.of(DocWithBoolean.class) - .filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) - .map(DocWithBoolean$.INDEXED_BOOLEAN) // should handle returned indexed boolean value, but fails - .collect(Collectors.toList()); + var result = entityStream.of(DocWithBoolean.class).filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) + .map(DocWithBoolean$.INDEXED_BOOLEAN) // should handle returned indexed boolean value, but fails + .collect(Collectors.toList()); assertThat(result).containsOnly(true); } @@ -422,10 +434,9 @@ void testMapEntityStreamsReturnIndexedBooleanPrimitiveValue() { docWithBoolean.setIndexedPrimitiveBoolean(true); docWithBooleanRepository.save(docWithBoolean); - var result = entityStream.of(DocWithBoolean.class) - .filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) - .map(DocWithBoolean$.INDEXED_PRIMITIVE_BOOLEAN) // should handle returned indexed boolean primitive value, but fails - .collect(Collectors.toList()); + var result = entityStream.of(DocWithBoolean.class).filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())).map( + DocWithBoolean$.INDEXED_PRIMITIVE_BOOLEAN) // should handle returned indexed boolean primitive value, but fails + .collect(Collectors.toList()); assertThat(result).containsOnly(true); } @@ -436,10 +447,9 @@ void testMapEntityStreamsReturnNonIndexedBooleanValue() { docWithBoolean.setNonIndexedBoolean(true); docWithBooleanRepository.save(docWithBoolean); - var result = entityStream.of(DocWithBoolean.class) - .filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) - .map(DocWithBoolean$.NON_INDEXED_BOOLEAN) // should handle returned non indexed boolean value, succeeds - .collect(Collectors.toList()); + var result = entityStream.of(DocWithBoolean.class).filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) + .map(DocWithBoolean$.NON_INDEXED_BOOLEAN) // should handle returned non indexed boolean value, succeeds + .collect(Collectors.toList()); assertThat(result).containsOnly(true); } @@ -450,10 +460,9 @@ void testMapEntityStreamsReturnNonIndexedBooleanPrimitiveValue() { docWithBoolean.setNonIndexedPrimitiveBoolean(true); docWithBooleanRepository.save(docWithBoolean); - var result = entityStream.of(DocWithBoolean.class) - .filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())) - .map(DocWithBoolean$.NON_INDEXED_PRIMITIVE_BOOLEAN) // should handle returned non indexed primitive boolean primitive value, but fails - .collect(Collectors.toList()); + var result = entityStream.of(DocWithBoolean.class).filter(DocWithBoolean$.ID.eq(docWithBoolean.getId())).map( + DocWithBoolean$.NON_INDEXED_PRIMITIVE_BOOLEAN) // should handle returned non indexed primitive boolean primitive value, but fails + .collect(Collectors.toList()); assertThat(result).containsOnly(true); } @@ -480,10 +489,8 @@ void testOnOrAfterDateFilter() throws ParseException { docWithDateRepository.saveAll(List.of(dwd1, dwd2, dwd3, dwd4, dwd5)); - var results = entityStream.of(DocWithDate.class) - .filter(DocWithDate$.DATE.onOrAfter(date4)) - .map(DocWithDate$.ID) - .collect(Collectors.toList()); + var results = entityStream.of(DocWithDate.class).filter(DocWithDate$.DATE.onOrAfter(date4)).map(DocWithDate$.ID) + .collect(Collectors.toList()); assertThat(results).containsOnly("three", "four", "five"); } @@ -491,146 +498,101 @@ void testOnOrAfterDateFilter() throws ParseException { @Test void testNonIndexedReturnedFields() { var allFields = Fields.of( // - KitchenSink$.LOCAL_DATE, - KitchenSink$.LOCAL_DATE_TIME, - KitchenSink$.DATE, - KitchenSink$.POINT, - KitchenSink$.ULID, - KitchenSink$.SET_THINGS, - KitchenSink$.LIST_THINGS); - var result = entityStream.of(KitchenSink.class) - .filter(KitchenSink$.ID.eq("ks0")) - .map(allFields) - .collect(Collectors.toList()); + KitchenSink$.LOCAL_DATE, KitchenSink$.LOCAL_DATE_TIME, KitchenSink$.DATE, KitchenSink$.POINT, KitchenSink$.ULID, + KitchenSink$.SET_THINGS, KitchenSink$.LIST_THINGS); + var result = entityStream.of(KitchenSink.class).filter(KitchenSink$.ID.eq("ks0")).map(allFields) + .collect(Collectors.toList()); assertThat(result).hasSize(1); var ksValues = result.get(0); assertAll( // - () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), - () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), - () -> assertThat(ksValues.getThird()).isEqualTo(date), - () -> assertThat(ksValues.getFourth()).isEqualTo(point), - () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), - () -> assertThat(ksValues.getSixth()).containsExactlyInAnyOrderElementsOf(setThings), - () -> assertThat(ksValues.getSeventh()).containsExactlyInAnyOrderElementsOf(listThings) - ); + () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), + () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), + () -> assertThat(ksValues.getThird()).isEqualTo(date), () -> assertThat(ksValues.getFourth()).isEqualTo(point), + () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), + () -> assertThat(ksValues.getSixth()).containsExactlyInAnyOrderElementsOf(setThings), + () -> assertThat(ksValues.getSeventh()).containsExactlyInAnyOrderElementsOf(listThings)); } @Test void testNonIndexedReturnedFieldsWithEmptyCollections() { var allFields = Fields.of( // - KitchenSink$.LOCAL_DATE, - KitchenSink$.LOCAL_DATE_TIME, - KitchenSink$.DATE, - KitchenSink$.POINT, - KitchenSink$.ULID, - KitchenSink$.SET_THINGS, - KitchenSink$.LIST_THINGS); - var result = entityStream.of(KitchenSink.class) - .filter(KitchenSink$.ID.eq("ks1")) - .map(allFields) - .collect(Collectors.toList()); + KitchenSink$.LOCAL_DATE, KitchenSink$.LOCAL_DATE_TIME, KitchenSink$.DATE, KitchenSink$.POINT, KitchenSink$.ULID, + KitchenSink$.SET_THINGS, KitchenSink$.LIST_THINGS); + var result = entityStream.of(KitchenSink.class).filter(KitchenSink$.ID.eq("ks1")).map(allFields) + .collect(Collectors.toList()); assertThat(result).hasSize(1); var ksValues = result.get(0); assertAll( // - () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), - () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), - () -> assertThat(ksValues.getThird()).isEqualTo(date), - () -> assertThat(ksValues.getFourth()).isEqualTo(point), - () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), - () -> assertThat(ksValues.getSixth()).isNull(), - () -> assertThat(ksValues.getSeventh()).isNull() - ); + () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), + () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), + () -> assertThat(ksValues.getThird()).isEqualTo(date), () -> assertThat(ksValues.getFourth()).isEqualTo(point), + () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), () -> assertThat(ksValues.getSixth()).isNull(), + () -> assertThat(ksValues.getSeventh()).isNull()); } @Test void testNonIndexedReturnedFieldsWithNullCollections() { var allFields = Fields.of( // - KitchenSink$.LOCAL_DATE, - KitchenSink$.LOCAL_DATE_TIME, - KitchenSink$.DATE, - KitchenSink$.POINT, - KitchenSink$.ULID, - KitchenSink$.SET_THINGS, - KitchenSink$.LIST_THINGS); - - var result = entityStream.of(KitchenSink.class) - .filter(KitchenSink$.ID.eq("ks2")) - .map(allFields) - .collect(Collectors.toList()); + KitchenSink$.LOCAL_DATE, KitchenSink$.LOCAL_DATE_TIME, KitchenSink$.DATE, KitchenSink$.POINT, KitchenSink$.ULID, + KitchenSink$.SET_THINGS, KitchenSink$.LIST_THINGS); + + var result = entityStream.of(KitchenSink.class).filter(KitchenSink$.ID.eq("ks2")).map(allFields) + .collect(Collectors.toList()); assertThat(result).hasSize(1); var ksValues = result.get(0); assertAll( // - () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), - () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), - () -> assertThat(ksValues.getThird()).isEqualTo(date), - () -> assertThat(ksValues.getFourth()).isEqualTo(point), - () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), - () -> assertThat(ksValues.getSixth()).isNull(), - () -> assertThat(ksValues.getSeventh()).isNull() - ); + () -> assertThat(ksValues.getFirst()).isEqualTo(localDate), + () -> assertThat(ksValues.getSecond()).isEqualToIgnoringNanos(localDateTime), + () -> assertThat(ksValues.getThird()).isEqualTo(date), () -> assertThat(ksValues.getFourth()).isEqualTo(point), + () -> assertThat(ksValues.getFifth()).isEqualTo(ulid), () -> assertThat(ksValues.getSixth()).isNull(), + () -> assertThat(ksValues.getSeventh()).isNull()); } @Test void testReturnedFieldsDeepNested() { var allFields = Fields.of( // - DeepNest$.NAME, - DeepNest$.NEST_LEVEL1_NAME, - DeepNest$.NEST_LEVEL1_BLOCK, - DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME, - DeepNest$.NEST_LEVEL1_NEST_LEVEL2_BLOCK - ); - var result = entityStream.of(DeepNest.class) - .filter(DeepNest$.NAME.eq("dn-1")) - .map(allFields) - .collect(Collectors.toList()); + DeepNest$.NAME, DeepNest$.NEST_LEVEL1_NAME, DeepNest$.NEST_LEVEL1_BLOCK, DeepNest$.NEST_LEVEL1_NEST_LEVEL2_NAME, + DeepNest$.NEST_LEVEL1_NEST_LEVEL2_BLOCK); + var result = entityStream.of(DeepNest.class).filter(DeepNest$.NAME.eq("dn-1")).map(allFields) + .collect(Collectors.toList()); assertThat(result).hasSize(1); var values = result.get(0); assertAll( // - () -> assertThat(values.getFirst()).isEqualTo("dn-1"), - () -> assertThat(values.getSecond()).isEqualTo("nl-1-1"), - () -> assertThat(values.getThird()).isEqualTo("Louis, I think this is the beginning of a beautiful friendship."), - () -> assertThat(values.getFourth()).isEqualTo("nl-2-1"), - () -> assertThat(values.getFifth()).isEqualTo("Here's looking at you, kid.") - ); + () -> assertThat(values.getFirst()).isEqualTo("dn-1"), () -> assertThat(values.getSecond()).isEqualTo("nl-1-1"), + () -> assertThat(values.getThird()).isEqualTo("Louis, I think this is the beginning of a beautiful friendship."), + () -> assertThat(values.getFourth()).isEqualTo("nl-2-1"), + () -> assertThat(values.getFifth()).isEqualTo("Here's looking at you, kid.")); } @Test void testReturnedFieldsDeepNestedNonIndexed() { var allFields = Fields.of( // - DeepNestNonIndexed$.NAME, - DeepNestNonIndexed$.NEST_LEVEL1_NAME, - DeepNestNonIndexed$.NEST_LEVEL1_BLOCK, - DeepNestNonIndexed$.NEST_LEVEL1_NEST_LEVEL2_NAME, - DeepNestNonIndexed$.NEST_LEVEL1_NEST_LEVEL2_BLOCK - ); - var result = entityStream.of(DeepNestNonIndexed.class) - .filter(DeepNestNonIndexed$.NAME.eq("dn-1")) - .map(allFields) - .collect(Collectors.toList()); + DeepNestNonIndexed$.NAME, DeepNestNonIndexed$.NEST_LEVEL1_NAME, DeepNestNonIndexed$.NEST_LEVEL1_BLOCK, + DeepNestNonIndexed$.NEST_LEVEL1_NEST_LEVEL2_NAME, DeepNestNonIndexed$.NEST_LEVEL1_NEST_LEVEL2_BLOCK); + var result = entityStream.of(DeepNestNonIndexed.class).filter(DeepNestNonIndexed$.NAME.eq("dn-1")).map(allFields) + .collect(Collectors.toList()); assertThat(result).hasSize(1); var values = result.get(0); assertAll( // - () -> assertThat(values.getFirst()).isEqualTo("dn-1"), - () -> assertThat(values.getSecond()).isEqualTo("nl-1-1"), - () -> assertThat(values.getThird()).isEqualTo("Louis, I think this is the beginning of a beautiful friendship."), - () -> assertThat(values.getFourth()).isEqualTo("nl-2-1"), - () -> assertThat(values.getFifth()).isEqualTo("Here's looking at you, kid.") - ); + () -> assertThat(values.getFirst()).isEqualTo("dn-1"), () -> assertThat(values.getSecond()).isEqualTo("nl-1-1"), + () -> assertThat(values.getThird()).isEqualTo("Louis, I think this is the beginning of a beautiful friendship."), + () -> assertThat(values.getFourth()).isEqualTo("nl-2-1"), + () -> assertThat(values.getFifth()).isEqualTo("Here's looking at you, kid.")); } @Test @@ -638,9 +600,7 @@ void testEqAgainstContentWithForwardSlash() { Doc2 doc1 = doc2Repository.save(Doc2.of("This is Picture", "excellent/birds")); Doc2 doc2 = doc2Repository.save(Doc2.of("Here it comes", "excellent/snow")); - var result = entityStream.of(Doc2.class) - .filter(Doc2$.TAG.eq("excellent/birds")) - .collect(Collectors.toList()); + var result = entityStream.of(Doc2.class).filter(Doc2$.TAG.eq("excellent/birds")).collect(Collectors.toList()); assertThat(result).hasSize(1); assertThat(result.get(0)).isEqualTo(doc1); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsZipCodeDataAggregationsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsZipCodeDataAggregationsTest.java index 52077ca4..07144387 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsZipCodeDataAggregationsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/EntityStreamsZipCodeDataAggregationsTest.java @@ -19,12 +19,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings({ "unchecked", "SpellCheckingInspection" }) class EntityStreamsZipCodeDataAggregationsTest extends AbstractBaseDocumentTest { - @Autowired EntityStream entityStream; +@SuppressWarnings({ "unchecked", "SpellCheckingInspection" }) +class EntityStreamsZipCodeDataAggregationsTest extends AbstractBaseDocumentTest { + @Autowired + EntityStream entityStream; - @Autowired ZipCodeRepository repository; + @Autowired + ZipCodeRepository repository; - @BeforeEach void beforeEach() throws IOException { + @BeforeEach + void beforeEach() throws IOException { // Load Sample Docs if (repository.count() == 0) { repository.bulkLoad("src/test/resources/data/zips.json"); @@ -39,21 +43,20 @@ * { $match: { totalPop: { $gte: 10*1000*1000 } } } * ] ) * - * */ - @Test void testReturnStatesWithPopulationsAbove10Million() { + @Test + void testReturnStatesWithPopulationsAbove10Million() { var stream = entityStream.of(ZipCode.class); - List> statePopulation = stream // - .apply("@state", "_id") // - .groupBy(Alias.of("_id")) // - .reduce(ReducerFunction.SUM, ZipCode$.POP).as("totalPop") // - .filter("@totalPop >= 10*1000*1000") - .toList(String.class, Long.class); + List> statePopulation = stream // + .apply("@state", "_id") // + .groupBy(Alias.of("_id")) // + .reduce(ReducerFunction.SUM, ZipCode$.POP).as("totalPop") // + .filter("@totalPop >= 10*1000*1000").toList(String.class, Long.class); assertAll( - () -> assertThat(statePopulation).map(Pair::getFirst).containsExactly("NY", "IL", "PA", "CA", "OH", "FL", "TX"), - () -> assertThat(statePopulation).map(Pair::getSecond).containsExactly(17990402L, 11427576L, 11881643L, 29754890L, 10846517L, 12686644L, 16984601L) - ); + () -> assertThat(statePopulation).map(Pair::getFirst).containsExactly("NY", "IL", "PA", "CA", "OH", "FL", "TX"), + () -> assertThat(statePopulation).map(Pair::getSecond) + .containsExactly(17990402L, 11427576L, 11881643L, 29754890L, 10846517L, 12686644L, 16984601L)); } /** @@ -64,21 +67,20 @@ * { $group: { _id: "$_id.state", avgCityPop: { $avg: "$pop" } } } * ] ) * - * */ - @Test void testReturnAverageCityPopulationByState() { + @Test + void testReturnAverageCityPopulationByState() { var stream = entityStream.of(ZipCode.class); - List> statePopulation = stream // - .apply("@state", "_id") // - .groupBy(Alias.of("_id")) // - .reduce(ReducerFunction.SUM, ZipCode$.POP).as("totalPop") // - .filter("@totalPop >= 10*1000*1000") - .toList(String.class, Long.class); + List> statePopulation = stream // + .apply("@state", "_id") // + .groupBy(Alias.of("_id")) // + .reduce(ReducerFunction.SUM, ZipCode$.POP).as("totalPop") // + .filter("@totalPop >= 10*1000*1000").toList(String.class, Long.class); assertAll( - () -> assertThat(statePopulation).map(Pair::getFirst).containsExactly("NY", "IL", "PA", "CA", "OH", "FL", "TX"), - () -> assertThat(statePopulation).map(Pair::getSecond).containsExactly(17990402L, 11427576L, 11881643L, 29754890L, 10846517L, 12686644L, 16984601L) - ); + () -> assertThat(statePopulation).map(Pair::getFirst).containsExactly("NY", "IL", "PA", "CA", "OH", "FL", "TX"), + () -> assertThat(statePopulation).map(Pair::getSecond) + .containsExactly(17990402L, 11427576L, 11881643L, 29754890L, 10846517L, 12686644L, 16984601L)); } /** @@ -112,7 +114,7 @@ * } * ]) * - * + *

* The RediSearch way: *

    * "FT.AGGREGATE" "com.redis.om.spring.annotations.document.fixtures.ZipCodeIdx" "( @pop:[(0 inf])"
@@ -126,73 +128,74 @@
    *   "LIMIT" "0" "10000"
    * 
*/ - @Test void testReturnLargestAndSmallestCitiesByState() { + @Test + void testReturnLargestAndSmallestCitiesByState() { // expected results - Quintuple[] expected = List.of( // - Tuples.of("AK", "ANCHORAGE", 183987L, "CROOKED CREEK", 1L), // - Tuples.of("AL", "BIRMINGHAM", 242606L, "MORVIN", 24L), // - Tuples.of("AR", "LITTLE ROCK", 192895L, "ARKANSAS CITY", 7L), // - Tuples.of("AZ", "PHOENIX", 890853L, "HUALAPAI", 2L), // - Tuples.of("CA", "LOS ANGELES", 2102295L, "MAD RIVER", 6L), // - Tuples.of("CO", "DENVER", 451182L, "ELK SPRINGS", 10L), // - Tuples.of("CT", "BRIDGEPORT", 141638L, "EAST KILLINGLY", 25L), // - Tuples.of("DC", "WASHINGTON", 606879L, "PENTAGON", 21L), // - Tuples.of("DE", "NEWARK", 111674L, "BETHEL", 108L), // - Tuples.of("FL", "MIAMI", 825232L, "KENNEDY SPACE CE", 1L), // - Tuples.of("GA", "ATLANTA", 609591L, "MARBLE HILL", 98L), // - Tuples.of("HI", "HONOLULU", 396643L, "HAWAII NATIONAL", 91L), // - Tuples.of("IA", "DES MOINES", 148155L, "DOUDS", 15L), // - Tuples.of("ID", "BOISE", 165522L, "DARLINGTON", 12L), // - Tuples.of("IL", "CHICAGO", 2452177L, "ANCONA", 38L), // - Tuples.of("IN", "INDIANAPOLIS", 348868L, "WESTPOINT", 145L), // - Tuples.of("KS", "WICHITA", 295115L, "NEW ALMELO", 2L), // - Tuples.of("KY", "LOUISVILLE", 288058L, "WOODBINE", 10L), // - Tuples.of("LA", "NEW ORLEANS", 496937L, "LOTTIE", 9L), // - Tuples.of("MA", "WORCESTER", 169856L, "BUCKLAND", 16L), // - Tuples.of("MD", "BALTIMORE", 733081L, "ANNAPOLIS JUNCTI", 32L), // - Tuples.of("ME", "PORTLAND", 63268L, "SQUIRREL ISLAND", 3L), // - Tuples.of("MI", "DETROIT", 963243L, "COOKS", 2L), // - Tuples.of("MN", "MINNEAPOLIS", 344719L, "JOHNSON", 12L), // - Tuples.of("MO", "SAINT LOUIS", 397802L, "BENDAVIS", 44L), // - Tuples.of("MS", "JACKSON", 204788L, "CHUNKY", 79L), // - Tuples.of("MT", "BILLINGS", 78805L, "HOMESTEAD", 7L), // - Tuples.of("NC", "CHARLOTTE", 465833L, "ROARING GAP", 21L), // - Tuples.of("ND", "GRAND FORKS", 59527L, "TROTTERS", 12L), // - Tuples.of("NE", "OMAHA", 358930L, "LAKESIDE", 5L), // - Tuples.of("NH", "MANCHESTER", 106452L, "WEST NOTTINGHAM", 27L), // - Tuples.of("NJ", "NEWARK", 275572L, "IMLAYSTOWN", 17L), // - Tuples.of("NM", "ALBUQUERQUE", 449584L, "JEMEZ SPRINGS", 1L), // - Tuples.of("NV", "LAS VEGAS", 597557L, "TUSCARORA", 1L), // - Tuples.of("NY", "BROOKLYN", 2300504L, "NEW HYDE PARK", 1L), // - Tuples.of("OH", "CLEVELAND", 536759L, "ISLE SAINT GEORG", 38L), // - Tuples.of("OK", "TULSA", 389072L, "SOUTHARD", 8L), // - Tuples.of("OR", "PORTLAND", 518543L, "SUMMER LAKE", 1L), // - Tuples.of("PA", "PHILADELPHIA", 1610956L, "OLIVEBURG", 8L), // - Tuples.of("RI", "CRANSTON", 176404L, "CLAYVILLE", 45L), // - Tuples.of("SC", "COLUMBIA", 269521L, "GARNETT", 61L), // - Tuples.of("SD", "SIOUX FALLS", 102046L, "ZEONA", 8L), // - Tuples.of("TN", "MEMPHIS", 632837L, "ALLRED", 2L), // - Tuples.of("TX", "HOUSTON", 2095918L, "BEND", 1L), // - Tuples.of("UT", "SALT LAKE CITY", 186346L, "MODENA", 9L), // - Tuples.of("VA", "VIRGINIA BEACH", 385080L, "HOWARDSVILLE", 21L), // - Tuples.of("VT", "BURLINGTON", 39127L, "AVERILL", 7L), // - Tuples.of("WA", "SEATTLE", 520096L, "BENGE", 2L), // - Tuples.of("WI", "MILWAUKEE", 597324L, "CLAM LAKE", 2L), // - Tuples.of("WV", "HUNTINGTON", 75343L, "FISHER", 1L), // - Tuples.of("WY", "CHEYENNE", 70185L, "LOST SPRINGS", 6L) // + Quintuple[] expected = List.of( // + Tuples.of("AK", "ANCHORAGE", 183987L, "CROOKED CREEK", 1L), // + Tuples.of("AL", "BIRMINGHAM", 242606L, "MORVIN", 24L), // + Tuples.of("AR", "LITTLE ROCK", 192895L, "ARKANSAS CITY", 7L), // + Tuples.of("AZ", "PHOENIX", 890853L, "HUALAPAI", 2L), // + Tuples.of("CA", "LOS ANGELES", 2102295L, "MAD RIVER", 6L), // + Tuples.of("CO", "DENVER", 451182L, "ELK SPRINGS", 10L), // + Tuples.of("CT", "BRIDGEPORT", 141638L, "EAST KILLINGLY", 25L), // + Tuples.of("DC", "WASHINGTON", 606879L, "PENTAGON", 21L), // + Tuples.of("DE", "NEWARK", 111674L, "BETHEL", 108L), // + Tuples.of("FL", "MIAMI", 825232L, "KENNEDY SPACE CE", 1L), // + Tuples.of("GA", "ATLANTA", 609591L, "MARBLE HILL", 98L), // + Tuples.of("HI", "HONOLULU", 396643L, "HAWAII NATIONAL", 91L), // + Tuples.of("IA", "DES MOINES", 148155L, "DOUDS", 15L), // + Tuples.of("ID", "BOISE", 165522L, "DARLINGTON", 12L), // + Tuples.of("IL", "CHICAGO", 2452177L, "ANCONA", 38L), // + Tuples.of("IN", "INDIANAPOLIS", 348868L, "WESTPOINT", 145L), // + Tuples.of("KS", "WICHITA", 295115L, "NEW ALMELO", 2L), // + Tuples.of("KY", "LOUISVILLE", 288058L, "WOODBINE", 10L), // + Tuples.of("LA", "NEW ORLEANS", 496937L, "LOTTIE", 9L), // + Tuples.of("MA", "WORCESTER", 169856L, "BUCKLAND", 16L), // + Tuples.of("MD", "BALTIMORE", 733081L, "ANNAPOLIS JUNCTI", 32L), // + Tuples.of("ME", "PORTLAND", 63268L, "SQUIRREL ISLAND", 3L), // + Tuples.of("MI", "DETROIT", 963243L, "COOKS", 2L), // + Tuples.of("MN", "MINNEAPOLIS", 344719L, "JOHNSON", 12L), // + Tuples.of("MO", "SAINT LOUIS", 397802L, "BENDAVIS", 44L), // + Tuples.of("MS", "JACKSON", 204788L, "CHUNKY", 79L), // + Tuples.of("MT", "BILLINGS", 78805L, "HOMESTEAD", 7L), // + Tuples.of("NC", "CHARLOTTE", 465833L, "ROARING GAP", 21L), // + Tuples.of("ND", "GRAND FORKS", 59527L, "TROTTERS", 12L), // + Tuples.of("NE", "OMAHA", 358930L, "LAKESIDE", 5L), // + Tuples.of("NH", "MANCHESTER", 106452L, "WEST NOTTINGHAM", 27L), // + Tuples.of("NJ", "NEWARK", 275572L, "IMLAYSTOWN", 17L), // + Tuples.of("NM", "ALBUQUERQUE", 449584L, "JEMEZ SPRINGS", 1L), // + Tuples.of("NV", "LAS VEGAS", 597557L, "TUSCARORA", 1L), // + Tuples.of("NY", "BROOKLYN", 2300504L, "NEW HYDE PARK", 1L), // + Tuples.of("OH", "CLEVELAND", 536759L, "ISLE SAINT GEORG", 38L), // + Tuples.of("OK", "TULSA", 389072L, "SOUTHARD", 8L), // + Tuples.of("OR", "PORTLAND", 518543L, "SUMMER LAKE", 1L), // + Tuples.of("PA", "PHILADELPHIA", 1610956L, "OLIVEBURG", 8L), // + Tuples.of("RI", "CRANSTON", 176404L, "CLAYVILLE", 45L), // + Tuples.of("SC", "COLUMBIA", 269521L, "GARNETT", 61L), // + Tuples.of("SD", "SIOUX FALLS", 102046L, "ZEONA", 8L), // + Tuples.of("TN", "MEMPHIS", 632837L, "ALLRED", 2L), // + Tuples.of("TX", "HOUSTON", 2095918L, "BEND", 1L), // + Tuples.of("UT", "SALT LAKE CITY", 186346L, "MODENA", 9L), // + Tuples.of("VA", "VIRGINIA BEACH", 385080L, "HOWARDSVILLE", 21L), // + Tuples.of("VT", "BURLINGTON", 39127L, "AVERILL", 7L), // + Tuples.of("WA", "SEATTLE", 520096L, "BENGE", 2L), // + Tuples.of("WI", "MILWAUKEE", 597324L, "CLAM LAKE", 2L), // + Tuples.of("WV", "HUNTINGTON", 75343L, "FISHER", 1L), // + Tuples.of("WY", "CHEYENNE", 70185L, "LOST SPRINGS", 6L) // ).toArray(new Quintuple[0]); var stream = entityStream.of(ZipCode.class); - List> largestAndSmallestCitiesByState = stream // - .filter(ZipCode$.POP.gt(0)) // - .groupBy(ZipCode$.STATE, ZipCode$.CITY) // - .reduce(ReducerFunction.SUM, ZipCode$.POP).as("total_pop") // - .groupBy(ZipCode$.STATE) // - .reduce(ReducerFunction.FIRST_VALUE, ZipCode$.CITY, Alias.of("total_pop").desc()).as("biggestCity") // - .reduce(ReducerFunction.FIRST_VALUE, Alias.of("total_pop"), Alias.of("total_pop").desc()).as("biggestPop") // - .reduce(ReducerFunction.FIRST_VALUE, ZipCode$.CITY, Alias.of("total_pop").asc()).as("smallestCity") // - .reduce(ReducerFunction.FIRST_VALUE, Alias.of("total_pop"), Alias.of("total_pop").asc()).as("smallestPop") // - .toList(String.class, String.class, Long.class, String.class, Long.class); + List> largestAndSmallestCitiesByState = stream // + .filter(ZipCode$.POP.gt(0)) // + .groupBy(ZipCode$.STATE, ZipCode$.CITY) // + .reduce(ReducerFunction.SUM, ZipCode$.POP).as("total_pop") // + .groupBy(ZipCode$.STATE) // + .reduce(ReducerFunction.FIRST_VALUE, ZipCode$.CITY, Alias.of("total_pop").desc()).as("biggestCity") // + .reduce(ReducerFunction.FIRST_VALUE, Alias.of("total_pop"), Alias.of("total_pop").desc()).as("biggestPop") // + .reduce(ReducerFunction.FIRST_VALUE, ZipCode$.CITY, Alias.of("total_pop").asc()).as("smallestCity") // + .reduce(ReducerFunction.FIRST_VALUE, Alias.of("total_pop"), Alias.of("total_pop").asc()).as("smallestPop") // + .toList(String.class, String.class, Long.class, String.class, Long.class); assertThat(largestAndSmallestCitiesByState).containsExactlyInAnyOrder(expected); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/TestTupleJsonSerialization.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/TestTupleJsonSerialization.java index 911d256f..5da2b5bd 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/TestTupleJsonSerialization.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/TestTupleJsonSerialization.java @@ -26,14 +26,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings("SpellCheckingInspection") class TestTupleJsonSerialization extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class TestTupleJsonSerialization extends AbstractBaseDocumentTest { @Autowired CompanyRepository repository; @Autowired EntityStream entityStream; - @SuppressWarnings("unused") private JacksonTester>> json; + @SuppressWarnings("unused") + private JacksonTester>> json; @BeforeEach void setupAndCleanup() { @@ -44,19 +46,20 @@ void setupAndCleanup() { repository.deleteAll(); Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Set employees = Sets.newHashSet(Employee.of("Brian Sam-Bodden"), Employee.of("Guy Royse"), - Employee.of("Justin Castilla")); + Employee.of("Justin Castilla")); redis.setEmployees(employees); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); microsoft.setTags(Set.of("innovative", "reliable", "os", "ai")); Company tesla = repository.save( - Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); + Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); tesla.setTags(Set.of("innovative", "futuristic", "ai")); repository.saveAll(List.of(redis, microsoft, tesla)); @@ -65,11 +68,11 @@ void setupAndCleanup() { @Test void testTripleResultWithLabels() throws IOException { List> results = entityStream // - .of(Company.class) // - .sorted(Company$.NAME, SortOrder.DESC) // - .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // - .mapToLabelledMaps() // - .collect(Collectors.toList()); + .of(Company.class) // + .sorted(Company$.NAME, SortOrder.DESC) // + .map(Fields.of(Company$.NAME, Company$.YEAR_FOUNDED, Company$.LOCATION)) // + .mapToLabelledMaps() // + .collect(Collectors.toList()); assertEquals(3, results.size()); diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/WrapperSearchStreamTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/WrapperSearchStreamTest.java index fdbca759..a9b5fa89 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/WrapperSearchStreamTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/search/stream/WrapperSearchStreamTest.java @@ -20,7 +20,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") class WrapperSearchStreamTest extends AbstractBaseDocumentTest { +@SuppressWarnings("SpellCheckingInspection") +class WrapperSearchStreamTest extends AbstractBaseDocumentTest { @Autowired CompanyRepository repository; @@ -36,19 +37,20 @@ void cleanUp() { repository.deleteAll(); Company redis = repository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Set employees = Sets.newHashSet(Employee.of("Brian Sam-Bodden"), Employee.of("Guy Royse"), - Employee.of("Justin Castilla")); + Employee.of("Justin Castilla")); redis.setEmployees(employees); - Company microsoft = repository.save(Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), - new Point(-122.124500, 47.640160), "research@microsoft.com")); + Company microsoft = repository.save( + Company.of("Microsoft", 1975, LocalDate.of(2022, 8, 15), new Point(-122.124500, 47.640160), + "research@microsoft.com")); microsoft.setTags(Set.of("innovative", "reliable", "os", "ai")); Company tesla = repository.save( - Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); + Company.of("Tesla", 2003, LocalDate.of(2022, 1, 1), new Point(-97.6208903, 30.2210767), "elon@tesla.com")); tesla.setTags(Set.of("innovative", "futuristic", "ai")); repository.saveAll(List.of(redis, microsoft, tesla)); @@ -56,7 +58,7 @@ void cleanUp() { // users userRepository.deleteAll(); List users = List.of(User.of("Steve Lorello", .9999), User.of("Nava Levy", 1234.5678), - User.of("Savannah Norem", 999.99), User.of("Suze Shardlow", 899.0)); + User.of("Savannah Norem", 999.99), User.of("Suze Shardlow", 899.0)); for (User user : users) { user.setRoles(List.of("devrel", "educator", "guru")); } @@ -102,11 +104,11 @@ void testCloseHandlerIsNullOnWrapperSearchStream() { void testFilterOnWrapperSearchStream() { Predicate predicate = i -> (i > 2000); List foundedAfter2000 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .filter(predicate) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .filter(predicate) // + .collect(Collectors.toList()); assertThat(foundedAfter2000).contains(2011, 2003); } @@ -123,10 +125,10 @@ void testFlatMapToIntOnMappedField() { // actual IntStream tagLengthIntStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .sequential() // - .flatMapToInt(tags -> tags.stream().mapToInt(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .sequential() // + .flatMapToInt(tags -> tags.stream().mapToInt(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); @@ -145,10 +147,10 @@ void testFlatMapToLongOnMappedField() { // actual LongStream tagLengthIntStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .sequential() // - .flatMapToLong(tags -> tags.stream().mapToLong(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .sequential() // + .flatMapToLong(tags -> tags.stream().mapToLong(String::length)); List actual = tagLengthIntStream.boxed().collect(Collectors.toList()); @@ -167,10 +169,10 @@ void testFlatMapToDoubleOnMappedField() { // actual DoubleStream tagLengthDoubleStream = entityStream // - .of(Company.class) // - .map(Company$.TAGS) // - .sequential() // - .flatMapToDouble(tags -> tags.stream().mapToDouble(String::length)); + .of(Company.class) // + .map(Company$.TAGS) // + .sequential() // + .flatMapToDouble(tags -> tags.stream().mapToDouble(String::length)); List actual = tagLengthDoubleStream.boxed().collect(Collectors.toList()); @@ -180,10 +182,10 @@ void testFlatMapToDoubleOnMappedField() { @Test void testMapToIntOnReturnFields() { IntStream intStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .mapToInt(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .mapToInt(i -> i); assertThat(intStream.boxed().collect(Collectors.toList())).contains(2011, 1975, 2003); } @@ -191,10 +193,10 @@ void testMapToIntOnReturnFields() { @Test void testMapToLongOnReturnFields() { LongStream longStream = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .mapToLong(i -> i); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .mapToLong(i -> i); assertThat(longStream.boxed().collect(Collectors.toList())).contains(2011L, 1975L, 2003L); } @@ -202,10 +204,10 @@ void testMapToLongOnReturnFields() { @Test void testMapToDoubleOnReturnFields() { DoubleStream doubleStream = entityStream // - .of(User.class) // - .map(User$.LOTTERY_WINNINGS) // - .sequential() // - .mapToDouble(w -> w); + .of(User.class) // + .map(User$.LOTTERY_WINNINGS) // + .sequential() // + .mapToDouble(w -> w); assertThat(doubleStream.boxed().collect(Collectors.toList())).contains(.9999, 1234.5678, 999.99, 899.0); } @@ -215,10 +217,10 @@ void testForEachOrderedOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .forEachOrdered(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .forEachOrdered(testConsumer); assertEquals(3, names.size()); @@ -232,10 +234,10 @@ void testForEachOnMappedField() { List names = new ArrayList<>(); Consumer testConsumer = names::add; entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .forEach(testConsumer); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .forEach(testConsumer); assertEquals(3, names.size()); @@ -247,10 +249,10 @@ void testForEachOnMappedField() { @Test void testToArrayOnMappedField() { Object[] allCompanies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .toArray(); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .toArray(); assertEquals(3, allCompanies.length); @@ -264,10 +266,10 @@ void testToArrayOnMappedField() { @Test void testToArrayTypedOnMappedField() { String[] namesArray = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .toArray(String[]::new); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .toArray(String[]::new); assertEquals(3, namesArray.length); @@ -280,14 +282,14 @@ void testToArrayTypedOnMappedField() { @Test void testCountOnMappedField() { long count = entityStream // - .of(Company.class) // - .filter( // - Company$.NAME.notEq("RedisInc") // - .and(Company$.NAME.notEq("Microsoft")) // - ) // - .map(Company$.NAME) // - .sequential() // - .count(); + .of(Company.class) // + .filter( // + Company$.NAME.notEq("RedisInc") // + .and(Company$.NAME.notEq("Microsoft")) // + ) // + .map(Company$.NAME) // + .sequential() // + .count(); assertEquals(1, count); } @@ -295,11 +297,11 @@ void testCountOnMappedField() { @Test void testLimitOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .limit(2) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .limit(2) // + .collect(Collectors.toList()); assertEquals(2, companies.size()); } @@ -307,11 +309,11 @@ void testLimitOnMappedField() { @Test void testSkipOnMappedField() { List companies = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .skip(1) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .skip(1) // + .collect(Collectors.toList()); assertEquals(2, companies.size()); } @@ -319,11 +321,11 @@ void testSkipOnMappedField() { @Test void testSortOnMappedField() { List names = entityStream // - .of(Company.class) // - .map(Company$.NAME) // - .sequential() // - .sorted(Comparator.reverseOrder()) // - .collect(Collectors.toList()); + .of(Company.class) // + .map(Company$.NAME) // + .sequential() // + .sorted(Comparator.reverseOrder()) // + .collect(Collectors.toList()); assertEquals(3, names.size()); @@ -336,12 +338,12 @@ void testSortOnMappedField() { void testPeekOnMappedField() { final List peekedEmails = new ArrayList<>(); List emails = entityStream // - .of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .sequential() // - .peek(peekedEmails::add) // - .collect(Collectors.toList()); + .of(Company.class) // + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .sequential() // + .peek(peekedEmails::add) // + .collect(Collectors.toList()); assertThat(peekedEmails).containsExactly("stack@redis.com"); @@ -351,10 +353,10 @@ void testPeekOnMappedField() { @Test void testFindFirstOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .sequential() // - .findFirst(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .sequential() // + .findFirst(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); @@ -363,10 +365,10 @@ void testFindFirstOnMappedField() { @Test void testFindAnyOnMappedField() { Optional maybeEmail = entityStream.of(Company.class) // - .filter(Company$.NAME.eq("RedisInc")) // - .map(Company$.EMAIL) // - .sequential() // - .findAny(); + .filter(Company$.NAME.eq("RedisInc")) // + .map(Company$.EMAIL) // + .sequential() // + .findAny(); assertTrue(maybeEmail.isPresent()); assertEquals("stack@redis.com", maybeEmail.get()); @@ -375,10 +377,10 @@ void testFindAnyOnMappedField() { @Test void testReduceWithMethodReferenceOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } @@ -386,10 +388,10 @@ void testReduceWithMethodReferenceOnMappedField() { @Test void testReduceWithLambdaOnMappedField() { int result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .reduce(0, (t, u) -> Integer.sum(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .reduce(0, (t, u) -> Integer.sum(t, u)); assertThat(result).isEqualTo(2011 + 1975 + 2003); } @@ -399,24 +401,24 @@ void testReduceWithCombinerOnMappedField() { BinaryOperator establishedFirst = (c1, c2) -> c1 < c2 ? c1 : c2; Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .reduce(establishedFirst); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .reduce(establishedFirst); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } @Test void testReduceWithIdentityBifunctionAndBinaryOperatorOnMappedField() { Integer firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .reduce(Integer.MAX_VALUE, (t, u) -> Integer.min(t, u), (t, u) -> Integer.min(t, u)); assertThat(firstEstablish).isEqualTo(1975); } @@ -428,10 +430,10 @@ void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { BiConsumer combiner = (a1, a2) -> a1.set(a1.get() + a2.get()); AtomicInteger result = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .collect(supplier, accumulator, combiner); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .collect(supplier, accumulator, combiner); assertThat(result.intValue()).isEqualTo(2011 + 1975 + 2003); } @@ -439,42 +441,42 @@ void testCollectWithSupplierAccumulatorAndCombinerOnMappedField() { @Test void testMinOnMappedField() { Optional firstEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .min(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .min(Integer::compareTo); assertAll( // - () -> assertThat(firstEstablish).isPresent(), // - () -> assertThat(firstEstablish).contains(1975) // + () -> assertThat(firstEstablish).isPresent(), // + () -> assertThat(firstEstablish).contains(1975) // ); } @Test void testMaxOnMappedField() { Optional lastEstablish = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .max(Integer::compareTo); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .max(Integer::compareTo); assertAll( // - () -> assertThat(lastEstablish).isPresent(), // - () -> assertThat(lastEstablish).contains(2011) // + () -> assertThat(lastEstablish).isPresent(), // + () -> assertThat(lastEstablish).contains(2011) // ); } @Test void testAnyMatchOnMappedField() { boolean c1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .anyMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .anyMatch(c -> c == 1975); boolean c1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .anyMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .anyMatch(c -> c == 1976); assertThat(c1975).isTrue(); assertThat(c1976).isFalse(); @@ -483,16 +485,16 @@ void testAnyMatchOnMappedField() { @Test void testAllMatchOnMappedField() { boolean allEstablishedBefore1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .allMatch(c -> c < 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .allMatch(c -> c < 1970); boolean allEstablishedOnOrAfter1970 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .allMatch(c -> c >= 1970); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .allMatch(c -> c >= 1970); assertThat(allEstablishedOnOrAfter1970).isTrue(); assertThat(allEstablishedBefore1970).isFalse(); @@ -501,16 +503,16 @@ void testAllMatchOnMappedField() { @Test void testNoneMatchOnMappedField() { boolean noneIn1975 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .noneMatch(c -> c == 1975); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .noneMatch(c -> c == 1975); boolean noneIn1976 = entityStream // - .of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .noneMatch(c -> c == 1976); + .of(Company.class) // + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .noneMatch(c -> c == 1976); assertThat(noneIn1976).isTrue(); assertThat(noneIn1975).isFalse(); @@ -521,14 +523,14 @@ void testMapOnMappedField() { ToLongFunction func = y -> y - 1; List yearsMinusOne = entityStream.of(Company.class) // - .map(Company$.YEAR_FOUNDED) // - .sequential() // - .map(func) // - .collect(Collectors.toList()); + .map(Company$.YEAR_FOUNDED) // + .sequential() // + .map(func) // + .collect(Collectors.toList()); assertAll( // - () -> assertThat(yearsMinusOne).hasSize(3), // - () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // + () -> assertThat(yearsMinusOne).hasSize(3), // + () -> assertThat(yearsMinusOne).containsExactly(2010L, 1974L, 2002L) // ); } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/FieldsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/FieldsTest.java index fa828069..ac823093 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/FieldsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/FieldsTest.java @@ -6,7 +6,8 @@ import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("SpellCheckingInspection") class FieldsTest { +@SuppressWarnings("SpellCheckingInspection") +class FieldsTest { @Test void testFieldsOf() { Function f = (Integer i) -> i * 2; @@ -18,67 +19,67 @@ void testFieldsOf() { Function> fQuad = Fields.of(f, f, f, f); Function> fQuintuple = Fields.of(f, f, f, f, f); Function // - > fHextuple = Fields.of(f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer> // + > fHextuple = Fields.of(f, f, f, f, f, f); Function // - > fSeptuple = Fields.of(f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fSeptuple = Fields.of(f, f, f, f, f, f, f); Function // - > fOctuple = Fields.of(f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fOctuple = Fields.of(f, f, f, f, f, f, f, f); Function // - > fNonuple = Fields.of(f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fNonuple = Fields.of(f, f, f, f, f, f, f, f, f); Function // - > fDecuple = Fields.of(f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fDecuple = Fields.of(f, f, f, f, f, f, f, f, f, f); Function // - > fUndecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fUndecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f); Function // - > fDuodecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer> // + > fDuodecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fTredecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer> // + > fTredecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fQuattuordecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer> // + > fQuattuordecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fQuindecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer> // + > fQuindecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fSexdecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer> // + > fSexdecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fSeptendecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer> // + > fSeptendecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fOctodecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer> // + > fOctodecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fNovemdecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fNovemdecuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); Function // - > fVigintuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, // + Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> // + > fVigintuple = Fields.of(f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f); assertThat(fEmpty.apply(0).streamOf(Integer.class)).isEmpty(); assertThat(fSingle.apply(2).streamOf(Integer.class)).containsExactly(4); @@ -92,24 +93,24 @@ void testFieldsOf() { assertThat(fNonuple.apply(10).streamOf(Integer.class)).containsExactly(20, 20, 20, 20, 20, 20, 20, 20, 20); assertThat(fDecuple.apply(11).streamOf(Integer.class)).containsExactly(22, 22, 22, 22, 22, 22, 22, 22, 22, 22); assertThat(fUndecuple.apply(12).streamOf(Integer.class)).containsExactly(24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24); + 24); assertThat(fDuodecuple.apply(13).streamOf(Integer.class)).containsExactly(26, 26, 26, 26, 26, 26, 26, 26, 26, 26, - 26, 26); + 26, 26); assertThat(fTredecuple.apply(14).streamOf(Integer.class)).containsExactly(28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, 28); + 28, 28, 28); assertThat(fQuattuordecuple.apply(15).streamOf(Integer.class)).containsExactly(30, 30, 30, 30, 30, 30, 30, 30, 30, - 30, 30, 30, 30, 30); + 30, 30, 30, 30, 30); assertThat(fQuindecuple.apply(16).streamOf(Integer.class)).containsExactly(32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 32, 32, 32, 32, 32); + 32, 32, 32, 32, 32); assertThat(fSexdecuple.apply(17).streamOf(Integer.class)).containsExactly(34, 34, 34, 34, 34, 34, 34, 34, 34, 34, - 34, 34, 34, 34, 34, 34); + 34, 34, 34, 34, 34, 34); assertThat(fSeptendecuple.apply(18).streamOf(Integer.class)).containsExactly(36, 36, 36, 36, 36, 36, 36, 36, 36, 36, - 36, 36, 36, 36, 36, 36, 36); + 36, 36, 36, 36, 36, 36, 36); assertThat(fOctodecuple.apply(19).streamOf(Integer.class)).containsExactly(38, 38, 38, 38, 38, 38, 38, 38, 38, 38, - 38, 38, 38, 38, 38, 38, 38, 38); + 38, 38, 38, 38, 38, 38, 38, 38); assertThat(fNovemdecuple.apply(20).streamOf(Integer.class)).containsExactly(40, 40, 40, 40, 40, 40, 40, 40, 40, 40, - 40, 40, 40, 40, 40, 40, 40, 40, 40); + 40, 40, 40, 40, 40, 40, 40, 40, 40); assertThat(fVigintuple.apply(21).streamOf(Integer.class)).containsExactly(42, 42, 42, 42, 42, 42, 42, 42, 42, 42, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42); + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TupleTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TupleTest.java index 71ab2b6d..9729971c 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TupleTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TupleTest.java @@ -11,8 +11,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings("SpellCheckingInspection") final class TupleTest { - +@SuppressWarnings("SpellCheckingInspection") +final class TupleTest { + @Test void empty() { final EmptyTuple tuple = Tuples.of(); @@ -34,11 +35,13 @@ void pair() { final Pair tuple = Tuples.of(0, 1); tupleTest(tuple); final Pair defaultTuple = new Pair<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } }; @@ -50,15 +53,18 @@ void triple() { final Triple tuple = Tuples.of(0, 1, 2); tupleTest(tuple); final Triple defaultTuple = new Triple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } }; @@ -70,19 +76,23 @@ void quad() { final Quad tuple = Tuples.of(0, 1, 2, 3); tupleTest(tuple); final Quad defaultTuple = new Quad<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } }; @@ -94,23 +104,28 @@ void quintuple() { final Quintuple tuple = Tuples.of(0, 1, 2, 3, 4); tupleTest(tuple); final Quintuple defaultTuple = new Quintuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } }; @@ -122,27 +137,33 @@ void hextuple() { final Hextuple tuple = Tuples.of(0, 1, 2, 3, 4, 5); tupleTest(tuple); final Hextuple defaultTuple = new Hextuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } }; @@ -152,34 +173,41 @@ void hextuple() { @Test void septuple() { final Septuple tuple = Tuples.of(0, 1, 2, 3, 4, 5, - 6); + 6); tupleTest(tuple); final Septuple defaultTuple = new Septuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } }; @@ -189,38 +217,46 @@ void septuple() { @Test void octuple() { final Octuple tuple = Tuples.of(0, 1, 2, 3, - 4, 5, 6, 7); + 4, 5, 6, 7); tupleTest(tuple); final Octuple defaultTuple = new Octuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } }; @@ -230,42 +266,51 @@ void octuple() { @Test void nonuple() { final Nonuple tuple = Tuples.of(0, - 1, 2, 3, 4, 5, 6, 7, 8); + 1, 2, 3, 4, 5, 6, 7, 8); tupleTest(tuple); final Nonuple defaultTuple = new Nonuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } }; @@ -274,47 +319,57 @@ void nonuple() { @Test void decuple() { - final Decuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + final Decuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); tupleTest(tuple); final Decuple defaultTuple = new Decuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } }; @@ -323,51 +378,62 @@ void decuple() { @Test void undecuple() { - final Undecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + final Undecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); tupleTest(tuple); final Undecuple defaultTuple = new Undecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } }; @@ -376,55 +442,67 @@ void undecuple() { @Test void duodecuple() { - final Duodecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + final Duodecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); tupleTest(tuple); final Duodecuple defaultTuple = new Duodecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } }; @@ -433,59 +511,72 @@ void duodecuple() { @Test void tredecuple() { - final Tredecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + final Tredecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); tupleTest(tuple); final Tredecuple defaultTuple = new Tredecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } }; @@ -494,63 +585,77 @@ void tredecuple() { @Test void quattuordecuple() { - final Quattuordecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); + final Quattuordecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); tupleTest(tuple); final Quattuordecuple defaultTuple = new Quattuordecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } }; @@ -559,67 +664,82 @@ void quattuordecuple() { @Test void quindecuple() { - final Quindecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); + final Quindecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); tupleTest(tuple); final Quindecuple defaultTuple = new Quindecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } }; @@ -628,71 +748,87 @@ void quindecuple() { @Test void sexdecuple() { - final Sexdecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + final Sexdecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); tupleTest(tuple); final Sexdecuple defaultTuple = new Sexdecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } - @Override public Integer getSixteenth() { + @Override + public Integer getSixteenth() { return 15; } }; @@ -701,75 +837,92 @@ void sexdecuple() { @Test void septendecuple() { - final Septendecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + final Septendecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); tupleTest(tuple); final Septendecuple defaultTuple = new Septendecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } - @Override public Integer getSixteenth() { + @Override + public Integer getSixteenth() { return 15; } - @Override public Integer getSeventeenth() { + @Override + public Integer getSeventeenth() { return 16; } }; @@ -778,79 +931,97 @@ void septendecuple() { @Test void octodecuple() { - final Octodecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17); + final Octodecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17); tupleTest(tuple); final Octodecuple defaultTuple = new Octodecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } - @Override public Integer getSixteenth() { + @Override + public Integer getSixteenth() { return 15; } - @Override public Integer getSeventeenth() { + @Override + public Integer getSeventeenth() { return 16; } - @Override public Integer getEighteenth() { + @Override + public Integer getEighteenth() { return 17; } }; @@ -859,83 +1030,102 @@ void octodecuple() { @Test void novemdecuple() { - final Novemdecuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18); + final Novemdecuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18); tupleTest(tuple); final Novemdecuple defaultTuple = new Novemdecuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } - @Override public Integer getSixteenth() { + @Override + public Integer getSixteenth() { return 15; } - @Override public Integer getSeventeenth() { + @Override + public Integer getSeventeenth() { return 16; } - @Override public Integer getEighteenth() { + @Override + public Integer getEighteenth() { return 17; } - @Override public Integer getNineteenth() { + @Override + public Integer getNineteenth() { return 18; } }; @@ -944,87 +1134,107 @@ void novemdecuple() { @Test void vigintuple() { - final Vigintuple tuple = Tuples - .of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19); + final Vigintuple tuple = Tuples.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19); tupleTest(tuple); final Vigintuple defaultTuple = new Vigintuple<>() { - @Override public Integer getFirst() { + @Override + public Integer getFirst() { return 0; } - @Override public Integer getSecond() { + @Override + public Integer getSecond() { return 1; } - @Override public Integer getThird() { + @Override + public Integer getThird() { return 2; } - @Override public Integer getFourth() { + @Override + public Integer getFourth() { return 3; } - @Override public Integer getFifth() { + @Override + public Integer getFifth() { return 4; } - @Override public Integer getSixth() { + @Override + public Integer getSixth() { return 5; } - @Override public Integer getSeventh() { + @Override + public Integer getSeventh() { return 6; } - @Override public Integer getEighth() { + @Override + public Integer getEighth() { return 7; } - @Override public Integer getNinth() { + @Override + public Integer getNinth() { return 8; } - @Override public Integer getTenth() { + @Override + public Integer getTenth() { return 9; } - @Override public Integer getEleventh() { + @Override + public Integer getEleventh() { return 10; } - @Override public Integer getTwelfth() { + @Override + public Integer getTwelfth() { return 11; } - @Override public Integer getThirteenth() { + @Override + public Integer getThirteenth() { return 12; } - @Override public Integer getFourteenth() { + @Override + public Integer getFourteenth() { return 13; } - @Override public Integer getFifteenth() { + @Override + public Integer getFifteenth() { return 14; } - @Override public Integer getSixteenth() { + @Override + public Integer getSixteenth() { return 15; } - @Override public Integer getSeventeenth() { + @Override + public Integer getSeventeenth() { return 16; } - @Override public Integer getEighteenth() { + @Override + public Integer getEighteenth() { return 17; } - @Override public Integer getNineteenth() { + @Override + public Integer getNineteenth() { return 18; } - @Override public Integer getTwentieth() { + @Override + public Integer getTwentieth() { return 19; } }; @@ -1092,16 +1302,11 @@ private void tupleTest(final Quad tuple) { } private void tupleTest(final Quintuple tuple) { - final FirstAccessor, Integer> getter0 = Quintuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Quintuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Quintuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Quintuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Quintuple - .getFifthGetter(); + final FirstAccessor, Integer> getter0 = Quintuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Quintuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Quintuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Quintuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Quintuple.getFifthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1122,18 +1327,12 @@ private void tupleTest(final Quintuple tuple) { - final FirstAccessor, Integer> getter0 = Hextuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Hextuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Hextuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Hextuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Hextuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Hextuple - .getSixthGetter(); + final FirstAccessor, Integer> getter0 = Hextuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Hextuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Hextuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Hextuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Hextuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Hextuple.getSixthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1157,20 +1356,13 @@ private void tupleTest(final Hextuple tuple) { - final FirstAccessor, Integer> getter0 = Septuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Septuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Septuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Septuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Septuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Septuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Septuple - .getSeventhGetter(); + final FirstAccessor, Integer> getter0 = Septuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Septuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Septuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Septuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Septuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Septuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Septuple.getSeventhGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1197,22 +1389,14 @@ private void tupleTest(final Septuple tuple) { - final FirstAccessor, Integer> getter0 = Octuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Octuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Octuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Octuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Octuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Octuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Octuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Octuple - .getEighthGetter(); + final FirstAccessor, Integer> getter0 = Octuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Octuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Octuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Octuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Octuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Octuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Octuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Octuple.getEighthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1242,25 +1426,16 @@ private void tupleTest(final Octuple tuple) { - final FirstAccessor, Integer> getter0 = Nonuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Nonuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Nonuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Nonuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Nonuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Nonuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Nonuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Nonuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Nonuple - .getNinthGetter(); + final Nonuple tuple) { + final FirstAccessor, Integer> getter0 = Nonuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Nonuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Nonuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Nonuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Nonuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Nonuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Nonuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Nonuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Nonuple.getNinthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1293,27 +1468,17 @@ private void tupleTest( } private void tupleTest( - final Decuple tuple) { - final FirstAccessor, Integer> getter0 = Decuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Decuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Decuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Decuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Decuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Decuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Decuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Decuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Decuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Decuple - .getTenthGetter(); + final Decuple tuple) { + final FirstAccessor, Integer> getter0 = Decuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Decuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Decuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Decuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Decuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Decuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Decuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Decuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Decuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Decuple.getTenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1349,29 +1514,18 @@ private void tupleTest( } private void tupleTest( - final Undecuple tuple) { - final FirstAccessor, Integer> getter0 = Undecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Undecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Undecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Undecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Undecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Undecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Undecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Undecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Undecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Undecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Undecuple - .getEleventhGetter(); + final Undecuple tuple) { + final FirstAccessor, Integer> getter0 = Undecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Undecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Undecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Undecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Undecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Undecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Undecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Undecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Undecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Undecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Undecuple.getEleventhGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1410,31 +1564,19 @@ private void tupleTest( } private void tupleTest( - final Duodecuple tuple) { - final FirstAccessor, Integer> getter0 = Duodecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Duodecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Duodecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Duodecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Duodecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Duodecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Duodecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Duodecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Duodecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Duodecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Duodecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Duodecuple - .getTwelfthGetter(); + final Duodecuple tuple) { + final FirstAccessor, Integer> getter0 = Duodecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Duodecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Duodecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Duodecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Duodecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Duodecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Duodecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Duodecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Duodecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Duodecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Duodecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Duodecuple.getTwelfthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1476,33 +1618,20 @@ private void tupleTest( } private void tupleTest( - final Tredecuple tuple) { - final FirstAccessor, Integer> getter0 = Tredecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Tredecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Tredecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Tredecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Tredecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Tredecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Tredecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Tredecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Tredecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Tredecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Tredecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Tredecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Tredecuple - .getThirteenthGetter(); + final Tredecuple tuple) { + final FirstAccessor, Integer> getter0 = Tredecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Tredecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Tredecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Tredecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Tredecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Tredecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Tredecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Tredecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Tredecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Tredecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Tredecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Tredecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Tredecuple.getThirteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1547,35 +1676,21 @@ private void tupleTest( } private void tupleTest( - final Quattuordecuple tuple) { - final FirstAccessor, Integer> getter0 = Quattuordecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Quattuordecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Quattuordecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Quattuordecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Quattuordecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Quattuordecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Quattuordecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Quattuordecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Quattuordecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Quattuordecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Quattuordecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Quattuordecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Quattuordecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Quattuordecuple - .getFourteenthGetter(); + final Quattuordecuple tuple) { + final FirstAccessor, Integer> getter0 = Quattuordecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Quattuordecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Quattuordecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Quattuordecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Quattuordecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Quattuordecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Quattuordecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Quattuordecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Quattuordecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Quattuordecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Quattuordecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Quattuordecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Quattuordecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Quattuordecuple.getFourteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1623,37 +1738,22 @@ private void tupleTest( } private void tupleTest( - final Quindecuple tuple) { - final FirstAccessor, Integer> getter0 = Quindecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Quindecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Quindecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Quindecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Quindecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Quindecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Quindecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Quindecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Quindecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Quindecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Quindecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Quindecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Quindecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Quindecuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Quindecuple - .getFifteenthGetter(); + final Quindecuple tuple) { + final FirstAccessor, Integer> getter0 = Quindecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Quindecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Quindecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Quindecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Quindecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Quindecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Quindecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Quindecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Quindecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Quindecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Quindecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Quindecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Quindecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Quindecuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Quindecuple.getFifteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1704,39 +1804,23 @@ private void tupleTest( } private void tupleTest( - final Sexdecuple tuple) { - final FirstAccessor, Integer> getter0 = Sexdecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Sexdecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Sexdecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Sexdecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Sexdecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Sexdecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Sexdecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Sexdecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Sexdecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Sexdecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Sexdecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Sexdecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Sexdecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Sexdecuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Sexdecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> getter15 = Sexdecuple - .getSixteenthGetter(); + final Sexdecuple tuple) { + final FirstAccessor, Integer> getter0 = Sexdecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Sexdecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Sexdecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Sexdecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Sexdecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Sexdecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Sexdecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Sexdecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Sexdecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Sexdecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Sexdecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Sexdecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Sexdecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Sexdecuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Sexdecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> getter15 = Sexdecuple.getSixteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1790,41 +1874,24 @@ private void tupleTest( } private void tupleTest( - final Septendecuple tuple) { - final FirstAccessor, Integer> getter0 = Septendecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Septendecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Septendecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Septendecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Septendecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Septendecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Septendecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Septendecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Septendecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Septendecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Septendecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Septendecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Septendecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Septendecuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Septendecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> getter15 = Septendecuple - .getSixteenthGetter(); - final SeventeenthAccessor, Integer> getter16 = Septendecuple - .getSeventeenthGetter(); + final Septendecuple tuple) { + final FirstAccessor, Integer> getter0 = Septendecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Septendecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Septendecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Septendecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Septendecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Septendecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Septendecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Septendecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Septendecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Septendecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Septendecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Septendecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Septendecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Septendecuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Septendecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> getter15 = Septendecuple.getSixteenthGetter(); + final SeventeenthAccessor, Integer> getter16 = Septendecuple.getSeventeenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1881,43 +1948,25 @@ private void tupleTest( } private void tupleTest( - final Octodecuple tuple) { - final FirstAccessor, Integer> getter0 = Octodecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Octodecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Octodecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Octodecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Octodecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Octodecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Octodecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Octodecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Octodecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Octodecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Octodecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Octodecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Octodecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Octodecuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Octodecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> getter15 = Octodecuple - .getSixteenthGetter(); - final SeventeenthAccessor, Integer> getter16 = Octodecuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> getter17 = Octodecuple - .getEighteenthGetter(); + final Octodecuple tuple) { + final FirstAccessor, Integer> getter0 = Octodecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Octodecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Octodecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Octodecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Octodecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Octodecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Octodecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Octodecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Octodecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Octodecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Octodecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Octodecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Octodecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Octodecuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Octodecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> getter15 = Octodecuple.getSixteenthGetter(); + final SeventeenthAccessor, Integer> getter16 = Octodecuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> getter17 = Octodecuple.getEighteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -1977,45 +2026,26 @@ private void tupleTest( } private void tupleTest( - final Novemdecuple tuple) { - final FirstAccessor, Integer> getter0 = Novemdecuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Novemdecuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Novemdecuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Novemdecuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Novemdecuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Novemdecuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Novemdecuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Novemdecuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Novemdecuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Novemdecuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Novemdecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Novemdecuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Novemdecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Novemdecuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Novemdecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> getter15 = Novemdecuple - .getSixteenthGetter(); - final SeventeenthAccessor, Integer> getter16 = Novemdecuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> getter17 = Novemdecuple - .getEighteenthGetter(); - final NineteenthAccessor, Integer> getter18 = Novemdecuple - .getNineteenthGetter(); + final Novemdecuple tuple) { + final FirstAccessor, Integer> getter0 = Novemdecuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Novemdecuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Novemdecuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Novemdecuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Novemdecuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Novemdecuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Novemdecuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Novemdecuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Novemdecuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Novemdecuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Novemdecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Novemdecuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Novemdecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Novemdecuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Novemdecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> getter15 = Novemdecuple.getSixteenthGetter(); + final SeventeenthAccessor, Integer> getter16 = Novemdecuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> getter17 = Novemdecuple.getEighteenthGetter(); + final NineteenthAccessor, Integer> getter18 = Novemdecuple.getNineteenthGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -2078,47 +2108,27 @@ private void tupleTest( } private void tupleTest( - final Vigintuple tuple) { - final FirstAccessor, Integer> getter0 = Vigintuple - .getFirstGetter(); - final SecondAccessor, Integer> getter1 = Vigintuple - .getSecondGetter(); - final ThirdAccessor, Integer> getter2 = Vigintuple - .getThirdGetter(); - final FourthAccessor, Integer> getter3 = Vigintuple - .getFourthGetter(); - final FifthAccessor, Integer> getter4 = Vigintuple - .getFifthGetter(); - final SixthAccessor, Integer> getter5 = Vigintuple - .getSixthGetter(); - final SeventhAccessor, Integer> getter6 = Vigintuple - .getSeventhGetter(); - final EighthAccessor, Integer> getter7 = Vigintuple - .getEighthGetter(); - final NinthAccessor, Integer> getter8 = Vigintuple - .getNinthGetter(); - final TenthAccessor, Integer> getter9 = Vigintuple - .getTenthGetter(); - final EleventhAccessor, Integer> getter10 = Vigintuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> getter11 = Vigintuple - .getTwelfthGetter(); - final ThirteenthAccessor, Integer> getter12 = Vigintuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> getter13 = Vigintuple - .getFourteenthGetter(); - final FifteenthAccessor, Integer> getter14 = Vigintuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> getter15 = Vigintuple - .getSixteenthGetter(); - final SeventeenthAccessor, Integer> getter16 = Vigintuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> getter17 = Vigintuple - .getEighteenthGetter(); - final NineteenthAccessor, Integer> getter18 = Vigintuple - .getNineteenthGetter(); - final TwentiethAccessor, Integer> getter19 = Vigintuple - .getTwentiethGetter(); + final Vigintuple tuple) { + final FirstAccessor, Integer> getter0 = Vigintuple.getFirstGetter(); + final SecondAccessor, Integer> getter1 = Vigintuple.getSecondGetter(); + final ThirdAccessor, Integer> getter2 = Vigintuple.getThirdGetter(); + final FourthAccessor, Integer> getter3 = Vigintuple.getFourthGetter(); + final FifthAccessor, Integer> getter4 = Vigintuple.getFifthGetter(); + final SixthAccessor, Integer> getter5 = Vigintuple.getSixthGetter(); + final SeventhAccessor, Integer> getter6 = Vigintuple.getSeventhGetter(); + final EighthAccessor, Integer> getter7 = Vigintuple.getEighthGetter(); + final NinthAccessor, Integer> getter8 = Vigintuple.getNinthGetter(); + final TenthAccessor, Integer> getter9 = Vigintuple.getTenthGetter(); + final EleventhAccessor, Integer> getter10 = Vigintuple.getEleventhGetter(); + final TwelfthAccessor, Integer> getter11 = Vigintuple.getTwelfthGetter(); + final ThirteenthAccessor, Integer> getter12 = Vigintuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> getter13 = Vigintuple.getFourteenthGetter(); + final FifteenthAccessor, Integer> getter14 = Vigintuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> getter15 = Vigintuple.getSixteenthGetter(); + final SeventeenthAccessor, Integer> getter16 = Vigintuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> getter17 = Vigintuple.getEighteenthGetter(); + final NineteenthAccessor, Integer> getter18 = Vigintuple.getNineteenthGetter(); + final TwentiethAccessor, Integer> getter19 = Vigintuple.getTwentiethGetter(); assertEquals(0, getter0.index()); assertEquals(1, getter1.index()); assertEquals(2, getter2.index()); @@ -2189,13 +2199,13 @@ private void tupleTest( @Test void testTuplesStream() { - final Vigintuple vigintuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3, "waldo", 4, "fred", 5); + final Vigintuple vigintuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3, + "waldo", 4, "fred", 5); List parts = vigintuple.stream().collect(Collectors.toList()); assertThat(parts).containsExactly(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, - 1, "grault", 2, "garply", 3, "waldo", 4, "fred", 5); + 1, "grault", 2, "garply", 3, "waldo", 4, "fred", 5); } @Test @@ -2212,18 +2222,19 @@ void testTuplesEqualsAndHashcode() { final Triple anotherTriple = Tuples.of(0, 1, 42); assertAll( // - () -> assertThat(oneTriple).hasSameHashCodeAs(anotherTriple), // - () -> assertThat(oneTriple).isEqualTo(anotherTriple) // + () -> assertThat(oneTriple).hasSameHashCodeAs(anotherTriple), // + () -> assertThat(oneTriple).isEqualTo(anotherTriple) // ); } - @Test void testTuplesEqualsWithBasicTuple() { + @Test + void testTuplesEqualsWithBasicTuple() { final Triple oneTriple = Tuples.of(0, 1, 42); assertThat(oneTriple) // - .isNotNull() // - .isEqualTo(oneTriple) // - .isEqualTo(Tuples.of(0, 1, 42) // - ); + .isNotNull() // + .isEqualTo(oneTriple) // + .isEqualTo(Tuples.of(0, 1, 42) // + ); } @Test @@ -2244,18 +2255,18 @@ void testTupleLabels() { Map labelledMap = pair.labelledMap(); assertThat(labelledMap) // - .containsEntry("lastName", "Jordan") // - .containsEntry("number", 23); + .containsEntry("lastName", "Jordan") // + .containsEntry("number", 23); } - + @Test void testTupleEquality() { final Pair pair = Tuples.of(new String[] { "lastName", "number" }, "Jordan", 23); final Pair other = Tuples.of(new String[] { "lastName", "number" }, "Jordan", 23); assertThat(pair) // - .isEqualTo(other) // - .isNotEqualTo(null) // - .isNotEqualTo("foo"); + .isEqualTo(other) // + .isNotEqualTo(null) // + .isNotEqualTo("foo"); } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TuplesTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TuplesTest.java index 8471f3be..ef60c46e 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TuplesTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/tuple/TuplesTest.java @@ -14,7 +14,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings("SpellCheckingInspection") final class TuplesTest { +@SuppressWarnings("SpellCheckingInspection") +final class TuplesTest { @Test void ofEmptyTuple() { @@ -56,8 +57,7 @@ void ofTriple() { @Test void toTriple() { - final Function> mapper = Tuples.toTuple(i -> i, i -> i + 1, - i -> i + 2); + final Function> mapper = Tuples.toTuple(i -> i, i -> i + 1, i -> i + 2); assertTuple(mapper.apply(0), 3); } @@ -69,7 +69,7 @@ void ofQuad() { @Test void toQuad() { final Function> mapper = Tuples.toTuple(i -> i, i -> i + 1, - i -> i + 2, i -> i + 3); + i -> i + 2, i -> i + 3); assertTuple(mapper.apply(0), 4); } @@ -81,7 +81,7 @@ void ofQuintuple() { @Test void toQuintuple() { final Function> mapper = Tuples.toTuple(i -> i, - i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4); + i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4); assertTuple(mapper.apply(0), 5); } @@ -92,8 +92,8 @@ void ofHextuple() { @Test void toHextuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5); assertTuple(mapper.apply(0), 6); } @@ -104,8 +104,8 @@ void ofSeptuple() { @Test void toSeptuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6); assertTuple(mapper.apply(0), 7); } @@ -116,8 +116,8 @@ void ofOctuple() { @Test void toOctuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7); assertTuple(mapper.apply(0), 8); } @@ -128,9 +128,8 @@ void ofNonuple() { @Test void toNonuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8); assertTuple(mapper.apply(0), 9); } @@ -141,9 +140,9 @@ void ofDecuple() { @Test void toDecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9); assertTuple(mapper.apply(0), 10); } @@ -154,9 +153,9 @@ void ofUndecuple() { @Test void toUndecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10); assertTuple(mapper.apply(0), 11); } @@ -167,9 +166,9 @@ void ofDuodecuple() { @Test void toDuodecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11); assertTuple(mapper.apply(0), 12); } @@ -180,9 +179,9 @@ void ofTredecuple() { @Test void toTredecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12); assertTuple(mapper.apply(0), 13); } @@ -193,9 +192,9 @@ void ofQuattuordecuple() { @Test void toQuattuordecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13); assertTuple(mapper.apply(0), 14); } @@ -206,9 +205,9 @@ void ofQuindecuple() { @Test void toQuindecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14); assertTuple(mapper.apply(0), 15); } @@ -219,9 +218,9 @@ void ofSexdecuple() { @Test void toSexdecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15); assertTuple(mapper.apply(0), 16); } @@ -232,10 +231,9 @@ void ofSeptendecuple() { @Test void toSeptendecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, - i -> i + 16); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, i -> i + 16); assertTuple(mapper.apply(0), 17); } @@ -246,10 +244,10 @@ void ofOctodecuple() { @Test void toOctodecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, - i -> i + 16, i -> i + 17); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, i -> i + 16, + i -> i + 17); assertTuple(mapper.apply(0), 18); } @@ -260,10 +258,10 @@ void ofNovemdecuple() { @Test void toNovemdecuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, - i -> i + 16, i -> i + 17, i -> i + 18); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, i -> i + 16, + i -> i + 17, i -> i + 18); assertTuple(mapper.apply(0), 19); } @@ -274,10 +272,10 @@ void ofVigintuple() { @Test void toVigintuple() { - final Function> mapper = Tuples - .toTuple(i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, - i -> i + 8, i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, - i -> i + 16, i -> i + 17, i -> i + 18, i -> i + 19); + final Function> mapper = Tuples.toTuple( + i -> i, i -> i + 1, i -> i + 2, i -> i + 3, i -> i + 4, i -> i + 5, i -> i + 6, i -> i + 7, i -> i + 8, + i -> i + 9, i -> i + 10, i -> i + 11, i -> i + 12, i -> i + 13, i -> i + 14, i -> i + 15, i -> i + 16, + i -> i + 17, i -> i + 18, i -> i + 19); assertTuple(mapper.apply(0), 20); } @@ -334,17 +332,12 @@ void testQuadGetters() { @Test void testQuintupleGetters() { final Quintuple quintuple = Tuples.of(0, 1, "Foobar", 42L, - BigInteger.ONE); - final FirstAccessor, Integer> firstGetter = Quintuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Quintuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Quintuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Quintuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Quintuple - .getFifthGetter(); + BigInteger.ONE); + final FirstAccessor, Integer> firstGetter = Quintuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Quintuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Quintuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Quintuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Quintuple.getFifthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -360,19 +353,13 @@ void testQuintupleGetters() { @Test void testHextupleGetters() { final Hextuple hextuple = Tuples.of(0, 1, "Foobar", 42L, - BigInteger.ONE, "qux"); - final FirstAccessor, Integer> firstGetter = Hextuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Hextuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Hextuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Hextuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Hextuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Hextuple - .getSixthGetter(); + BigInteger.ONE, "qux"); + final FirstAccessor, Integer> firstGetter = Hextuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Hextuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Hextuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Hextuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Hextuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Hextuple.getSixthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -390,21 +377,14 @@ void testHextupleGetters() { @Test void testSeptupleGetters() { final Septuple septuple = Tuples.of(0, 1, "Foobar", - 42L, BigInteger.ONE, "qux", 20); - final FirstAccessor, Integer> firstGetter = Septuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Septuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Septuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Septuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Septuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Septuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Septuple - .getSeventhGetter(); + 42L, BigInteger.ONE, "qux", 20); + final FirstAccessor, Integer> firstGetter = Septuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Septuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Septuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Septuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Septuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Septuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Septuple.getSeventhGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -424,23 +404,15 @@ void testSeptupleGetters() { @Test void testOctupleGetters() { final Octuple octuple = Tuples.of(0, 1, - "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN); - final FirstAccessor, Integer> firstGetter = Octuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Octuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Octuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Octuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Octuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Octuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Octuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Octuple - .getEighthGetter(); + "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN); + final FirstAccessor, Integer> firstGetter = Octuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Octuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Octuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Octuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Octuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Octuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Octuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Octuple.getEighthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -461,26 +433,17 @@ void testOctupleGetters() { @Test void testNonupleGetters() { - final Nonuple nonuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22); - final FirstAccessor, Integer> firstGetter = Nonuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Nonuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Nonuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Nonuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Nonuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Nonuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Nonuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Nonuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Nonuple - .getNinthGetter(); + final Nonuple nonuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22); + final FirstAccessor, Integer> firstGetter = Nonuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Nonuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Nonuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Nonuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Nonuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Nonuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Nonuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Nonuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Nonuple.getNinthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -503,28 +466,18 @@ void testNonupleGetters() { @Test void testDecupleGetters() { - final Decuple decuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge"); - final FirstAccessor, Integer> firstGetter = Decuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Decuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Decuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Decuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Decuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Decuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Decuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Decuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Decuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Decuple - .getTenthGetter(); + final Decuple decuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge"); + final FirstAccessor, Integer> firstGetter = Decuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Decuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Decuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Decuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Decuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Decuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Decuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Decuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Decuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Decuple.getTenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -549,30 +502,19 @@ void testDecupleGetters() { @Test void testUndecupleGetters() { - final Undecuple undecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L); - final FirstAccessor, Integer> firstGetter = Undecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Undecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Undecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Undecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Undecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Undecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Undecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Undecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Undecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Undecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Undecuple - .getEleventhGetter(); + final Undecuple undecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L); + final FirstAccessor, Integer> firstGetter = Undecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Undecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Undecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Undecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Undecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Undecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Undecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Undecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Undecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Undecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Undecuple.getEleventhGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -599,32 +541,20 @@ void testUndecupleGetters() { @Test void testDuodecupleGetters() { - final Duodecuple duodecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1); - final FirstAccessor, Integer> firstGetter = Duodecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Duodecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Duodecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Duodecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Duodecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Duodecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Duodecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Duodecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Duodecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Duodecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Duodecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Duodecuple - .getTwelfthGetter(); + final Duodecuple duodecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1); + final FirstAccessor, Integer> firstGetter = Duodecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Duodecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Duodecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Duodecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Duodecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Duodecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Duodecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Duodecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Duodecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Duodecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Duodecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Duodecuple.getTwelfthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -653,34 +583,21 @@ void testDuodecupleGetters() { @Test void testTredecupleGetters() { - final Tredecuple tredecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault"); - final FirstAccessor, Integer> firstGetter = Tredecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Tredecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Tredecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Tredecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Tredecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Tredecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Tredecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Tredecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Tredecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Tredecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Tredecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Tredecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Tredecuple - .getThirteenthGetter(); + final Tredecuple tredecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault"); + final FirstAccessor, Integer> firstGetter = Tredecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Tredecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Tredecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Tredecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Tredecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Tredecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Tredecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Tredecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Tredecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Tredecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Tredecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Tredecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Tredecuple.getThirteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -711,36 +628,22 @@ void testTredecupleGetters() { @Test void testQuattuordecupleGetters() { - final Quattuordecuple quattuordecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2); - final FirstAccessor, Integer> firstGetter = Quattuordecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Quattuordecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Quattuordecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Quattuordecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Quattuordecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Quattuordecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Quattuordecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Quattuordecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Quattuordecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Quattuordecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Quattuordecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Quattuordecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Quattuordecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Quattuordecuple - .getFourteenthGetter(); + final Quattuordecuple quattuordecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2); + final FirstAccessor, Integer> firstGetter = Quattuordecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Quattuordecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Quattuordecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Quattuordecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Quattuordecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Quattuordecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Quattuordecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Quattuordecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Quattuordecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Quattuordecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Quattuordecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Quattuordecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Quattuordecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Quattuordecuple.getFourteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -773,38 +676,23 @@ void testQuattuordecupleGetters() { @Test void testQuindecupleGetters() { - final Quindecuple quindecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply"); - final FirstAccessor, Integer> firstGetter = Quindecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Quindecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Quindecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Quindecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Quindecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Quindecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Quindecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Quindecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Quindecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Quindecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Quindecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Quindecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Quindecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Quindecuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Quindecuple - .getFifteenthGetter(); + final Quindecuple quindecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply"); + final FirstAccessor, Integer> firstGetter = Quindecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Quindecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Quindecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Quindecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Quindecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Quindecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Quindecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Quindecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Quindecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Quindecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Quindecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Quindecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Quindecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Quindecuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Quindecuple.getFifteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -839,41 +727,24 @@ void testQuindecupleGetters() { @Test void testSexdecupleGetters() { - final Sexdecuple sexdecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3); - final FirstAccessor, Integer> firstGetter = Sexdecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Sexdecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Sexdecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Sexdecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Sexdecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Sexdecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Sexdecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Sexdecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Sexdecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Sexdecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Sexdecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Sexdecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Sexdecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Sexdecuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Sexdecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> sixteenthGetter = Sexdecuple - .getSixteenthGetter(); + final Sexdecuple sexdecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3); + final FirstAccessor, Integer> firstGetter = Sexdecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Sexdecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Sexdecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Sexdecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Sexdecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Sexdecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Sexdecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Sexdecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Sexdecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Sexdecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Sexdecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Sexdecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Sexdecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Sexdecuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Sexdecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> sixteenthGetter = Sexdecuple.getSixteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -910,43 +781,26 @@ void testSexdecupleGetters() { @Test void testSeptendecupleGetters() { - final Septendecuple septendecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3, "waldo"); - final FirstAccessor, Integer> firstGetter = Septendecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Septendecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Septendecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Septendecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Septendecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Septendecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Septendecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Septendecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Septendecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Septendecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Septendecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Septendecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Septendecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Septendecuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Septendecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> sixteenthGetter = Septendecuple - .getSixteenthGetter(); - final SeventeenthAccessor, String> seventeenthGetter = Septendecuple - .getSeventeenthGetter(); + final Septendecuple septendecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3, + "waldo"); + final FirstAccessor, Integer> firstGetter = Septendecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Septendecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Septendecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Septendecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Septendecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Septendecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Septendecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Septendecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Septendecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Septendecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Septendecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Septendecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Septendecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Septendecuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Septendecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> sixteenthGetter = Septendecuple.getSixteenthGetter(); + final SeventeenthAccessor, String> seventeenthGetter = Septendecuple.getSeventeenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -985,45 +839,27 @@ void testSeptendecupleGetters() { @Test void testOctodecupleGetters() { - final Octodecuple octodecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3, "waldo", 4); - final FirstAccessor, Integer> firstGetter = Octodecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Octodecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Octodecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Octodecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Octodecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Octodecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Octodecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Octodecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Octodecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Octodecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Octodecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Octodecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Octodecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Octodecuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Octodecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> sixteenthGetter = Octodecuple - .getSixteenthGetter(); - final SeventeenthAccessor, String> seventeenthGetter = Octodecuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> eighteenthGetter = Octodecuple - .getEighteenthGetter(); + final Octodecuple octodecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3, + "waldo", 4); + final FirstAccessor, Integer> firstGetter = Octodecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Octodecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Octodecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Octodecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Octodecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Octodecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Octodecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Octodecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Octodecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Octodecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Octodecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Octodecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Octodecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Octodecuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Octodecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> sixteenthGetter = Octodecuple.getSixteenthGetter(); + final SeventeenthAccessor, String> seventeenthGetter = Octodecuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> eighteenthGetter = Octodecuple.getEighteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -1064,47 +900,28 @@ void testOctodecupleGetters() { @Test void testNovemdecupleGetters() { - final Novemdecuple novemdecuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3, "waldo", 4, "fred"); - final FirstAccessor, Integer> firstGetter = Novemdecuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Novemdecuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Novemdecuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Novemdecuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Novemdecuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Novemdecuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Novemdecuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Novemdecuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Novemdecuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Novemdecuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Novemdecuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Novemdecuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Novemdecuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Novemdecuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Novemdecuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> sixteenthGetter = Novemdecuple - .getSixteenthGetter(); - final SeventeenthAccessor, String> seventeenthGetter = Novemdecuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> eighteenthGetter = Novemdecuple - .getEighteenthGetter(); - final NineteenthAccessor, String> nineteenthGetter = Novemdecuple - .getNineteenthGetter(); + final Novemdecuple novemdecuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3, + "waldo", 4, "fred"); + final FirstAccessor, Integer> firstGetter = Novemdecuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Novemdecuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Novemdecuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Novemdecuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Novemdecuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Novemdecuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Novemdecuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Novemdecuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Novemdecuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Novemdecuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Novemdecuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Novemdecuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Novemdecuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Novemdecuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Novemdecuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> sixteenthGetter = Novemdecuple.getSixteenthGetter(); + final SeventeenthAccessor, String> seventeenthGetter = Novemdecuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> eighteenthGetter = Novemdecuple.getEighteenthGetter(); + final NineteenthAccessor, String> nineteenthGetter = Novemdecuple.getNineteenthGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -1147,49 +964,29 @@ void testNovemdecupleGetters() { @Test void testVigintupleGetters() { - final Vigintuple vigintuple = Tuples - .of(0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", - 3, "waldo", 4, "fred", 5); - final FirstAccessor, Integer> firstGetter = Vigintuple - .getFirstGetter(); - final SecondAccessor, Integer> secondGetter = Vigintuple - .getSecondGetter(); - final ThirdAccessor, String> thirdGetter = Vigintuple - .getThirdGetter(); - final FourthAccessor, Long> fourthGetter = Vigintuple - .getFourthGetter(); - final FifthAccessor, BigInteger> fifthGetter = Vigintuple - .getFifthGetter(); - final SixthAccessor, String> sixthGetter = Vigintuple - .getSixthGetter(); - final SeventhAccessor, Integer> seventhGetter = Vigintuple - .getSeventhGetter(); - final EighthAccessor, BigInteger> eighthGetter = Vigintuple - .getEighthGetter(); - final NinthAccessor, Integer> ninthGetter = Vigintuple - .getNinthGetter(); - final TenthAccessor, String> tenthGetter = Vigintuple - .getTenthGetter(); - final EleventhAccessor, Long> eleventhGetter = Vigintuple - .getEleventhGetter(); - final TwelfthAccessor, Integer> twelfthGetter = Vigintuple - .getTwelfthGetter(); - final ThirteenthAccessor, String> thirteenthGetter = Vigintuple - .getThirteenthGetter(); - final FourteenthAccessor, Integer> fourteenthGetter = Vigintuple - .getFourteenthGetter(); - final FifteenthAccessor, String> fifteenthGetter = Vigintuple - .getFifteenthGetter(); - final SixteenthAccessor, Integer> sixteenthGetter = Vigintuple - .getSixteenthGetter(); - final SeventeenthAccessor, String> seventeenthGetter = Vigintuple - .getSeventeenthGetter(); - final EighteenthAccessor, Integer> eighteenthGetter = Vigintuple - .getEighteenthGetter(); - final NineteenthAccessor, String> nineteenthGetter = Vigintuple - .getNineteenthGetter(); - final TwentiethAccessor, Integer> twentiethGetter = Vigintuple - .getTwentiethGetter(); + final Vigintuple vigintuple = Tuples.of( + 0, 1, "Foobar", 42L, BigInteger.ONE, "qux", 20, BigInteger.TEN, 22, "corge", 1L, 1, "grault", 2, "garply", 3, + "waldo", 4, "fred", 5); + final FirstAccessor, Integer> firstGetter = Vigintuple.getFirstGetter(); + final SecondAccessor, Integer> secondGetter = Vigintuple.getSecondGetter(); + final ThirdAccessor, String> thirdGetter = Vigintuple.getThirdGetter(); + final FourthAccessor, Long> fourthGetter = Vigintuple.getFourthGetter(); + final FifthAccessor, BigInteger> fifthGetter = Vigintuple.getFifthGetter(); + final SixthAccessor, String> sixthGetter = Vigintuple.getSixthGetter(); + final SeventhAccessor, Integer> seventhGetter = Vigintuple.getSeventhGetter(); + final EighthAccessor, BigInteger> eighthGetter = Vigintuple.getEighthGetter(); + final NinthAccessor, Integer> ninthGetter = Vigintuple.getNinthGetter(); + final TenthAccessor, String> tenthGetter = Vigintuple.getTenthGetter(); + final EleventhAccessor, Long> eleventhGetter = Vigintuple.getEleventhGetter(); + final TwelfthAccessor, Integer> twelfthGetter = Vigintuple.getTwelfthGetter(); + final ThirteenthAccessor, String> thirteenthGetter = Vigintuple.getThirteenthGetter(); + final FourteenthAccessor, Integer> fourteenthGetter = Vigintuple.getFourteenthGetter(); + final FifteenthAccessor, String> fifteenthGetter = Vigintuple.getFifteenthGetter(); + final SixteenthAccessor, Integer> sixteenthGetter = Vigintuple.getSixteenthGetter(); + final SeventeenthAccessor, String> seventeenthGetter = Vigintuple.getSeventeenthGetter(); + final EighteenthAccessor, Integer> eighteenthGetter = Vigintuple.getEighteenthGetter(); + final NineteenthAccessor, String> nineteenthGetter = Vigintuple.getNineteenthGetter(); + final TwentiethAccessor, Integer> twentiethGetter = Vigintuple.getTwentiethGetter(); assertEquals(0, firstGetter.index()); assertEquals(1, secondGetter.index()); assertEquals(2, thirdGetter.index()); @@ -1254,12 +1051,12 @@ void testOfArray() { assertThat(tuple.size()).isEqualTo(k); }); } - + @Test void testEmptyTuple() { final EmptyTuple empty = Tuples.of(); assertThat(empty.size()).isZero(); - + IndexOutOfBoundsException exception = Assertions.assertThrows(IndexOutOfBoundsException.class, () -> empty.get(0)); String expectedErrorMessage = "index 0 is illegal. The degree of this Tuple is 0."; diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/util/ObjectUtilsTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/util/ObjectUtilsTest.java index 3f6a961b..285c7227 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/util/ObjectUtilsTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/util/ObjectUtilsTest.java @@ -29,7 +29,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -@SuppressWarnings({ "ConstantConditions", "SpellCheckingInspection" }) class ObjectUtilsTest extends AbstractBaseDocumentTest { +@SuppressWarnings({ "ConstantConditions", "SpellCheckingInspection" }) +class ObjectUtilsTest extends AbstractBaseDocumentTest { @Autowired CompanyRepository companyRepository; @@ -110,7 +111,8 @@ void testGetTargetClassName() throws SecurityException { assertThat(ObjectUtils.getTargetClassName(inta.getClass().getTypeName())).isEqualTo(int[].class.getTypeName()); assertThat(ObjectUtils.getTargetClassName(typeName)).isEqualTo(boolean.class.getTypeName()); assertThat(ObjectUtils.getTargetClassName( - "java.util.List")).isEqualTo(List.class.getTypeName()); + "java.util.List")).isEqualTo( + List.class.getTypeName()); } @Test @@ -121,12 +123,6 @@ void testFirstToLowercase() { assertThat(ObjectUtils.firstToLowercase("8675309")).isEqualTo("8675309"); } - static class BunchOfCollections { - public final List lofs = new ArrayList<>(); - public final Set sois = new HashSet<>(); - public final Iterable ioc = new ArrayList<>(); - } - @Test void testGetCollectionElementType() throws SecurityException { Field lofsField = ReflectionUtils.findField(BunchOfCollections.class, "lofs"); @@ -142,14 +138,14 @@ void testGetCollectionElementType() throws SecurityException { Optional> maybeContentsOfIoc = ObjectUtils.getCollectionElementClass(iocField); assertAll( // - () -> assertThat(maybeContentsOfLofs).isPresent(), // - () -> assertThat(maybeContentsOfLofs).contains(String.class), // + () -> assertThat(maybeContentsOfLofs).isPresent(), // + () -> assertThat(maybeContentsOfLofs).contains(String.class), // - () -> assertThat(maybeContentsOfSois).isPresent(), // - () -> assertThat(maybeContentsOfSois).contains(Integer.class), // + () -> assertThat(maybeContentsOfSois).isPresent(), // + () -> assertThat(maybeContentsOfSois).contains(Integer.class), // - () -> assertThat(maybeContentsOfIoc).isPresent(), // - () -> assertThat(maybeContentsOfIoc).contains(Company.class) // + () -> assertThat(maybeContentsOfIoc).isPresent(), // + () -> assertThat(maybeContentsOfIoc).contains(Company.class) // ); } @@ -169,7 +165,7 @@ void testGetIdFieldForEntityClass() { @Test void testGetIdFieldForEntity() { Company redis = companyRepository.save( - Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); + Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), "stack@redis.com")); String actualCompanyId = redis.getId(); Object id = ObjectUtils.getIdFieldForEntity(redis); @@ -263,7 +259,7 @@ void testUnQuote() { assertThat(ObjectUtils.unQuote("\"Spam\"")).isEqualTo("Spam"); assertThat(ObjectUtils.unQuote("Spam")).isEqualTo("Spam"); assertThat(ObjectUtils.unQuote("\"The quick \\\"brown\\\" fox \\\"jumps\\\" over the lazy dog\"")).isEqualTo( - "The quick \\\"brown\\\" fox \\\"jumps\\\" over the lazy dog"); + "The quick \\\"brown\\\" fox \\\"jumps\\\" over the lazy dog"); } @Test @@ -296,13 +292,13 @@ void testIsPropertyAnnotatedWith() { @Test void testGetValueByPath() { Company redis = Company.of("RedisInc", 2011, LocalDate.of(2021, 5, 1), new Point(-122.066540, 37.377690), - "stack@redis.com"); + "stack@redis.com"); redis.setId("8675309"); redis.setMetaList(Set.of(CompanyMeta.of("RD", 100, Set.of("RedisTag", "CommonTag")))); redis.setTags(Set.of("fast", "scalable", "reliable", "database", "nosql")); Set employees = Sets.newHashSet(Employee.of("Brian Sam-Bodden"), Employee.of("Guy Royse"), - Employee.of("Justin Castilla")); + Employee.of("Justin Castilla")); redis.setEmployees(employees); String id = (String) ObjectUtils.getValueByPath(redis, "$.id"); @@ -310,26 +306,33 @@ void testGetValueByPath() { Integer yearFounded = (Integer) ObjectUtils.getValueByPath(redis, "$.yearFounded"); LocalDate lastValuation = (LocalDate) ObjectUtils.getValueByPath(redis, "$.lastValuation"); Point location = (Point) ObjectUtils.getValueByPath(redis, "$.location"); - Set tags = (Set) ObjectUtils.getValueByPath(redis, "$.tags[*]"); + @SuppressWarnings("unchecked") Set tags = (Set) ObjectUtils.getValueByPath(redis, "$.tags[*]"); String email = (String) ObjectUtils.getValueByPath(redis, "$.email"); boolean publiclyListed = (boolean) ObjectUtils.getValueByPath(redis, "$.publiclyListed"); - Collection metaList_numberValue = (Collection) ObjectUtils.getValueByPath(redis, "$.metaList[0:].numberValue"); - Collection metaList_stringValue = (Collection) ObjectUtils.getValueByPath(redis, "$.metaList[0:].stringValue"); - Collection employees_name = (Collection) ObjectUtils.getValueByPath(redis, "$.employees[0:].name"); + @SuppressWarnings( + "unchecked" + ) Collection metaList_numberValue = (Collection) ObjectUtils.getValueByPath(redis, + "$.metaList[0:].numberValue"); + @SuppressWarnings( + "unchecked" + ) Collection metaList_stringValue = (Collection) ObjectUtils.getValueByPath(redis, + "$.metaList[0:].stringValue"); + @SuppressWarnings("unchecked") Collection employees_name = (Collection) ObjectUtils.getValueByPath( + redis, "$.employees[0:].name"); assertAll( // - () -> assertThat(id).isEqualTo(redis.getId()), - () -> assertThat(name).isEqualTo(redis.getName()), - () -> assertThat(yearFounded).isEqualTo(redis.getYearFounded()), - () -> assertThat(lastValuation).isEqualTo(redis.getLastValuation()), - () -> assertThat(location).isEqualTo(redis.getLocation()), - () -> assertThat(tags).isEqualTo(redis.getTags()), - () -> assertThat(email).isEqualTo(redis.getEmail()), - () -> assertThat(publiclyListed).isEqualTo(redis.isPubliclyListed()), - () -> assertThat(metaList_numberValue).containsExactlyElementsOf(redis.getMetaList().stream().map(CompanyMeta::getNumberValue).toList()), - () -> assertThat(metaList_stringValue).containsExactlyElementsOf(redis.getMetaList().stream().map(CompanyMeta::getStringValue).toList()), - () -> assertThat(employees_name).containsExactlyElementsOf(redis.getEmployees().stream().map(Employee::getName).toList()) - ); + () -> assertThat(id).isEqualTo(redis.getId()), () -> assertThat(name).isEqualTo(redis.getName()), + () -> assertThat(yearFounded).isEqualTo(redis.getYearFounded()), + () -> assertThat(lastValuation).isEqualTo(redis.getLastValuation()), + () -> assertThat(location).isEqualTo(redis.getLocation()), () -> assertThat(tags).isEqualTo(redis.getTags()), + () -> assertThat(email).isEqualTo(redis.getEmail()), + () -> assertThat(publiclyListed).isEqualTo(redis.isPubliclyListed()), + () -> assertThat(metaList_numberValue).containsExactlyElementsOf( + redis.getMetaList().stream().map(CompanyMeta::getNumberValue).toList()), + () -> assertThat(metaList_stringValue).containsExactlyElementsOf( + redis.getMetaList().stream().map(CompanyMeta::getStringValue).toList()), + () -> assertThat(employees_name).containsExactlyElementsOf( + redis.getEmployees().stream().map(Employee::getName).toList())); } @Test @@ -394,4 +397,10 @@ public void testCompletelyInvalidString() { String expected = "__________"; assertThat(result).isEqualTo(expected); } + + static class BunchOfCollections { + public final List lofs = new ArrayList<>(); + public final Set sois = new HashSet<>(); + public final Iterable ioc = new ArrayList<>(); + } } diff --git a/redis-om-spring/src/test/java/com/redis/om/spring/util/SearchResultRawResponseToObjectConverterTest.java b/redis-om-spring/src/test/java/com/redis/om/spring/util/SearchResultRawResponseToObjectConverterTest.java index e21aa96c..8448cb2a 100644 --- a/redis-om-spring/src/test/java/com/redis/om/spring/util/SearchResultRawResponseToObjectConverterTest.java +++ b/redis-om-spring/src/test/java/com/redis/om/spring/util/SearchResultRawResponseToObjectConverterTest.java @@ -11,45 +11,48 @@ import static org.assertj.core.api.Assertions.assertThat; public class SearchResultRawResponseToObjectConverterTest { - @Autowired - private Gson gson; + private final Gson gson = new Gson(); @Test void shouldReturnNullWhenRawValueIsNull() { - assertThat(SearchResultRawResponseToObjectConverter.process(null, String.class, new Gson())).isNull(); + assertThat(SearchResultRawResponseToObjectConverter.process(null, String.class, gson)).isNull(); } @Test void shouldProcessStringWhenTargetClassIsString() { - assertThat(SearchResultRawResponseToObjectConverter.process("hello".getBytes(), String.class, new Gson())).isEqualTo("hello"); + assertThat(SearchResultRawResponseToObjectConverter.process("hello".getBytes(), String.class, gson)).isEqualTo( + "hello"); } @Test void shouldProcessDateWhenTargetClassIsDate() { Date date = new Date(); - assertThat(SearchResultRawResponseToObjectConverter.process(String.valueOf(date.getTime()).getBytes(), Date.class, new Gson())).isEqualTo(date); + assertThat(SearchResultRawResponseToObjectConverter.process(String.valueOf(date.getTime()).getBytes(), Date.class, + gson)).isEqualTo(date); } @Test void shouldProcessPointWhenTargetClassIsPoint() { Point point = new Point(12.34, 56.78); - assertThat(SearchResultRawResponseToObjectConverter.process("12.34,56.78".getBytes(), Point.class, new Gson())).isEqualTo(point); + assertThat(SearchResultRawResponseToObjectConverter.process("12.34,56.78".getBytes(), Point.class, gson)).isEqualTo( + point); } @Test void shouldProcessBooleanWhenTargetClassIsBoolean() { - assertThat(SearchResultRawResponseToObjectConverter.process("1".getBytes(), Boolean.class, new Gson())).isEqualTo(true); - assertThat(SearchResultRawResponseToObjectConverter.process("0".getBytes(), Boolean.class, new Gson())).isEqualTo(false); - } - - @Data - static class MyClass { - private String name; + assertThat(SearchResultRawResponseToObjectConverter.process("1".getBytes(), Boolean.class, gson)).isEqualTo(true); + assertThat(SearchResultRawResponseToObjectConverter.process("0".getBytes(), Boolean.class, gson)).isEqualTo(false); } @Test void shouldProcessOtherObjectWhenTargetClassIsNotSpecial() { MyClass target = new Gson().fromJson("{\"name\": \"Morgan\"}", MyClass.class); - assertThat(SearchResultRawResponseToObjectConverter.process("{\"name\": \"Morgan\"}".getBytes(), MyClass.class, new Gson())).isEqualTo(target); + assertThat(SearchResultRawResponseToObjectConverter.process("{\"name\": \"Morgan\"}".getBytes(), MyClass.class, + gson)).isEqualTo(target); + } + + @Data + static class MyClass { + private String name; } } diff --git a/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentIndexed.java b/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentIndexed.java index 51270433..422b238c 100644 --- a/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentIndexed.java +++ b/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentIndexed.java @@ -31,7 +31,7 @@ public class ValidDocumentIndexed { @NonNull @Indexed private Integer yearFounded; - + @NonNull @Indexed private LocalDate lastValuation; diff --git a/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentUnindexed.java b/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentUnindexed.java index ddec960c..948c6eda 100644 --- a/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentUnindexed.java +++ b/redis-om-spring/src/test/resources/data/metamodel/ValidDocumentUnindexed.java @@ -24,16 +24,16 @@ public class ValidDocumentUnindexed { @Id private String id; - + @NonNull private String string; - + @NonNull private Boolean bool; @NonNull private Integer integerWrapper; - + @NonNull private int integerPrimitive;