From 715fb0e6730de52ff7bbf99d260118b318186b7f Mon Sep 17 00:00:00 2001 From: Greg Burd Date: Mon, 17 Jul 2017 09:42:00 -0400 Subject: [PATCH] Helenus was the son of King Priam and Queen Hecuba of Troy, and the twin brother of the prophetess Cassandra. Like Cassandra, he was always right, but unlike her, others believed him. Seems like a good name for a layer to access DataStax, Apache, or ScyllaDB's implementations of the Cassandra database. - move to 3.x DataStax drivers (NOTE, this broke the Casser.dsl() API a bit) - introduce UnitOfWork-style pseudo transactional scoping (WIP as of this commit) - introduce session and UnitOfWork scoped caches (WIP as of this commit) - add support for SASI-based secondary index types (such as case insensitive matching, etc.) - add support for Lucene-based secondary index types (WIP https://github.com/Stratio/cassandra-lucene-index) - update types for Java 8 (WIP) - add in Codahale/Dropwizard and Zipkin metrics/tracing support (WIP) - and a lot more... --- .idea/.name | 1 + .idea/eclipseCodeFormatter.xml | 11 + .idea/encodings.xml | 6 + AUTHORS | 3 + README.md | 18 +- helenus-core.iml | 99 +++ pom.xml | 736 +++++++++--------- .../datastax/driver/core/DefaultMetadata.java | 22 + .../core/schemabuilder/CreateCustomIndex.java | 132 ++++ .../core/schemabuilder/CreateSasiIndex.java | 18 + .../core/schemabuilder/CreateTable.java | 40 + .../java/com/noorq/casser/core/Casser.java | 173 ---- .../java/com/noorq/casser/core/Mappers.java | 238 ------ .../java/com/noorq/casser/core/Postulate.java | 104 --- .../com/noorq/casser/core/SchemaUtil.java | 378 --------- .../casser/mapping/CasserMappingEntity.java | 244 ------ .../mapping/annotation/ClusteringColumn.java | 115 --- .../mapping/annotation/Constraints.java | 277 ------- .../casser/mapping/annotation/Types.java | 532 ------------- .../java/com/noorq/casser/support/Scala.java | 92 --- .../config/DefaultHelenusSettings.java} | 16 +- .../helenus}/config/GetterMethodDetector.java | 21 +- .../helenus/config/HelenusSettings.java} | 14 +- .../core/AbstractSessionOperations.java | 139 ++-- .../casser => net/helenus}/core/AutoDdl.java | 11 +- .../core/ConflictingUnitOfWorkException.java | 11 + .../helenus}/core/DslInstantiator.java | 11 +- .../casser => net/helenus}/core/Filter.java | 59 +- .../casser => net/helenus}/core/Getter.java | 6 +- src/main/java/net/helenus/core/Helenus.java | 187 +++++ .../helenus/core/HelenusSession.java} | 353 +++++---- .../helenus/core/HelenusValidator.java} | 38 +- .../helenus}/core/MapperInstantiator.java | 8 +- src/main/java/net/helenus/core/Mappers.java | 187 +++++ .../casser => net/helenus}/core/Operator.java | 18 +- .../casser => net/helenus}/core/Ordered.java | 46 +- src/main/java/net/helenus/core/Postulate.java | 102 +++ .../helenus}/core/PropertyValueValidator.java | 10 +- .../casser => net/helenus}/core/Query.java | 57 +- .../java/net/helenus/core/SchemaUtil.java | 365 +++++++++ .../helenus}/core/SessionInitializer.java | 250 +++--- .../helenus}/core/SessionRepository.java | 29 +- .../core/SessionRepositoryBuilder.java | 126 +-- .../helenus}/core/TableOperations.java | 61 +- .../java/net/helenus/core/UnitOfWork.java | 60 ++ .../helenus}/core/UserTypeOperations.java | 56 +- .../helenus/core/annotation/Cacheable.java | 11 + .../net/helenus/core/annotation/Retry.java | 17 + .../RetryConcurrentUnitOfWorkAspect.java | 83 ++ .../operation/AbstractFilterOperation.java | 58 +- .../AbstractFilterOptionalOperation.java | 56 +- .../AbstractFilterStreamOperation.java | 56 +- .../core/operation/AbstractOperation.java | 59 +- .../operation/AbstractOptionalOperation.java | 80 +- .../operation/AbstractStatementOperation.java | 88 +-- .../operation/AbstractStreamOperation.java | 81 +- .../core/operation/BoundOperation.java | 12 +- .../operation/BoundOptionalOperation.java | 10 +- .../core/operation/BoundStreamOperation.java | 10 +- .../core/operation/CountOperation.java | 51 +- .../core/operation/DeleteOperation.java | 65 +- .../core/operation/InsertOperation.java | 107 +-- .../core/operation/PreparedOperation.java | 12 +- .../operation/PreparedOptionalOperation.java | 17 +- .../operation/PreparedStreamOperation.java | 17 +- .../core/operation/SelectFirstOperation.java | 16 +- .../SelectFirstTransformingOperation.java | 15 +- .../core/operation/SelectOperation.java | 220 +++--- .../SelectTransformingOperation.java | 18 +- .../core/operation/UpdateOperation.java | 332 ++++---- .../core/reflect/DefaultPrimitiveTypes.java | 24 +- .../helenus}/core/reflect/DslExportable.java | 23 +- .../core/reflect/DslInvocationHandler.java | 178 ++--- .../core/reflect/HelenusNamedProperty.java} | 44 +- .../core/reflect/HelenusPropertyNode.java} | 79 +- .../helenus}/core/reflect/ListDsl.java | 36 +- .../helenus}/core/reflect/MapDsl.java | 28 +- .../helenus}/core/reflect/MapExportable.java | 8 +- .../core/reflect/MapperInvocationHandler.java | 60 +- .../reflect/ReflectionDslInstantiator.java | 20 +- .../core/reflect/ReflectionInstantiator.java | 14 +- .../reflect/ReflectionMapperInstantiator.java | 18 +- .../helenus}/core/reflect/SetDsl.java | 20 +- .../helenus}/mapping/ColumnInformation.java | 46 +- .../helenus}/mapping/ColumnType.java | 4 +- .../helenus/mapping/HelenusEntity.java} | 24 +- .../helenus/mapping/HelenusEntityType.java} | 6 +- .../helenus/mapping/HelenusMappingEntity.java | 270 +++++++ .../mapping/HelenusMappingProperty.java} | 132 ++-- .../helenus/mapping/HelenusProperty.java} | 38 +- .../helenus}/mapping/IdentityName.java | 17 +- .../helenus}/mapping/MappingUtil.java | 190 +++-- .../helenus}/mapping/OrderingDirection.java | 17 +- .../TypeAndOrdinalColumnComparator.java | 12 +- .../mapping/annotation/ClusteringColumn.java | 111 +++ .../helenus}/mapping/annotation/Column.java | 55 +- .../mapping/annotation/Constraints.java | 270 +++++++ .../helenus}/mapping/annotation/Index.java | 63 +- .../mapping/annotation/InheritedTable.java | 32 + .../mapping/annotation/PartitionKey.java | 69 +- .../mapping/annotation/StaticColumn.java | 43 +- .../helenus}/mapping/annotation/Table.java | 48 +- .../mapping/annotation/Transient.java} | 17 +- .../helenus}/mapping/annotation/Tuple.java | 27 +- .../net/helenus/mapping/annotation/Types.java | 556 +++++++++++++ .../helenus}/mapping/annotation/UDT.java | 41 +- .../convert/AbstractEntityValueWriter.java | 73 +- .../ByteArrayToByteBufferConverter.java | 12 +- .../ByteBufferToByteArrayConverter.java | 12 +- .../CamelCaseToUnderscoreConverter.java | 10 +- .../convert/DateToTimeuuidConverter.java | 8 +- .../convert/EnumToStringConverter.java | 6 +- .../mapping/convert/ProxyValueReader.java | 28 +- .../convert/StringToEnumConverter.java | 4 +- .../convert/TimeuuidToDateConverter.java | 6 +- .../mapping/convert/TupleValueWriter.java | 26 +- .../mapping/convert/TypedConverter.java | 32 +- .../mapping/convert/UDTValueWriter.java | 28 +- .../tuple/EntityToTupleValueConverter.java | 13 +- .../tuple/MapToTupleKeyMapConverter.java | 16 +- .../convert/tuple/MapToTupleMapConverter.java | 18 +- .../tuple/MapToTupleValueMapConverter.java | 16 +- .../convert/tuple/SetToTupleSetConverter.java | 16 +- .../tuple/TupleKeyMapToMapConverter.java | 15 +- .../tuple/TupleListToListConverter.java | 15 +- .../convert/tuple/TupleMapToMapConverter.java | 15 +- .../convert/tuple/TupleSetToSetConverter.java | 15 +- .../tuple/TupleValueMapToMapConverter.java | 15 +- .../tuple/TupleValueToEntityConverter.java | 15 +- .../udt/EntityToUDTValueConverter.java | 9 +- .../convert/udt/ListToUDTListConverter.java | 15 +- .../convert/udt/MapToUDTKeyMapConverter.java | 16 +- .../convert/udt/MapToUDTMapConverter.java | 18 +- .../udt/MapToUDTValueMapConverter.java | 16 +- .../convert/udt/SetToUDTSetConverter.java | 16 +- .../convert/udt/UDTKeyMapToMapConverter.java | 15 +- .../convert/udt/UDTListToListConverter.java | 15 +- .../convert/udt/UDTMapToMapConverter.java | 15 +- .../convert/udt/UDTSetToSetConverter.java | 15 +- .../udt/UDTValueMapToMapConverter.java | 15 +- .../udt/UDTValueToEntityConverter.java | 11 +- .../mapping/javatype/AbstractJavaType.java | 80 +- .../mapping/javatype/ByteArrayJavaType.java | 56 +- .../mapping/javatype/ByteBufferJavaType.java | 24 +- .../mapping/javatype/DateJavaType.java | 58 +- .../mapping/javatype/EnumJavaType.java | 45 +- .../mapping/javatype/ListJavaType.java | 126 ++- .../mapping/javatype/LongJavaType.java | 24 +- .../mapping/javatype/MapJavaType.java | 384 ++++----- .../mapping/javatype/MappingJavaTypes.java | 95 ++- .../mapping/javatype/SetJavaType.java | 122 ++- .../mapping/javatype/SimpleJavaTypes.java | 30 +- .../mapping/javatype/StringJavaType.java | 22 +- .../mapping/javatype/TupleValueJavaType.java | 117 ++- .../mapping/javatype/UDTValueJavaType.java | 89 +-- .../mapping/javatype/UUIDJavaType.java | 22 +- .../mapping/type/AbstractDataType.java | 27 +- .../helenus}/mapping/type/DTDataType.java | 182 +++-- .../type/ListToTupleListConverter.java | 16 +- .../mapping/type/OptionalColumnMetadata.java | 8 +- .../helenus}/mapping/type/UDTDataType.java | 110 ++- .../mapping/type/UDTKeyMapDataType.java | 65 +- .../mapping/type/UDTListDataType.java | 55 +- .../helenus}/mapping/type/UDTMapDataType.java | 71 +- .../helenus}/mapping/type/UDTSetDataType.java | 61 +- .../mapping/type/UDTValueMapDataType.java | 56 +- .../mapping/validator/AlphabetValidator.java | 25 +- .../mapping/validator/EmailValidator.java | 33 +- .../mapping/validator/LengthValidator.java | 14 +- .../mapping/validator/LowerCaseValidator.java | 26 +- .../mapping/validator/MaxLengthValidator.java | 18 +- .../mapping/validator/MinLengthValidator.java | 18 +- .../mapping/validator/NotEmptyValidator.java | 16 +- .../mapping/validator/NotNullValidator.java | 8 +- .../mapping/validator/NumberValidator.java | 27 +- .../mapping/validator/PatternValidator.java | 17 +- .../mapping/validator/SizeConstraint.java | 30 +- .../mapping/validator/UpperCaseValidator.java | 26 +- .../value/BeanColumnValueProvider.java | 25 +- .../mapping/value/ColumnValuePreparer.java | 31 + .../mapping/value/ColumnValueProvider.java | 30 + .../mapping/value/RowColumnValueProvider.java | 75 +- .../value/StatementColumnValuePreparer.java | 22 +- .../value/TupleColumnValuePreparer.java | 35 +- .../value/TupleColumnValueProvider.java | 31 +- .../mapping/value/UDTColumnValuePreparer.java | 31 +- .../mapping/value/UDTColumnValueProvider.java | 35 +- .../mapping/value/ValueProviderMap.java | 28 +- .../helenus}/support/CqlUtil.java | 10 +- .../support/DslPropertyException.java | 16 +- .../helenus}/support/Either.java | 31 +- .../helenus}/support/EitherCase.java | 6 +- .../casser => net/helenus}/support/Fun.java | 75 +- .../helenus/support/HelenusException.java} | 14 +- .../support/HelenusMappingException.java} | 14 +- .../helenus}/support/Immutables.java | 81 +- .../helenus}/support/Mutable.java | 10 +- .../helenus}/support/PackageUtil.java | 52 +- .../helenus}/support/Requires.java | 7 +- src/main/java/net/helenus/support/Scala.java | 103 +++ .../helenus}/support/Timeuuid.java | 8 +- .../helenus}/support/Transformers.java | 31 +- .../helenus}/support/UuidBuilder.java | 11 +- .../integration/core/CasserValidatorTest.java | 54 -- .../core/usertype/AddressInformation.java | 12 - .../integration/core/usertype/Customer.java | 18 - .../casser/test/unit/core/dsl/Rocket.java | 12 - .../build/AbstractEmbeddedCassandraTest.java | 50 +- .../integration/build/BuildProperties.java | 22 +- .../integration/core/ContextInitTest.java | 16 +- .../core/HelenusValidatorTest.java | 57 ++ .../core/collection/CollectionTest.java | 255 +++--- .../integration/core/collection/Customer.java | 16 +- .../core/compound/CompondKeyTest.java | 29 +- .../integration/core/compound/Timeline.java | 20 +- .../integration/core/counter/CounterTest.java | 39 +- .../test/integration/core/counter/Page.java | 14 +- .../integration/core/hierarchy/Animal.java | 19 +- .../test/integration/core/hierarchy/Cat.java | 12 +- .../core/hierarchy/HierarchyTest.java | 63 ++ .../test/integration/core/hierarchy/Pig.java} | 14 +- .../test/integration/core/index/Book.java | 18 +- .../core/index/SecondaryIndexTest.java | 39 +- .../test/integration/core/prepared/Car.java | 14 +- .../core/prepared/PreparedStatementTest.java | 105 ++- .../test/integration/core/simple/Message.java | 20 +- .../core/simple/SimpleUserTest.java | 109 +-- .../core/simple/StaticColumnTest.java | 116 +-- .../test/integration/core/simple/User.java | 18 +- .../integration/core/simple/UserType.java | 4 +- .../integration/core/simple/Username.java | 7 +- .../test/integration/core/tuple/Album.java | 18 +- .../core/tuple/AlbumInformation.java | 12 +- .../test/integration/core/tuple/DslTest.java | 36 + .../core/tuple/InnerTupleTest.java | 102 +-- .../test/integration/core/tuple/Photo.java | 9 +- .../integration/core/tuple/PhotoAlbum.java | 12 +- .../integration/core/tuple/PhotoFolder.java | 13 +- .../integration/core/tuple/TupleTest.java | 130 ++-- .../core/tuplecollection/Author.java | 12 +- .../core/tuplecollection}/Book.java | 16 +- .../core/tuplecollection/Section.java | 12 +- .../tuplecollection/TupleCollectionTest.java | 41 +- .../core/tuplecollection/TupleKeyMapTest.java | 130 ++-- .../core/tuplecollection/TupleListTest.java | 152 ++-- .../core/tuplecollection/TupleMapTest.java | 147 ++-- .../core/tuplecollection/TupleSetTest.java | 107 ++- .../tuplecollection/TupleValueMapTest.java | 124 ++- .../core/udtcollection/Author.java | 10 +- .../integration/core/udtcollection}/Book.java | 16 +- .../core/udtcollection/Section.java | 10 +- .../core/udtcollection/UDTCollectionTest.java | 44 +- .../core/udtcollection/UDTKeyMapTest.java | 94 +-- .../core/udtcollection/UDTListTest.java | 152 ++-- .../core/udtcollection/UDTMapTest.java | 130 ++-- .../core/udtcollection/UDTSetTest.java | 113 ++- .../core/udtcollection/UDTValueMapTest.java | 88 +-- .../integration/core/usertype/Account.java | 18 +- .../integration/core/usertype/Address.java | 12 +- .../core/usertype/AddressInformation.java | 12 + .../integration/core/usertype/Customer.java | 18 + .../usertype/InnerUserDefinedTypeTest.java | 87 ++- .../core/usertype/UserDefinedTypeTest.java | 139 ++-- .../core/dsl/CachedElevatorImpl.java | 32 +- .../test/performance/core/dsl/Elevator.java | 10 +- .../performance/core/dsl/ElevatorImpl.java | 12 +- .../performance/core/dsl/MappingTest.java | 60 +- .../helenus}/test/unit/core/dsl/Account.java | 21 +- .../unit/core/dsl/AccountWithCollections.java | 18 +- .../unit/core/dsl/CollectionsDlsTest.java | 58 +- .../helenus}/test/unit/core/dsl/DslTest.java | 11 +- .../helenus/test/unit/core/dsl/Rocket.java | 12 + .../unit/core/dsl/UDTCollectionsDlsTest.java | 26 +- .../test/unit/core/dsl/WrapperTest.java | 48 +- .../test/unit/core/dsl/WrongAccount.java | 6 +- .../test/unit/support/ImmutablesTest.java | 51 +- .../test/unit/support/TransformersTest.java | 30 +- src/test/resources/log4j.properties | 4 +- 278 files changed, 8690 insertions(+), 8113 deletions(-) create mode 100644 .idea/.name create mode 100644 .idea/eclipseCodeFormatter.xml create mode 100644 .idea/encodings.xml create mode 100644 AUTHORS create mode 100644 helenus-core.iml create mode 100644 src/main/java/com/datastax/driver/core/DefaultMetadata.java create mode 100644 src/main/java/com/datastax/driver/core/schemabuilder/CreateCustomIndex.java create mode 100644 src/main/java/com/datastax/driver/core/schemabuilder/CreateSasiIndex.java create mode 100644 src/main/java/com/datastax/driver/core/schemabuilder/CreateTable.java delete mode 100644 src/main/java/com/noorq/casser/core/Casser.java delete mode 100644 src/main/java/com/noorq/casser/core/Mappers.java delete mode 100644 src/main/java/com/noorq/casser/core/Postulate.java delete mode 100644 src/main/java/com/noorq/casser/core/SchemaUtil.java delete mode 100644 src/main/java/com/noorq/casser/mapping/CasserMappingEntity.java delete mode 100644 src/main/java/com/noorq/casser/mapping/annotation/ClusteringColumn.java delete mode 100644 src/main/java/com/noorq/casser/mapping/annotation/Constraints.java delete mode 100644 src/main/java/com/noorq/casser/mapping/annotation/Types.java delete mode 100644 src/main/java/com/noorq/casser/support/Scala.java rename src/main/java/{com/noorq/casser/config/DefaultCasserSettings.java => net/helenus/config/DefaultHelenusSettings.java} (69%) rename src/main/java/{com/noorq/casser => net/helenus}/config/GetterMethodDetector.java (75%) rename src/main/java/{com/noorq/casser/config/CasserSettings.java => net/helenus/config/HelenusSettings.java} (77%) rename src/main/java/{com/noorq/casser => net/helenus}/core/AbstractSessionOperations.java (68%) rename src/main/java/{com/noorq/casser => net/helenus}/core/AutoDdl.java (83%) create mode 100644 src/main/java/net/helenus/core/ConflictingUnitOfWorkException.java rename src/main/java/{com/noorq/casser => net/helenus}/core/DslInstantiator.java (69%) rename src/main/java/{com/noorq/casser => net/helenus}/core/Filter.java (80%) rename src/main/java/{com/noorq/casser => net/helenus}/core/Getter.java (88%) create mode 100644 src/main/java/net/helenus/core/Helenus.java rename src/main/java/{com/noorq/casser/core/CasserSession.java => net/helenus/core/HelenusSession.java} (52%) rename src/main/java/{com/noorq/casser/core/CasserValidator.java => net/helenus/core/HelenusValidator.java} (61%) rename src/main/java/{com/noorq/casser => net/helenus}/core/MapperInstantiator.java (79%) create mode 100644 src/main/java/net/helenus/core/Mappers.java rename src/main/java/{com/noorq/casser => net/helenus}/core/Operator.java (92%) rename src/main/java/{com/noorq/casser => net/helenus}/core/Ordered.java (53%) create mode 100644 src/main/java/net/helenus/core/Postulate.java rename src/main/java/{com/noorq/casser => net/helenus}/core/PropertyValueValidator.java (77%) rename src/main/java/{com/noorq/casser => net/helenus}/core/Query.java (72%) create mode 100644 src/main/java/net/helenus/core/SchemaUtil.java rename src/main/java/{com/noorq/casser => net/helenus}/core/SessionInitializer.java (53%) rename src/main/java/{com/noorq/casser => net/helenus}/core/SessionRepository.java (68%) rename src/main/java/{com/noorq/casser => net/helenus}/core/SessionRepositoryBuilder.java (52%) rename src/main/java/{com/noorq/casser => net/helenus}/core/TableOperations.java (70%) create mode 100644 src/main/java/net/helenus/core/UnitOfWork.java rename src/main/java/{com/noorq/casser => net/helenus}/core/UserTypeOperations.java (66%) create mode 100644 src/main/java/net/helenus/core/annotation/Cacheable.java create mode 100644 src/main/java/net/helenus/core/annotation/Retry.java create mode 100644 src/main/java/net/helenus/core/aspect/RetryConcurrentUnitOfWorkAspect.java rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractFilterOperation.java (84%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractFilterOptionalOperation.java (83%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractFilterStreamOperation.java (84%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractOperation.java (83%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractOptionalOperation.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractStatementOperation.java (91%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/AbstractStreamOperation.java (74%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/BoundOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/BoundOptionalOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/BoundStreamOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/CountOperation.java (70%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/DeleteOperation.java (77%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/InsertOperation.java (66%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/PreparedOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/PreparedOptionalOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/PreparedStreamOperation.java (93%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/SelectFirstOperation.java (90%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/SelectFirstTransformingOperation.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/SelectOperation.java (62%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/SelectTransformingOperation.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/core/operation/UpdateOperation.java (74%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/DefaultPrimitiveTypes.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/DslExportable.java (61%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/DslInvocationHandler.java (55%) rename src/main/java/{com/noorq/casser/core/reflect/CasserNamedProperty.java => net/helenus/core/reflect/HelenusNamedProperty.java} (60%) rename src/main/java/{com/noorq/casser/core/reflect/CasserPropertyNode.java => net/helenus/core/reflect/HelenusPropertyNode.java} (54%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/ListDsl.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/MapDsl.java (76%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/MapExportable.java (89%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/MapperInvocationHandler.java (54%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/ReflectionDslInstantiator.java (69%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/ReflectionInstantiator.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/ReflectionMapperInstantiator.java (71%) rename src/main/java/{com/noorq/casser => net/helenus}/core/reflect/SetDsl.java (85%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/ColumnInformation.java (84%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/ColumnType.java (89%) rename src/main/java/{com/noorq/casser/mapping/CasserEntity.java => net/helenus/mapping/HelenusEntity.java} (71%) rename src/main/java/{com/noorq/casser/mapping/CasserEntityType.java => net/helenus/mapping/HelenusEntityType.java} (84%) create mode 100644 src/main/java/net/helenus/mapping/HelenusMappingEntity.java rename src/main/java/{com/noorq/casser/mapping/CasserMappingProperty.java => net/helenus/mapping/HelenusMappingProperty.java} (73%) rename src/main/java/{com/noorq/casser/mapping/CasserProperty.java => net/helenus/mapping/HelenusProperty.java} (80%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/IdentityName.java (90%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/MappingUtil.java (68%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/OrderingDirection.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/TypeAndOrdinalColumnComparator.java (83%) create mode 100644 src/main/java/net/helenus/mapping/annotation/ClusteringColumn.java rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/Column.java (67%) create mode 100644 src/main/java/net/helenus/mapping/annotation/Constraints.java rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/Index.java (60%) create mode 100644 src/main/java/net/helenus/mapping/annotation/InheritedTable.java rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/PartitionKey.java (58%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/StaticColumn.java (76%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/Table.java (65%) rename src/main/java/{com/noorq/casser/mapping/value/ColumnValuePreparer.java => net/helenus/mapping/annotation/Transient.java} (61%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/Tuple.java (68%) create mode 100644 src/main/java/net/helenus/mapping/annotation/Types.java rename src/main/java/{com/noorq/casser => net/helenus}/mapping/annotation/UDT.java (67%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/AbstractEntityValueWriter.java (65%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/ByteArrayToByteBufferConverter.java (87%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/ByteBufferToByteArrayConverter.java (87%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/CamelCaseToUnderscoreConverter.java (88%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/DateToTimeuuidConverter.java (87%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/EnumToStringConverter.java (89%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/ProxyValueReader.java (67%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/StringToEnumConverter.java (91%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/TimeuuidToDateConverter.java (86%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/TupleValueWriter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/TypedConverter.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/UDTValueWriter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/EntityToTupleValueConverter.java (82%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/MapToTupleKeyMapConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/MapToTupleMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/MapToTupleValueMapConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/SetToTupleSetConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleKeyMapToMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleListToListConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleMapToMapConverter.java (80%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleSetToSetConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleValueMapToMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/tuple/TupleValueToEntityConverter.java (72%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/EntityToUDTValueConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/ListToUDTListConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/MapToUDTKeyMapConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/MapToUDTMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/MapToUDTValueMapConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/SetToUDTSetConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTKeyMapToMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTListToListConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTMapToMapConverter.java (80%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTSetToSetConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTValueMapToMapConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/convert/udt/UDTValueToEntityConverter.java (78%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/AbstractJavaType.java (77%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/ByteArrayJavaType.java (55%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/ByteBufferJavaType.java (70%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/DateJavaType.java (60%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/EnumJavaType.java (58%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/ListJavaType.java (65%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/LongJavaType.java (71%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/MapJavaType.java (55%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/MappingJavaTypes.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/SetJavaType.java (65%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/SimpleJavaTypes.java (69%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/StringJavaType.java (68%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/TupleValueJavaType.java (54%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/UDTValueJavaType.java (60%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/javatype/UUIDJavaType.java (70%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/AbstractDataType.java (77%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/DTDataType.java (58%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/ListToTupleListConverter.java (81%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/OptionalColumnMetadata.java (88%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTDataType.java (64%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTKeyMapDataType.java (73%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTListDataType.java (73%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTMapDataType.java (73%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTSetDataType.java (72%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/type/UDTValueMapDataType.java (72%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/AlphabetValidator.java (75%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/EmailValidator.java (63%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/LengthValidator.java (87%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/LowerCaseValidator.java (76%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/MaxLengthValidator.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/MinLengthValidator.java (79%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/NotEmptyValidator.java (83%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/NotNullValidator.java (82%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/NumberValidator.java (70%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/PatternValidator.java (80%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/SizeConstraint.java (80%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/validator/UpperCaseValidator.java (76%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/BeanColumnValueProvider.java (69%) create mode 100644 src/main/java/net/helenus/mapping/value/ColumnValuePreparer.java create mode 100644 src/main/java/net/helenus/mapping/value/ColumnValueProvider.java rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/RowColumnValueProvider.java (66%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/StatementColumnValuePreparer.java (77%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/TupleColumnValuePreparer.java (71%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/TupleColumnValueProvider.java (83%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/UDTColumnValuePreparer.java (70%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/UDTColumnValueProvider.java (83%) rename src/main/java/{com/noorq/casser => net/helenus}/mapping/value/ValueProviderMap.java (85%) rename src/main/java/{com/noorq/casser => net/helenus}/support/CqlUtil.java (90%) rename src/main/java/{com/noorq/casser => net/helenus}/support/DslPropertyException.java (65%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Either.java (82%) rename src/main/java/{com/noorq/casser => net/helenus}/support/EitherCase.java (88%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Fun.java (92%) rename src/main/java/{com/noorq/casser/support/CasserException.java => net/helenus/support/HelenusException.java} (70%) rename src/main/java/{com/noorq/casser/support/CasserMappingException.java => net/helenus/support/HelenusMappingException.java} (70%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Immutables.java (87%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Mutable.java (90%) rename src/main/java/{com/noorq/casser => net/helenus}/support/PackageUtil.java (72%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Requires.java (92%) create mode 100644 src/main/java/net/helenus/support/Scala.java rename src/main/java/{com/noorq/casser => net/helenus}/support/Timeuuid.java (96%) rename src/main/java/{com/noorq/casser => net/helenus}/support/Transformers.java (86%) rename src/main/java/{com/noorq/casser => net/helenus}/support/UuidBuilder.java (91%) delete mode 100644 src/test/java/com/noorq/casser/test/integration/core/CasserValidatorTest.java delete mode 100644 src/test/java/com/noorq/casser/test/integration/core/usertype/AddressInformation.java delete mode 100644 src/test/java/com/noorq/casser/test/integration/core/usertype/Customer.java delete mode 100644 src/test/java/com/noorq/casser/test/unit/core/dsl/Rocket.java rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/build/AbstractEmbeddedCassandraTest.java (66%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/build/BuildProperties.java (93%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/ContextInitTest.java (70%) create mode 100644 src/test/java/net/helenus/test/integration/core/HelenusValidatorTest.java rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/collection/CollectionTest.java (91%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/collection/Customer.java (78%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/compound/CompondKeyTest.java (73%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/compound/Timeline.java (68%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/counter/CounterTest.java (74%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/counter/Page.java (72%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/hierarchy/Animal.java (63%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/hierarchy/Cat.java (71%) create mode 100644 src/test/java/net/helenus/test/integration/core/hierarchy/HierarchyTest.java rename src/{main/java/com/noorq/casser/mapping/value/ColumnValueProvider.java => test/java/net/helenus/test/integration/core/hierarchy/Pig.java} (66%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/index/Book.java (70%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/index/SecondaryIndexTest.java (63%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/prepared/Car.java (78%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/prepared/PreparedStatementTest.java (65%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/Message.java (66%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/SimpleUserTest.java (86%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/StaticColumnTest.java (61%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/User.java (73%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/UserType.java (86%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/simple/Username.java (85%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/Album.java (73%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/AlbumInformation.java (77%) create mode 100644 src/test/java/net/helenus/test/integration/core/tuple/DslTest.java rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/InnerTupleTest.java (69%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/Photo.java (80%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/PhotoAlbum.java (76%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/PhotoFolder.java (77%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuple/TupleTest.java (82%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/Author.java (76%) rename src/test/java/{com/noorq/casser/test/integration/core/udtcollection => net/helenus/test/integration/core/tuplecollection}/Book.java (79%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/Section.java (76%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleCollectionTest.java (85%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleKeyMapTest.java (64%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleListTest.java (65%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleMapTest.java (59%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleSetTest.java (68%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/tuplecollection/TupleValueMapTest.java (68%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/Author.java (80%) rename src/test/java/{com/noorq/casser/test/integration/core/tuplecollection => net/helenus/test/integration/core/udtcollection}/Book.java (79%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/Section.java (80%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTCollectionTest.java (84%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTKeyMapTest.java (91%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTListTest.java (65%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTMapTest.java (68%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTSetTest.java (65%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/udtcollection/UDTValueMapTest.java (92%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/usertype/Account.java (71%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/usertype/Address.java (77%) create mode 100644 src/test/java/net/helenus/test/integration/core/usertype/AddressInformation.java create mode 100644 src/test/java/net/helenus/test/integration/core/usertype/Customer.java rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/usertype/InnerUserDefinedTypeTest.java (58%) rename src/test/java/{com/noorq/casser => net/helenus}/test/integration/core/usertype/UserDefinedTypeTest.java (76%) rename src/test/java/{com/noorq/casser => net/helenus}/test/performance/core/dsl/CachedElevatorImpl.java (89%) rename src/test/java/{com/noorq/casser => net/helenus}/test/performance/core/dsl/Elevator.java (86%) rename src/test/java/{com/noorq/casser => net/helenus}/test/performance/core/dsl/ElevatorImpl.java (90%) rename src/test/java/{com/noorq/casser => net/helenus}/test/performance/core/dsl/MappingTest.java (89%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/Account.java (67%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/AccountWithCollections.java (78%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/CollectionsDlsTest.java (73%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/DslTest.java (77%) create mode 100644 src/test/java/net/helenus/test/unit/core/dsl/Rocket.java rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/UDTCollectionsDlsTest.java (85%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/WrapperTest.java (73%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/core/dsl/WrongAccount.java (87%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/support/ImmutablesTest.java (91%) rename src/test/java/{com/noorq/casser => net/helenus}/test/unit/support/TransformersTest.java (93%) diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..cefa68f --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +helenus-core \ No newline at end of file diff --git a/.idea/eclipseCodeFormatter.xml b/.idea/eclipseCodeFormatter.xml new file mode 100644 index 0000000..4ae0669 --- /dev/null +++ b/.idea/eclipseCodeFormatter.xml @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..b26911b --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..b2ae19e --- /dev/null +++ b/AUTHORS @@ -0,0 +1,3 @@ + * Gregory Burd @gregburd github:gburd keybase:gregburd + * Alex Shvid + diff --git a/README.md b/README.md index 20a29e8..ad29db1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# casser +# helenus Fast and easy, functional style cutting edge Java 8 and Scala 2.11 Cassandra client Current status: First application in production (may be more) @@ -26,8 +26,8 @@ Latest release dependency: ``` - com.noorq.casser - casser-core + net.helenus + helenus-core 1.1.0_2.11 @@ -37,8 +37,8 @@ Active development dependency for Scala 2.11: ``` - com.noorq.casser - casser-core + net.helenus + helenus-core 1.2.0_2.11-SNAPSHOT @@ -77,8 +77,8 @@ public interface Timeline { Session initialization: ``` -Timeline timeline = Casser.dsl(Timeline.class); -CasserSession session = Casser.init(getSession()).showCql().add(Timeline.class).autoCreateDrop().get(); +Timeline timeline = Helenus.dsl(Timeline.class); +HelenusSession session = Helenus.init(getSession()).showCql().add(Timeline.class).autoCreateDrop().get(); ``` Select example: @@ -138,7 +138,7 @@ Abstract repository: ``` public interface AbstractRepository { - CasserSession session(); + HelenusSession session(); } ``` @@ -149,7 +149,7 @@ import scala.concurrent.Future; public interface AccountRepository extends AbstractRepository { - static final Account account = Casser.dsl(Account.class); + static final Account account = Helenus.dsl(Account.class); static final String DEFAULT_TIMEZONE = "America/Los_Angeles"; diff --git a/helenus-core.iml b/helenus-core.iml new file mode 100644 index 0000000..64d67d0 --- /dev/null +++ b/helenus-core.iml @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 3047e07..0566104 100644 --- a/pom.xml +++ b/pom.xml @@ -1,410 +1,418 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - com.noorq.casser - casser-core - 1.2.0_2.11-SNAPSHOT - jar + 4.0.0 + net.helenus + helenus-core + 2.0.0-SNAPSHOT + jar - casser - Casser Cassandra Client - https://github.com/noorq/casser + helenus + Helenus Cassandra Client + https://helenus.net/ - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + - - https://github.com/noorq/casser - scm:git:git@github.com:noorq/casser.git - scm:git:git@github.com:noorq/casser.git - + + https://github.net.helenus + scm:git:git@github.com:gburd/helenus.git + scm:git:git@github.com:gburd/helenus.git + - - GitHub - https://github.com/noorq/casser/issues - + + GitHub + https://github.com/gburd/helenus/issues + - - org.sonatype.oss - oss-parent - 7 - + + org.sonatype.oss + oss-parent + 7 + - - casser - UTF-8 - - 2.0.2.2 - 2.1.5 - 2.1.4 - 16.0.1 - - 1.3 - 2.1 - 4.11 - 0.2.5 - 1.7.1 - 1.0.11 - 1.9.5 - 1.9.13 - - + + helenus + UTF-8 + - - release + + release - + - + - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + - + - + - + - + - - org.scala-lang - scala-library - 2.11.6 - + + org.scala-lang + scala-library + 2.13.0-M1 + - - com.datastax.cassandra - cassandra-driver-core - ${cassandra-driver-core.version} - - - slf4j-log4j12 - org.slf4j - - - slf4j-log4j12 - org.slf4j - - - guava - com.google.guava - - - + + com.datastax.cassandra + cassandra-driver-core + 3.3.0 + + + slf4j-log4j12 + org.slf4j + + + slf4j-log4j12 + org.slf4j + + + guava + com.google.guava + + + - - com.google.guava - guava - ${guava.version} - + + org.aspectj + aspectjrt + 1.8.10 + - - - javax.validation - validation-api - 1.1.0.Final - + + org.aspectj + aspectjweaver + 1.8.10 + - + + org.apache.commons + commons-lang3 + 3.6 + - - org.codehaus.jackson - jackson-mapper-asl - ${jackson} - test - + + org.springframework + spring-core + 4.3.10.RELEASE + - - org.codehaus.jackson - jackson-core-asl - ${jackson} - test - + + com.google.guava + guava + 16.0.1 + - - org.cassandraunit - cassandra-unit - ${cassandra-unit.version} - test - - - com.datastax.cassandra - cassandra-driver-core - - - + + + javax.validation + validation-api + 2.0.0.CR3 + - - org.apache.cassandra - cassandra-all - ${cassandra} - test - - - org.slf4j - slf4j-log4j12 - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - com.google.guava - guava - - - + - - commons-io - commons-io - 2.4 - test - + + org.codehaus.jackson + jackson-mapper-asl + 1.9.13 + test + - - junit - junit - ${junit} - test - + + org.codehaus.jackson + jackson-core-asl + 1.9.13 + test + - - com.github.stephenc - jamm - ${jamm} - test - + + org.cassandraunit + cassandra-unit + 3.1.3.2 + test + + + com.datastax.cassandra + cassandra-driver-core + + + - - org.hamcrest - hamcrest-library - ${hamcrest} - test - + + org.apache.cassandra + cassandra-all + 3.11.0 + test + + + org.slf4j + slf4j-log4j12 + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + com.google.guava + guava + + + - - org.hamcrest - hamcrest-core - ${hamcrest} - test - + + commons-io + commons-io + 2.5 + test + - - org.mockito - mockito-core - ${mockito} - test - + + junit + junit + 4.12 + test + - - - org.slf4j - slf4j-api - ${slf4j} - + + com.github.stephenc + jamm + 0.2.5 + test + - - org.slf4j - jcl-over-slf4j - ${slf4j} - runtime - + + org.hamcrest + hamcrest-library + 1.3 + test + - + + org.hamcrest + hamcrest-core + 1.3 + test + - + + org.mockito + mockito-core + 2.8.47 + test + - - - src/test/resources - true - - **/* - - - + + + org.slf4j + slf4j-api + 1.7.1 + - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - true - true - true - target/javadoc - casser.* - true - true - - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - true - true - 2.0 - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - org.codehaus.mojo - build-helper-maven-plugin - 1.8 - - - reserve-network-port - - reserve-network-port - - process-resources - - - build.cassandra.native_transport_port - build.cassandra.rpc_port - build.cassandra.storage_port - build.cassandra.ssl_storage_port - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - methods - 10 - false - - **/test/unit/**/*.java - - - **/test/integration/**/*.java - **/test/performance/**/*.java - - - src/test/resources/logging.properties - - - - - org.bitstrings.maven.plugins - dependencypath-maven-plugin - 1.1.1 - - - set-all - - set - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.16 - - 1 - -Xmx1024m -Xss512m - -javaagent:${com.github.stephenc:jamm:jar} - true - false - - **/test/integration/**/*.java - - - **/test/unit/**/*.java - **/test/performance/**/*.java - - - src/test/resources/logging.properties - true - - - - - - integration-test - verify - - - - + + org.slf4j + jcl-over-slf4j + 1.7.1 + runtime + - - + + + + + + src/test/resources + true + + **/* + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + true + true + true + target/javadoc + true + true + + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + true + true + 2.0 + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.8 + + + org.codehaus.mojo + build-helper-maven-plugin + 1.8 + + + reserve-network-port + + reserve-network-port + + process-resources + + + build.cassandra.native_transport_port + build.cassandra.rpc_port + build.cassandra.storage_port + build.cassandra.ssl_storage_port + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + methods + 10 + false + + **/test/unit/**/*.java + + + **/test/integration/**/*.java + **/test/performance/**/*.java + + + src/test/resources/logging.properties + + + + + + org.bitstrings.maven.plugins + dependencypath-maven-plugin + 1.1.1 + + + set-all + + set + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.16 + + 1 + + true + false + + **/test/integration/**/*.java + + + **/test/unit/**/*.java + **/test/performance/**/*.java + + + src/test/resources/logging.properties + + true + + + + + + integration-test + verify + + + + + + + diff --git a/src/main/java/com/datastax/driver/core/DefaultMetadata.java b/src/main/java/com/datastax/driver/core/DefaultMetadata.java new file mode 100644 index 0000000..c343e29 --- /dev/null +++ b/src/main/java/com/datastax/driver/core/DefaultMetadata.java @@ -0,0 +1,22 @@ +package com.datastax.driver.core; + +import java.util.Arrays; +import java.util.List; + +public class DefaultMetadata extends Metadata { + + public DefaultMetadata() { super(null); } + + private DefaultMetadata(Cluster.Manager cluster) { + super(cluster); + } + + public TupleType newTupleType(DataType... types) { + return newTupleType(Arrays.asList(types)); + } + + public TupleType newTupleType(List types) { + return new TupleType(types, ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE); + } + +} diff --git a/src/main/java/com/datastax/driver/core/schemabuilder/CreateCustomIndex.java b/src/main/java/com/datastax/driver/core/schemabuilder/CreateCustomIndex.java new file mode 100644 index 0000000..d41b6f2 --- /dev/null +++ b/src/main/java/com/datastax/driver/core/schemabuilder/CreateCustomIndex.java @@ -0,0 +1,132 @@ +package com.datastax.driver.core.schemabuilder; + +import com.google.common.base.Optional; + +import static com.datastax.driver.core.schemabuilder.SchemaStatement.STATEMENT_START; +import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty; +import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord; + +public class CreateCustomIndex extends CreateIndex { + + private String indexName; + private boolean ifNotExists = false; + private Optional keyspaceName = Optional.absent(); + private String tableName; + private String columnName; + private boolean keys; + + CreateCustomIndex(String indexName) { + super(indexName); + validateNotEmpty(indexName, "Index name"); + validateNotKeyWord(indexName, String.format("The index name '%s' is not allowed because it is a reserved keyword", indexName)); + this.indexName = indexName; + } + + /** + * Add the 'IF NOT EXISTS' condition to this CREATE INDEX statement. + * + * @return this CREATE INDEX statement. + */ + public CreateIndex ifNotExists() { + this.ifNotExists = true; + return this; + } + + /** + * Specify the keyspace and table to create the index on. + * + * @param keyspaceName the keyspace name. + * @param tableName the table name. + * @return a {@link CreateIndex.CreateIndexOn} that will allow the specification of the column. + */ + public CreateIndex.CreateIndexOn onTable(String keyspaceName, String tableName) { + validateNotEmpty(keyspaceName, "Keyspace name"); + validateNotEmpty(tableName, "Table name"); + validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName)); + validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName)); + this.keyspaceName = Optional.fromNullable(keyspaceName); + this.tableName = tableName; + return new CreateCustomIndex.CreateIndexOn(); + } + + /** + * Specify the table to create the index on. + * + * @param tableName the table name. + * @return a {@link CreateIndex.CreateIndexOn} that will allow the specification of the column. + */ + public CreateIndex.CreateIndexOn onTable(String tableName) { + validateNotEmpty(tableName, "Table name"); + validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName)); + this.tableName = tableName; + return new CreateCustomIndex.CreateIndexOn(); + } + + public class CreateIndexOn extends CreateIndex.CreateIndexOn { + /** + * Specify the column to create the index on. + * + * @param columnName the column name. + * @return the final CREATE INDEX statement. + */ + public SchemaStatement andColumn(String columnName) { + validateNotEmpty(columnName, "Column name"); + validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName)); + CreateCustomIndex.this.columnName = columnName; + return SchemaStatement.fromQueryString(buildInternal()); + } + + /** + * Create an index on the keys of the given map column. + * + * @param columnName the column name. + * @return the final CREATE INDEX statement. + */ + public SchemaStatement andKeysOfColumn(String columnName) { + validateNotEmpty(columnName, "Column name"); + validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName)); + CreateCustomIndex.this.columnName = columnName; + CreateCustomIndex.this.keys = true; + return SchemaStatement.fromQueryString(buildInternal()); + } + } + + String getCustomClassName() { return ""; } + String getOptions() { return ""; } + + @Override + public String buildInternal() { + StringBuilder createStatement = new StringBuilder(STATEMENT_START).append("CREATE CUSTOM INDEX "); + + if (ifNotExists) { + createStatement.append("IF NOT EXISTS "); + } + + createStatement.append(indexName).append(" ON "); + + if (keyspaceName.isPresent()) { + createStatement.append(keyspaceName.get()).append("."); + } + createStatement.append(tableName); + + createStatement.append("("); + if (keys) { + createStatement.append("KEYS("); + } + + createStatement.append(columnName); + + if (keys) { + createStatement.append(")"); + } + createStatement.append(")"); + + createStatement.append(" USING '"); + createStatement.append(getCustomClassName()); + createStatement.append("' WITH OPTIONS = {"); + createStatement.append(getOptions()); + createStatement.append(" }"); + + return createStatement.toString(); + } +} diff --git a/src/main/java/com/datastax/driver/core/schemabuilder/CreateSasiIndex.java b/src/main/java/com/datastax/driver/core/schemabuilder/CreateSasiIndex.java new file mode 100644 index 0000000..f5f5a69 --- /dev/null +++ b/src/main/java/com/datastax/driver/core/schemabuilder/CreateSasiIndex.java @@ -0,0 +1,18 @@ +package com.datastax.driver.core.schemabuilder; + +public class CreateSasiIndex extends CreateCustomIndex { + + public CreateSasiIndex(String indexName) { + super(indexName); + } + + String getCustomClassName() { + return "org.apache.cassandra.index.sasi.SASIIndex"; + } + + String getOptions() { + return "'analyzer_class': " + + "'org.apache.cassandra.index.sasi.analyzer.NonTokenizingAnalyzer', " + + "'case_sensitive': 'false'"; + } +} diff --git a/src/main/java/com/datastax/driver/core/schemabuilder/CreateTable.java b/src/main/java/com/datastax/driver/core/schemabuilder/CreateTable.java new file mode 100644 index 0000000..00bebe2 --- /dev/null +++ b/src/main/java/com/datastax/driver/core/schemabuilder/CreateTable.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2012-2017 DataStax Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.driver.core.schemabuilder; + +import com.datastax.driver.core.CodecRegistry; + +/** + * A built CREATE TABLE statement. + */ +public class CreateTable extends Create { + + public CreateTable(String keyspaceName, String tableName) { + super(keyspaceName, tableName); + } + + public CreateTable(String tableName) { + super(tableName); + } + + public String getQueryString(CodecRegistry codecRegistry) { + return buildInternal(); + } + + public String toString() { + return buildInternal(); + } +} diff --git a/src/main/java/com/noorq/casser/core/Casser.java b/src/main/java/com/noorq/casser/core/Casser.java deleted file mode 100644 index 1c53655..0000000 --- a/src/main/java/com/noorq/casser/core/Casser.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.core; - -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.noorq.casser.config.CasserSettings; -import com.noorq.casser.config.DefaultCasserSettings; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.core.reflect.DslExportable; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.support.CasserMappingException; - - - -public final class Casser { - - private static volatile CasserSettings settings = new DefaultCasserSettings(); - - private static final ConcurrentMap, Object> dslCache = new ConcurrentHashMap, Object>(); - - private static volatile CasserSession session; - - private Casser() { - } - - public static CasserSession session() { - return Objects.requireNonNull(session, "session is not initialized"); - } - - protected static void setSession(CasserSession newSession) { - session = newSession; - } - - public static void shutdown() { - if (session != null) { - session.close(); - } - session = null; - dslCache.clear(); - } - - public static CasserSettings settings() { - return settings; - } - - public static CasserSettings settings(CasserSettings overrideSettings) { - CasserSettings old = settings; - settings = overrideSettings; - return old; - } - - public static SessionInitializer connect(Cluster cluster) { - Session session = cluster.connect(); - return new SessionInitializer(session); - } - - public static SessionInitializer connect(Cluster cluster, String keyspace) { - Session session = cluster.connect(keyspace); - return new SessionInitializer(session); - } - - public static SessionInitializer init(Session session) { - - if (session == null) { - throw new IllegalArgumentException("empty session"); - } - - return new SessionInitializer(session); - } - - public static void clearDslCache() { - dslCache.clear(); - } - - public static E dsl(Class iface) { - return dsl(iface, iface.getClassLoader(), Optional.empty()); - } - - public static E dsl(Class iface, ClassLoader classLoader) { - return dsl(iface, classLoader, Optional.empty()); - } - - public static E dsl(Class iface, ClassLoader classLoader, Optional parent) { - - Object instance = null; - - if (!parent.isPresent()) { - instance = dslCache.get(iface); - } - - if (instance == null) { - - instance = settings.getDslInstantiator().instantiate(iface, classLoader, parent); - - if (!parent.isPresent()) { - - Object c = dslCache.putIfAbsent(iface, instance); - if (c != null) { - instance = c; - } - - } - } - - return (E) instance; - } - - public static E map(Class iface, Map src) { - return map(iface, src, iface.getClassLoader()); - } - - public static E map(Class iface, Map src, ClassLoader classLoader) { - return settings.getMapperInstantiator().instantiate(iface, src, classLoader); - } - - public static CasserEntity entity(Class iface) { - - Object dsl = dsl(iface); - - DslExportable e = (DslExportable) dsl; - - return e.getCasserMappingEntity(); - } - - public static CasserEntity resolve(Object ifaceOrDsl) { - - if (ifaceOrDsl == null) { - throw new CasserMappingException("ifaceOrDsl is null"); - } - - if (ifaceOrDsl instanceof DslExportable) { - - DslExportable e = (DslExportable) ifaceOrDsl; - - return e.getCasserMappingEntity(); - } - - if (ifaceOrDsl instanceof Class) { - - Class iface = (Class) ifaceOrDsl; - - if (!iface.isInterface()) { - throw new CasserMappingException("class is not an interface " + iface); - } - - return entity(iface); - - } - - throw new CasserMappingException("unknown dsl object or mapping interface " + ifaceOrDsl); - } - -} diff --git a/src/main/java/com/noorq/casser/core/Mappers.java b/src/main/java/com/noorq/casser/core/Mappers.java deleted file mode 100644 index 212a8b4..0000000 --- a/src/main/java/com/noorq/casser/core/Mappers.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.core; - -import java.util.function.Function; - -import com.datastax.driver.core.Row; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.support.Fun; - -public final class Mappers { - - private Mappers() { - } - - public final static class Mapper1 implements Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1; - - public Mapper1(ColumnValueProvider provider, CasserPropertyNode p1) { - this.provider = provider; - this.p1 = p1.getProperty(); - } - - @Override - public Fun.Tuple1 apply(Row row) { - return new Fun.Tuple1(provider.getColumnValue(row, 0, p1)); - } - } - - public final static class Mapper2 implements Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1; - private final CasserProperty p2; - - public Mapper2(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - } - - @Override - public Fun.Tuple2 apply(Row row) { - return new Fun.Tuple2( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2)); - } - } - - public final static class Mapper3 implements Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1; - private final CasserProperty p2; - private final CasserProperty p3; - - public Mapper3(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2, - CasserPropertyNode p3) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - this.p3 = p3.getProperty(); - } - - @Override - public Fun.Tuple3 apply(Row row) { - return new Fun.Tuple3( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2), - provider.getColumnValue(row, 2, p3) - ); - } - } - - public final static class Mapper4 implements Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1; - private final CasserProperty p2; - private final CasserProperty p3; - private final CasserProperty p4; - - public Mapper4(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2, - CasserPropertyNode p3, - CasserPropertyNode p4 - ) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - this.p3 = p3.getProperty(); - this.p4 = p4.getProperty(); - } - - @Override - public Fun.Tuple4 apply(Row row) { - return new Fun.Tuple4( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2), - provider.getColumnValue(row, 2, p3), - provider.getColumnValue(row, 3, p4) - ); - } - } - - public final static class Mapper5 implements Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1, p2, p3, p4, p5; - - public Mapper5(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2, - CasserPropertyNode p3, - CasserPropertyNode p4, - CasserPropertyNode p5 - ) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - this.p3 = p3.getProperty(); - this.p4 = p4.getProperty(); - this.p5 = p5.getProperty(); - } - - @Override - public Fun.Tuple5 apply(Row row) { - return new Fun.Tuple5( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2), - provider.getColumnValue(row, 2, p3), - provider.getColumnValue(row, 3, p4), - provider.getColumnValue(row, 4, p5) - ); - } - } - - - public final static class Mapper6 implements - Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1, p2, p3, p4, p5, p6; - - public Mapper6(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2, - CasserPropertyNode p3, - CasserPropertyNode p4, - CasserPropertyNode p5, - CasserPropertyNode p6 - ) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - this.p3 = p3.getProperty(); - this.p4 = p4.getProperty(); - this.p5 = p5.getProperty(); - this.p6 = p6.getProperty(); - } - - @Override - public Fun.Tuple6 apply(Row row) { - return new Fun.Tuple6( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2), - provider.getColumnValue(row, 2, p3), - provider.getColumnValue(row, 3, p4), - provider.getColumnValue(row, 4, p5), - provider.getColumnValue(row, 5, p6) - ); - } - } - - public final static class Mapper7 implements - Function> { - - private final ColumnValueProvider provider; - private final CasserProperty p1, p2, p3, p4, p5, p6, p7; - - public Mapper7(ColumnValueProvider provider, - CasserPropertyNode p1, - CasserPropertyNode p2, - CasserPropertyNode p3, - CasserPropertyNode p4, - CasserPropertyNode p5, - CasserPropertyNode p6, - CasserPropertyNode p7 - ) { - this.provider = provider; - this.p1 = p1.getProperty(); - this.p2 = p2.getProperty(); - this.p3 = p3.getProperty(); - this.p4 = p4.getProperty(); - this.p5 = p5.getProperty(); - this.p6 = p6.getProperty(); - this.p7 = p7.getProperty(); - } - - @Override - public Fun.Tuple7 apply(Row row) { - return new Fun.Tuple7( - provider.getColumnValue(row, 0, p1), - provider.getColumnValue(row, 1, p2), - provider.getColumnValue(row, 2, p3), - provider.getColumnValue(row, 3, p4), - provider.getColumnValue(row, 4, p5), - provider.getColumnValue(row, 5, p6), - provider.getColumnValue(row, 6, p7) - ); - } - } - -} diff --git a/src/main/java/com/noorq/casser/core/Postulate.java b/src/main/java/com/noorq/casser/core/Postulate.java deleted file mode 100644 index 8d7b033..0000000 --- a/src/main/java/com/noorq/casser/core/Postulate.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.core; - -import java.util.Arrays; - -import com.datastax.driver.core.querybuilder.Clause; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.value.ColumnValuePreparer; -import com.noorq.casser.support.CasserMappingException; - -public final class Postulate { - - private final Operator operator; - private final V[] values; - - protected Postulate(Operator op, V[] values) { - this.operator = op; - this.values = values; - } - - public static Postulate of(Operator op, V... values) { - return new Postulate(op, values); - } - - public Clause getClause(CasserPropertyNode node, ColumnValuePreparer valuePreparer) { - - switch(operator) { - - case EQ: - return QueryBuilder.eq(node.getColumnName(), - valuePreparer.prepareColumnValue(values[0], node.getProperty())); - - case IN: - Object[] preparedValues = new Object[values.length]; - for (int i = 0; i != values.length; ++i) { - preparedValues[i] = valuePreparer.prepareColumnValue(values[i], node.getProperty()); - } - return QueryBuilder.in(node.getColumnName(), preparedValues); - - case LT: - return QueryBuilder.lt(node.getColumnName(), - valuePreparer.prepareColumnValue(values[0], node.getProperty())); - - case LTE: - return QueryBuilder.lte(node.getColumnName(), - valuePreparer.prepareColumnValue(values[0], node.getProperty())); - - case GT: - return QueryBuilder.gt(node.getColumnName(), - valuePreparer.prepareColumnValue(values[0], node.getProperty())); - - case GTE: - return QueryBuilder.gte(node.getColumnName(), - valuePreparer.prepareColumnValue(values[0], node.getProperty())); - - default: - throw new CasserMappingException("unknown filter operation " + operator); - } - - } - - @Override - public String toString() { - - if (operator == Operator.IN) { - - if (values == null) { - return "in()"; - } - - int len = values.length; - StringBuilder b = new StringBuilder(); - b.append("in("); - for (int i = 0; i != len; i++) { - if (b.length() > 3) { - b.append(", "); - } - b.append(String.valueOf(values[i])); - } - return b.append(')').toString(); - - } - - return operator.getName() + values[0]; - - } - - -} diff --git a/src/main/java/com/noorq/casser/core/SchemaUtil.java b/src/main/java/com/noorq/casser/core/SchemaUtil.java deleted file mode 100644 index f77036f..0000000 --- a/src/main/java/com/noorq/casser/core/SchemaUtil.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.core; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import com.datastax.driver.core.ColumnMetadata; -import com.datastax.driver.core.ColumnMetadata.IndexMetadata; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.RegularStatement; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.TableMetadata; -import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.Create.Options; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserEntityType; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.OrderingDirection; -import com.noorq.casser.mapping.type.OptionalColumnMetadata; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.CqlUtil; - -public final class SchemaUtil { - - private SchemaUtil() { - } - - public static RegularStatement use(String keyspace, boolean forceQuote) { - if (forceQuote) { - return new SimpleStatement("USE" + CqlUtil.forceQuote(keyspace)); - } - else { - return new SimpleStatement("USE " + keyspace); - } - } - - public static SchemaStatement createUserType(CasserEntity entity) { - - if (entity.getType() != CasserEntityType.UDT) { - throw new CasserMappingException("expected UDT entity " + entity); - } - - CreateType create = SchemaBuilder.createType(entity.getName().toCql()); - - for (CasserProperty prop : entity.getOrderedProperties()) { - - ColumnType columnType = prop.getColumnType(); - - if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { - throw new CasserMappingException("primary key columns are not supported in UserDefinedType for " + prop.getPropertyName() + " in entity " + entity); - } - - try { - prop.getDataType().addColumn(create, prop.getColumnName()); - } - catch(IllegalArgumentException e) { - throw new CasserMappingException("invalid column name '" + prop.getColumnName() + "' in entity '" + entity.getName().getName() + "'", e); - } - } - - return create; - } - - public static List alterUserType(UserType userType, - CasserEntity entity, boolean dropUnusedColumns) { - - if (entity.getType() != CasserEntityType.UDT) { - throw new CasserMappingException("expected UDT entity " + entity); - } - - List result = new ArrayList(); - - /** - * TODO: In future replace SchemaBuilder.alterTable by SchemaBuilder.alterType when it will exist - */ - - Alter alter = SchemaBuilder.alterTable(entity.getName().toCql()); - - final Set visitedColumns = dropUnusedColumns ? new HashSet() - : Collections. emptySet(); - - for (CasserProperty prop : entity.getOrderedProperties()) { - - String columnName = prop.getColumnName().getName(); - - if (dropUnusedColumns) { - visitedColumns.add(columnName); - } - - ColumnType columnType = prop.getColumnType(); - - if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { - continue; - } - - DataType dataType = userType.getFieldType(columnName); - SchemaStatement stmt = prop.getDataType().alterColumn(alter, prop.getColumnName(), optional(columnName, dataType)); - - if (stmt != null) { - result.add(stmt); - } - - } - - if (dropUnusedColumns) { - for (String field : userType.getFieldNames()) { - if (!visitedColumns.contains(field)) { - - result.add(alter.dropColumn(field)); - - } - } - } - - return result; - - } - - - public static SchemaStatement dropUserType(CasserEntity entity) { - - if (entity.getType() != CasserEntityType.UDT) { - throw new CasserMappingException("expected UDT entity " + entity); - } - - return SchemaBuilder.dropType(entity.getName().toCql()); - } - - public static SchemaStatement createTable(CasserEntity entity) { - - if (entity.getType() != CasserEntityType.TABLE) { - throw new CasserMappingException("expected table entity " + entity); - } - - Create create = SchemaBuilder.createTable(entity.getName().toCql()); - - create.ifNotExists(); - - List clusteringColumns = new ArrayList(); - - for (CasserProperty prop : entity.getOrderedProperties()) { - - ColumnType columnType = prop.getColumnType(); - - if (columnType == ColumnType.CLUSTERING_COLUMN) { - clusteringColumns.add(prop); - } - - prop.getDataType().addColumn(create, prop.getColumnName()); - - } - - if (!clusteringColumns.isEmpty()) { - Options options = create.withOptions(); - clusteringColumns.forEach(p -> options.clusteringOrder(p.getColumnName().toCql(), mapDirection(p.getOrdering()))); - } - - return create; - - } - - public static List alterTable(TableMetadata tmd, - CasserEntity entity, boolean dropUnusedColumns) { - - if (entity.getType() != CasserEntityType.TABLE) { - throw new CasserMappingException("expected table entity " + entity); - } - - List result = new ArrayList(); - - Alter alter = SchemaBuilder.alterTable(entity.getName().toCql()); - - final Set visitedColumns = dropUnusedColumns ? new HashSet() - : Collections. emptySet(); - - for (CasserProperty prop : entity.getOrderedProperties()) { - - String columnName = prop.getColumnName().getName(); - - if (dropUnusedColumns) { - visitedColumns.add(columnName); - } - - ColumnType columnType = prop.getColumnType(); - - if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { - continue; - } - - ColumnMetadata columnMetadata = tmd.getColumn(columnName); - SchemaStatement stmt = prop.getDataType().alterColumn(alter, prop.getColumnName(), optional(columnMetadata)); - - if (stmt != null) { - result.add(stmt); - } - - } - - if (dropUnusedColumns) { - for (ColumnMetadata cm : tmd.getColumns()) { - if (!visitedColumns.contains(cm.getName())) { - - result.add(alter.dropColumn(cm.getName())); - - } - } - } - - return result; - } - - public static SchemaStatement dropTable(CasserEntity entity) { - - if (entity.getType() != CasserEntityType.TABLE) { - throw new CasserMappingException("expected table entity " + entity); - } - - return SchemaBuilder.dropTable(entity.getName().toCql()).ifExists(); - - } - - public static SchemaStatement createIndex(CasserProperty prop) { - - return SchemaBuilder.createIndex(prop.getIndexName().get().toCql()) - .ifNotExists() - .onTable(prop.getEntity().getName().toCql()) - .andColumn(prop.getColumnName().toCql()); - - } - - public static List createIndexes(CasserEntity entity) { - - return entity.getOrderedProperties().stream() - .filter(p -> p.getIndexName().isPresent()) - .map(p -> SchemaUtil.createIndex(p)) - .collect(Collectors.toList()); - - } - - public static List alterIndexes(TableMetadata tmd, - CasserEntity entity, boolean dropUnusedIndexes) { - - List list = new ArrayList(); - - final Set visitedColumns = dropUnusedIndexes ? new HashSet() - : Collections. emptySet(); - - entity - .getOrderedProperties() - .stream() - .filter(p -> p.getIndexName().isPresent()) - .forEach(p -> { - - String columnName = p.getColumnName().getName(); - - if (dropUnusedIndexes) { - visitedColumns.add(columnName); - } - - ColumnMetadata cm = tmd.getColumn(columnName); - - if (cm != null) { - IndexMetadata im = cm.getIndex(); - if (im == null) { - list.add(createIndex(p)); - } - } - else { - list.add(createIndex(p)); - } - - - }); - - if (dropUnusedIndexes) { - - tmd - .getColumns() - .stream() - .filter(c -> c.getIndex() != null && !visitedColumns.contains(c.getName())) - .forEach(c -> { - - list.add(SchemaBuilder.dropIndex(c.getIndex().getName()).ifExists()); - - }); - - - } - - return list; - - } - - public static SchemaStatement dropIndex(CasserProperty prop) { - return SchemaBuilder.dropIndex(prop.getIndexName().get().toCql()).ifExists(); - } - - private static SchemaBuilder.Direction mapDirection(OrderingDirection o) { - switch(o) { - case ASC: - return SchemaBuilder.Direction.ASC; - case DESC: - return SchemaBuilder.Direction.DESC; - } - throw new CasserMappingException("unknown ordering " + o); - } - - public static void throwNoMapping(CasserProperty prop) { - - throw new CasserMappingException( - "only primitive types and Set,List,Map collections and UserDefinedTypes are allowed, unknown type for property '" + prop.getPropertyName() - + "' type is '" + prop.getJavaType() + "' in the entity " + prop.getEntity()); - - } - - private static OptionalColumnMetadata optional(final ColumnMetadata columnMetadata) { - if (columnMetadata != null) { - return new OptionalColumnMetadata() { - - @Override - public String getName() { - return columnMetadata.getName(); - } - - @Override - public DataType getType() { - return columnMetadata.getType(); - } - - }; - } - return null; - } - - private static OptionalColumnMetadata optional(final String name, final DataType dataType) { - if (dataType != null) { - return new OptionalColumnMetadata() { - - @Override - public String getName() { - return name; - } - - @Override - public DataType getType() { - return dataType; - } - - }; - } - return null; - } - -} diff --git a/src/main/java/com/noorq/casser/mapping/CasserMappingEntity.java b/src/main/java/com/noorq/casser/mapping/CasserMappingEntity.java deleted file mode 100644 index 8ab9e38..0000000 --- a/src/main/java/com/noorq/casser/mapping/CasserMappingEntity.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * - * Copyright (C) 2015 The Casser Authors - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.mapping; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.noorq.casser.config.CasserSettings; -import com.noorq.casser.core.Casser; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Tuple; -import com.noorq.casser.mapping.annotation.UDT; -import com.noorq.casser.support.CasserMappingException; - -public final class CasserMappingEntity implements CasserEntity { - - private final Class iface; - private final CasserEntityType type; - private final IdentityName name; - private final ImmutableMap props; - private final ImmutableList orderedProps; - - public CasserMappingEntity(Class iface) { - this(iface, autoDetectType(iface)); - } - - public CasserMappingEntity(Class iface, CasserEntityType type) { - - if (iface == null || !iface.isInterface()) { - throw new IllegalArgumentException("invalid parameter " + iface); - } - - this.iface = iface; - this.type = Objects.requireNonNull(type, "type is empty"); - this.name = resolveName(iface, type); - - CasserSettings settings = Casser.settings(); - - Method[] all = iface.getDeclaredMethods(); - - List propsLocal = new ArrayList(); - ImmutableMap.Builder propsBuilder = ImmutableMap.builder(); - - for (Method m : all) { - - if (settings.getGetterMethodDetector().apply(m)) { - - CasserProperty prop = new CasserMappingProperty(this, m); - - propsBuilder.put(prop.getPropertyName(), prop); - propsLocal.add(prop); - - } - - } - - this.props = propsBuilder.build(); - - Collections.sort(propsLocal, TypeAndOrdinalColumnComparator.INSTANCE); - this.orderedProps = ImmutableList.copyOf(propsLocal); - - validateOrdinals(); - } - - @Override - public CasserEntityType getType() { - return type; - } - - @Override - public Class getMappingInterface() { - return iface; - } - - @Override - public Collection getOrderedProperties() { - return orderedProps; - } - - @Override - public CasserProperty getProperty(String name) { - return props.get(name); - } - - @Override - public IdentityName getName() { - return name; - } - - private static IdentityName resolveName(Class iface, CasserEntityType type) { - - switch(type) { - - case TABLE: - return MappingUtil.getTableName(iface, true); - - case TUPLE: - return IdentityName.of(MappingUtil.getDefaultEntityName(iface), false); - - case UDT: - return MappingUtil.getUserDefinedTypeName(iface, true); - } - - throw new CasserMappingException("invalid entity type " + type + " in " + type); - - } - - private static CasserEntityType autoDetectType(Class iface) { - - Objects.requireNonNull(iface, "empty iface"); - - if (null != iface.getDeclaredAnnotation(Table.class)) { - return CasserEntityType.TABLE; - } - - else if (null != iface.getDeclaredAnnotation(Tuple.class)) { - return CasserEntityType.TUPLE; - } - - else if (null != iface.getDeclaredAnnotation(UDT.class)) { - return CasserEntityType.UDT; - } - - throw new CasserMappingException("entity must be annotated by @Table or @Tuple or @UserDefinedType " + iface); - } - - private void validateOrdinals() { - - switch(getType()) { - - case TABLE: - validateOrdinalsForTable(); - break; - - case TUPLE: - validateOrdinalsInTuple(); - break; - - default: - break; - } - - } - - private void validateOrdinalsForTable() { - - BitSet partitionKeys = new BitSet(); - BitSet clusteringColumns = new BitSet(); - - for (CasserProperty prop : getOrderedProperties()) { - - ColumnType type = prop.getColumnType(); - - int ordinal = prop.getOrdinal(); - - switch(type) { - - case PARTITION_KEY: - if (partitionKeys.get(ordinal)) { - throw new CasserMappingException("detected two or more partition key columns with the same ordinal " + ordinal + " in " + prop.getEntity()); - } - partitionKeys.set(ordinal); - break; - - case CLUSTERING_COLUMN: - if (clusteringColumns.get(ordinal)) { - throw new CasserMappingException("detected two or clustering columns with the same ordinal " + ordinal + " in " + prop.getEntity()); - } - clusteringColumns.set(ordinal); - break; - - default: - break; - } - - } - - } - - private void validateOrdinalsInTuple() { - boolean[] ordinals = new boolean[props.size()]; - - getOrderedProperties().forEach(p -> { - - int ordinal = p.getOrdinal(); - - if (ordinal < 0 || ordinal >= ordinals.length) { - throw new CasserMappingException("invalid ordinal " + ordinal + " found for property " + p.getPropertyName() + " in " + p.getEntity()); - } - - if (ordinals[ordinal]) { - throw new CasserMappingException("detected two or more properties with the same ordinal " + ordinal + " in " + p.getEntity()); - } - - ordinals[ordinal] = true; - - }); - - for (int i = 0; i != ordinals.length; ++i) { - if (!ordinals[i]) { - throw new CasserMappingException("detected absent ordinal " + i + " in " + this); - } - } - - } - - @Override - public String toString() { - - StringBuilder str = new StringBuilder(); - str.append(iface.getSimpleName()) - .append("(").append(name.getName()).append(") ") - .append(type.name().toLowerCase()) - .append(":\n"); - - for (CasserProperty prop : getOrderedProperties()) { - str.append(prop.toString()); - str.append("\n"); - } - return str.toString(); - } - -} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/ClusteringColumn.java b/src/main/java/com/noorq/casser/mapping/annotation/ClusteringColumn.java deleted file mode 100644 index dc497fe..0000000 --- a/src/main/java/com/noorq/casser/mapping/annotation/ClusteringColumn.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.mapping.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.noorq.casser.mapping.OrderingDirection; - -/** - * ClusteringColumn is the family column in legacy Cassandra API - * - * The purpose of this column is have additional dimension in the table. - * Both @PartitionKey and @ClusteringColumn together are parts of the primary key of the table. - * The primary difference between them is that the first one is using for routing purposes - * in order to locate a data node in the cluster, otherwise the second one is using - * inside the node to locate peace of data in concrete machine. - * - * ClusteringColumn can be represented as a Key in SortedMap that fully stored in a single node. - * All developers must be careful for selecting fields for clustering columns, because all data - * inside this SortedMap must fit in to one node. - * - * ClusteringColumn can have more than one part and the order of parts is important. - * This order defines the way how Cassandra joins the parts and influence of data retrieval - * operations. Each part can have ordering property that defines default ascending or descending order - * of data. In case of two and more parts in select queries developer needs to have consisdent - * order of all parts as they defined in table. - * - * For example, first part is ASC ordering, second is also ASC, so Cassandra will sort entries like this: - * a-a - * a-b - * b-a - * b-b - * In this case we are able run queries: - * ORDER BY first ASC, second ASC - * ORDER BY first DESC, second DESC - * WHERE first=? ORDER BY second ASC - * WHERE first=? ORDER BY second DESC - * WHERE first=? AND second=? - * - * But, we can not run queries: - * ORDER BY first DESC, second ASC - * ORDER BY first ASC, second DESC - * WHERE second=? ORDER BY first (ASC,DESC) - * - * @author Alex Shvid - * - */ - -@Retention(value = RetentionPolicy.RUNTIME) -@Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -public @interface ClusteringColumn { - - /** - * Default value is the name of the method normalized to underscore - * - * @return name of the column - */ - - String value() default ""; - - /** - * ClusteringColumn parts must be ordered in the @Table. It is the requirement of Cassandra. - * Cassandra joins all parts to the final clustering key that is stored in column family name. - * Additionally all parts can have some ordering (ASC, DESC) that with sequence of parts - * determines key comparison function, so Cassandra storing column family names always in sorted order. - * - * Be default ordinal has 0 value, that's because in most cases @Table have single column for ClusteringColumn - * If you have 2 and more parts of the ClusteringColumn, then you need to use ordinal() to - * define the sequence of the parts - * - * @return number that used to sort clustering columns - */ - - int ordinal() default 0; - - /** - * Default order of values in the ClusteringColumn - * This ordering is using for comparison of the clustering column values when Cassandra stores it in the - * sorted order. - * - * Default value is the ascending order - * - * @return ascending order or descending order of clustering column values - */ - - OrderingDirection ordering() default OrderingDirection.ASC; - - /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * - * Default value is false, we are quoting only selected names. - * - * @return true if name have to be quoted - */ - - boolean forceQuote() default false; - -} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Constraints.java b/src/main/java/com/noorq/casser/mapping/annotation/Constraints.java deleted file mode 100644 index 408dbb0..0000000 --- a/src/main/java/com/noorq/casser/mapping/annotation/Constraints.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.mapping.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.validation.Constraint; - -import com.noorq.casser.mapping.validator.AlphabetValidator; -import com.noorq.casser.mapping.validator.EmailValidator; -import com.noorq.casser.mapping.validator.LengthValidator; -import com.noorq.casser.mapping.validator.LowerCaseValidator; -import com.noorq.casser.mapping.validator.MaxLengthValidator; -import com.noorq.casser.mapping.validator.MinLengthValidator; -import com.noorq.casser.mapping.validator.NotEmptyValidator; -import com.noorq.casser.mapping.validator.NotNullValidator; -import com.noorq.casser.mapping.validator.NumberValidator; -import com.noorq.casser.mapping.validator.PatternValidator; -import com.noorq.casser.mapping.validator.UpperCaseValidator; - -/** - * Constraint annotations are using for data integrity mostly for @java.lang.String types. - * The place of the annotation is the particular method in model interface. - * - * All of them does not have effect on selects and data retrieval operations. - * - * Support types: - * - @NotNull supports any @java.lang.Object type - * - All annotations support @java.lang.String type - * - * @author Alex Shvid - * - */ - -public final class Constraints { - - private Constraints() { - } - - /** - * NotNull annotation is using to check that value is not null before storing it - * - * Applicable to use in any @java.lang.Object - * - * It does not check on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = NotNullValidator.class) - public @interface NotNull { - - } - - /** - * NotEmpty annotation is using to check that value has text before storing it - * - * Also checks for the null and it is more strict annotation then @NotNull - * - * Can be used for @java.lang.CharSequence, @ByteBuffer and any array - * - * It does not check on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = NotEmptyValidator.class) - public @interface NotEmpty { - - } - - /** - * Email annotation is using to check that value has a valid email before storing it - * - * Can be used only for @CharSequence - * - * It does not check on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = EmailValidator.class) - public @interface Email { - - } - - /** - * Number annotation is using to check that all letters in value are digits before storing it - * - * Can be used only for @java.lang.CharSequence - * - * It does not check on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = NumberValidator.class) - public @interface Number { - - } - - - /** - * Alphabet annotation is using to check that all letters in value are in specific alphabet before storing it - * - * Can be used only for @java.lang.CharSequence - * - * It does not check on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = AlphabetValidator.class) - public @interface Alphabet { - - /** - * Defines alphabet that will be used to check value - * - * @return alphabet characters in the string - */ - - String value(); - - } - - /** - * Length annotation is using to ensure that value has exact length before storing it - * - * Can be used for @java.lang.CharSequence, @ByteBuffer and any array - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = LengthValidator.class) - public @interface Length { - - int value(); - - } - - /** - * MaxLength annotation is using to ensure that value has length less or equal to some threshold before storing it - * - * Can be used for @java.lang.CharSequence, @ByteBuffer and byte[] - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = MaxLengthValidator.class) - public @interface MaxLength { - - int value(); - - } - - /** - * MinLength annotation is using to ensure that value has length greater or equal to some threshold before storing it - * - * Can be used for @java.lang.CharSequence, @ByteBuffer and byte[] - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = MinLengthValidator.class) - public @interface MinLength { - - int value(); - - } - - /** - * LowerCase annotation is using to ensure that value is in lower case before storing it - * - * Can be used only for @java.lang.CharSequence - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = LowerCaseValidator.class) - public @interface LowerCase { - - } - - /** - * UpperCase annotation is using to ensure that value is in upper case before storing it - * - * Can be used only for @java.lang.CharSequence - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = UpperCaseValidator.class) - public @interface UpperCase { - - } - - /** - * Pattern annotation is LowerCase annotation is using to ensure that value is upper case before storing it - * - * Can be used only for @java.lang.CharSequence - * - * It does not have effect on selects and data retrieval operations - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - @Constraint(validatedBy = PatternValidator.class) - public @interface Pattern { - - /** - * User defined regex expression to check match of the value - * - * @return Java regex pattern - */ - - String value(); - - /** - * Regex flags composition - * - * @return Java regex flags - */ - - int flags(); - - } - -} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Types.java b/src/main/java/com/noorq/casser/mapping/annotation/Types.java deleted file mode 100644 index 79808dc..0000000 --- a/src/main/java/com/noorq/casser/mapping/annotation/Types.java +++ /dev/null @@ -1,532 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.mapping.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import com.datastax.driver.core.DataType; - -/** - * Types annotations are using for clarification of Cassandra data type for particular Java type. - * - * Sometimes it is possible to have for single Java type multiple Cassandra data types: - * - @String can be @DataType.Name.ASCII or @DataType.Name.TEXT or @DataType.Name.VARCHAR - * - @Long can be @DataType.Name.BIGINT or @DataType.Name.COUNTER - * - * All those type annotations simplify mapping between Java types and Cassandra data types. - * They are not required, for each Java type there is a default Cassandra data type in Casser, but in some - * cases you would like to control mapping to make sure that the right Cassandra data type is using. - * - * For complex types like collections, UDF and Tuple types all those annotations are using to - * clarify the sub-type(s) or class/UDF names. - * - * Has significant effect on schema operations. - * - * @author Alex Shvid - * - */ - -public final class Types { - - private Types() { - } - - /** - * Says to use @DataType.Name.ASCII data type in schema - * Java type is @String - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Ascii { - - } - - /** - * Says to use @DataType.Name.BIGINT data type in schema - * Java type is @Long - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Bigint { - - } - - /** - * Says to use @DataType.Name.BLOB data type in schema - * Java type is @ByteBuffer or @byte[] - * Using by default - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Blob { - - } - - /** - * Says to use @DataType.Name.LIST data type in schema with specific sub-type - * Java type is @List - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: prepend, prependAll, setIdx, append, appendAll, discard and discardAll in @UpdateOperation - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface List { - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT sub-type in the list, consider @UDTList annotation - * - * @return data type name of the value - */ - - DataType.Name value(); - - } - - /** - * Says to use @DataType.Name.MAP data type in schema with specific sub-types - * Java type is @Map - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: put and putAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Map { - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT key sub-type in the map, consider @UDTKeyMap or @UDTMap annotations - * - * @return data type name of the key - */ - - DataType.Name key(); - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT value sub-type in the map, consider @UDTValueMap or @UDTMap annotations - * - * @return data type name of the value - */ - - DataType.Name value(); - - } - - /** - * Says to use @DataType.Name.COUNTER type in schema - * Java type is @Long - * - * For this type there are special operations: increment and decrement in @UpdateOperation. - * You do not need to initialize counter value, it will be done automatically by Cassandra. - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Counter { - - } - - /** - * Says to use @DataType.Name.SET data type in schema with specific sub-type - * Java type is @Set - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: add, addAll, remove and removeAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Set { - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT sub-type in the set, consider @UDTSet annotation - * - * @return data type name of the value - */ - - DataType.Name value(); - - } - - /** - * Says to use @DataType.Name.CUSTOM type in schema - * Java type is @ByteBuffer or @byte[] - * - * Uses for custom user types that has special implementation. - * Casser does not deal with this class directly for now, uses only in serialized form. - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Custom { - - /** - * Class name of the custom user type that is implementation of the type - * - * @return class name of the custom type implementation - */ - - String className(); - - } - - /** - * Says to use @DataType.Name.TEXT type in schema - * Java type is @String - * Using by default - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Text { - - } - - /** - * Says to use @DataType.Name.TIMESTAMP type in schema - * Java type is @Date - * Using by default - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Timestamp { - - } - - /** - * Says to use @DataType.Name.TIMEUUID type in schema - * Java type is @UUID or @Date - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Timeuuid { - - } - - /** - * Says to use @DataType.Name.TUPLE type in schema - * Java type is @TupleValue or model interface with @Tuple annotation - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - public @interface Tuple { - - /** - * If Java type is the @TupleValue then this field is required. - * Any Cassandra Tuple is the sequence of Cassandra types. - * For now Casser supports only simple data types in tuples for @TupleValue Java type - * - * In case if Java type is the model interface with @Tuple annotation then - * all methods in this interface can have Types annotations that can be complex types as well. - * - * @return data type name sequence - */ - - DataType.Name[] value() default {}; - - } - - /** - * Says to use @DataType.Name.UDT type in schema - * Java type is @UDTValue or model interface with @UDT annotation - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDT { - - /** - * If Java type is the @UDTValue then this field is required. - * Any Cassandra UDT has name and must be created before this use as a Cassandra Type. - * - * This value is the UDT name of the Cassandra Type that was already created in the schema - * - * In case of Java type is the model interface with @UDT annotation then - * this field is not using since model interface defines UserDefinedType with specific name - * - * @return UDT name - */ - - String value() default ""; - - /** - * Only used for JavaType @UDTValue - * - * In case if value() method returns reserved word that can not be used as a name of UDT then - * forceQuote will add additional quotes around this name in all CQL queries. - * - * Default value is false. - * - * @return true if quotation is needed - */ - - boolean forceQuote() default false; - - } - - /** - * Says to use @DataType.Name.MAP data type in schema with specific UDT sub-type as a key and simple sub-type as a value - * Java type is @Map - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: put and putAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDTKeyMap { - - /** - * Clarification of using the UDT data type as a key sub-type in the collection. - * - * @return annotation of UDT type - */ - - UDT key(); - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT value sub-type in the map, consider @UDTMap annotations - * - * @return data type name of the value - */ - - DataType.Name value(); - - } - - /** - * Says to use @DataType.Name.LIST data type in schema with specific UDT sub-type - * Java type is @List - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: prepend, prependAll, setIdx, append, appendAll, discard and discardAll in @UpdateOperation - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDTList { - - /** - * Clarification of using the UDT data type as a sub-type in the collection. - * - * @return annotation of the UDT value - */ - - UDT value(); - - } - - /** - * Says to use @DataType.Name.MAP data type in schema with specific UDT sub-types - * Java type is @Map - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: put and putAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDTMap { - - /** - * Clarification of using the UDT data type as a key sub-type in the collection. - * - * @return annotation of the UDT key - */ - - UDT key(); - - /** - * Clarification of using the UDT data type as a value sub-type in the collection. - * - * @return annotation of the UDT value - */ - - UDT value(); - - } - - /** - * Says to use @DataType.Name.SET data type in schema with specific UDT sub-type - * Java type is @Set - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: add, addAll, remove and removeAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDTSet { - - /** - * Clarification of using the UDT data type as a sub-type in the collection. - * - * @return annotation of the UDT value - */ - - UDT value(); - - } - - /** - * Says to use @DataType.Name.MAP data type in schema with specific simple sub-type as a key and UDT sub-type as a value - * Java type is @Map - * - * Casser does not allow to use a specific implementation of the collection thereof data retrieval operation - * result can be a collection with another implementation. - * - * This annotation is usually used only for sub-types clarification and only in case if sub-type is Java type that - * corresponds to multiple Cassandra data types. - * - * For this type there are special operations: put and putAll in @UpdateOperation. - * - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface UDTValueMap { - - /** - * Clarification of using the sub-type data type in the collection. - * It supports only simple data type (not Collection, UDT or Tuple) - * - * In case if you need UDT key sub-type in the map, consider @UDTMap annotations - * - * @return data type name of the key - */ - - DataType.Name key(); - - /** - * Clarification of using the UDT data type as a value sub-type in the collection. - * - * @return annotation of the UDT value - */ - - UDT value(); - - } - - /** - * Says to use @DataType.Name.UUID type in schema - * Java type is @UUID - * Using by default - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Uuid { - - } - - /** - * Says to use @DataType.Name.VARCHAR type in schema - * Java type is @String - */ - - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) - public @interface Varchar { - - } - -} diff --git a/src/main/java/com/noorq/casser/support/Scala.java b/src/main/java/com/noorq/casser/support/Scala.java deleted file mode 100644 index 062ff27..0000000 --- a/src/main/java/com/noorq/casser/support/Scala.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2015 The Casser Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.noorq.casser.support; - -import scala.concurrent.Future; -import scala.concurrent.impl.Promise.DefaultPromise; - -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -public final class Scala { - - public static Future asFuture(ListenableFuture future) { - final scala.concurrent.Promise promise = new DefaultPromise(); - Futures.addCallback(future, new FutureCallback() { - @Override public void onSuccess(T result) { - promise.success(result); - } - @Override public void onFailure(Throwable t) { - promise.failure(t); - } - }); - return promise.future(); - } - - public static Future> asFuture(ListenableFuture future, A a) { - final scala.concurrent.Promise> promise = new DefaultPromise>(); - Futures.addCallback(future, new FutureCallback() { - @Override public void onSuccess(T result) { - promise.success(new Fun.Tuple2(result, a)); - } - @Override public void onFailure(Throwable t) { - promise.failure(t); - } - }); - return promise.future(); - } - - public static Future> asFuture(ListenableFuture future, A a, B b) { - final scala.concurrent.Promise> promise = new DefaultPromise>(); - Futures.addCallback(future, new FutureCallback() { - @Override public void onSuccess(T result) { - promise.success(new Fun.Tuple3(result, a, b)); - } - @Override public void onFailure(Throwable t) { - promise.failure(t); - } - }); - return promise.future(); - } - - public static Future> asFuture(ListenableFuture future, A a, B b, C c) { - final scala.concurrent.Promise> promise = new DefaultPromise>(); - Futures.addCallback(future, new FutureCallback() { - @Override public void onSuccess(T result) { - promise.success(new Fun.Tuple4(result, a, b, c)); - } - @Override public void onFailure(Throwable t) { - promise.failure(t); - } - }); - return promise.future(); - } - - public static Future> asFuture(ListenableFuture future, A a, B b, C c, D d) { - final scala.concurrent.Promise> promise = new DefaultPromise>(); - Futures.addCallback(future, new FutureCallback() { - @Override public void onSuccess(T result) { - promise.success(new Fun.Tuple5(result, a, b, c, d)); - } - @Override public void onFailure(Throwable t) { - promise.failure(t); - } - }); - return promise.future(); - } - -} diff --git a/src/main/java/com/noorq/casser/config/DefaultCasserSettings.java b/src/main/java/net/helenus/config/DefaultHelenusSettings.java similarity index 69% rename from src/main/java/com/noorq/casser/config/DefaultCasserSettings.java rename to src/main/java/net/helenus/config/DefaultHelenusSettings.java index 145934d..cacc892 100644 --- a/src/main/java/com/noorq/casser/config/DefaultCasserSettings.java +++ b/src/main/java/net/helenus/config/DefaultHelenusSettings.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.config; +package net.helenus.config; import java.lang.reflect.Method; import java.util.function.Function; -import com.noorq.casser.core.DslInstantiator; -import com.noorq.casser.core.MapperInstantiator; -import com.noorq.casser.core.reflect.ReflectionDslInstantiator; -import com.noorq.casser.core.reflect.ReflectionMapperInstantiator; -import com.noorq.casser.mapping.convert.CamelCaseToUnderscoreConverter; +import net.helenus.core.DslInstantiator; +import net.helenus.core.MapperInstantiator; +import net.helenus.core.reflect.ReflectionDslInstantiator; +import net.helenus.core.reflect.ReflectionMapperInstantiator; +import net.helenus.mapping.convert.CamelCaseToUnderscoreConverter; -public class DefaultCasserSettings implements CasserSettings { +public class DefaultHelenusSettings implements HelenusSettings { @Override public Function getPropertyToColumnConverter() { diff --git a/src/main/java/com/noorq/casser/config/GetterMethodDetector.java b/src/main/java/net/helenus/config/GetterMethodDetector.java similarity index 75% rename from src/main/java/com/noorq/casser/config/GetterMethodDetector.java rename to src/main/java/net/helenus/config/GetterMethodDetector.java index 866fb27..72c0f9f 100644 --- a/src/main/java/com/noorq/casser/config/GetterMethodDetector.java +++ b/src/main/java/net/helenus/config/GetterMethodDetector.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.config; +package net.helenus.config; + +import net.helenus.mapping.annotation.Transient; import java.lang.reflect.Method; import java.util.function.Function; @@ -21,20 +23,25 @@ import java.util.function.Function; public enum GetterMethodDetector implements Function { INSTANCE; - + @Override public Boolean apply(Method method) { - + if (method == null) { throw new IllegalArgumentException("empty parameter"); } - + if (method.getParameterCount() != 0 || method.getReturnType() == void.class) { return false; } - + + // Methods marked "Transient" are not mapped, skip them. + if (method.getDeclaredAnnotation(Transient.class) != null) { + return false; + } + return true; - + } } diff --git a/src/main/java/com/noorq/casser/config/CasserSettings.java b/src/main/java/net/helenus/config/HelenusSettings.java similarity index 77% rename from src/main/java/com/noorq/casser/config/CasserSettings.java rename to src/main/java/net/helenus/config/HelenusSettings.java index bd25c59..c5fc17b 100644 --- a/src/main/java/com/noorq/casser/config/CasserSettings.java +++ b/src/main/java/net/helenus/config/HelenusSettings.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.config; +package net.helenus.config; import java.lang.reflect.Method; import java.util.function.Function; -import com.noorq.casser.core.DslInstantiator; -import com.noorq.casser.core.MapperInstantiator; +import net.helenus.core.DslInstantiator; +import net.helenus.core.MapperInstantiator; -public interface CasserSettings { +public interface HelenusSettings { Function getPropertyToColumnConverter(); - + Function getGetterMethodDetector(); DslInstantiator getDslInstantiator(); - + MapperInstantiator getMapperInstantiator(); } diff --git a/src/main/java/com/noorq/casser/core/AbstractSessionOperations.java b/src/main/java/net/helenus/core/AbstractSessionOperations.java similarity index 68% rename from src/main/java/com/noorq/casser/core/AbstractSessionOperations.java rename to src/main/java/net/helenus/core/AbstractSessionOperations.java index 5b2d9e1..36a5145 100644 --- a/src/main/java/com/noorq/casser/core/AbstractSessionOperations.java +++ b/src/main/java/net/helenus/core/AbstractSessionOperations.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,141 +13,136 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.io.PrintStream; import java.util.concurrent.Executor; +import com.datastax.driver.core.schemabuilder.SchemaStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.datastax.driver.core.PreparedStatement; -import com.datastax.driver.core.RegularStatement; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.ResultSetFuture; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.Statement; +import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.google.common.util.concurrent.ListenableFuture; -import com.noorq.casser.mapping.value.ColumnValuePreparer; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.support.CasserException; + +import net.helenus.mapping.value.ColumnValuePreparer; +import net.helenus.mapping.value.ColumnValueProvider; +import net.helenus.support.HelenusException; + +import javax.xml.validation.Schema; public abstract class AbstractSessionOperations { final Logger logger = LoggerFactory.getLogger(getClass()); - + abstract public Session currentSession(); - + abstract public String usingKeyspace(); - + abstract public boolean isShowCql(); - + abstract public PrintStream getPrintStream(); - + abstract public Executor getExecutor(); - + abstract public SessionRepository getSessionRepository(); - + abstract public ColumnValueProvider getValueProvider(); - + abstract public ColumnValuePreparer getValuePreparer(); public PreparedStatement prepare(RegularStatement statement) { - + try { - + log(statement, false); - + return currentSession().prepare(statement); - - } - catch(RuntimeException e) { + + } catch (RuntimeException e) { throw translateException(e); } - + } - + public ListenableFuture prepareAsync(RegularStatement statement) { - + try { - + log(statement, false); - + return currentSession().prepareAsync(statement); - - } - catch(RuntimeException e) { + + } catch (RuntimeException e) { throw translateException(e); } - + } - + public ResultSet execute(Statement statement, boolean showValues) { - + return executeAsync(statement, showValues).getUninterruptibly(); - + } - + public ResultSetFuture executeAsync(Statement statement, boolean showValues) { - + try { - + log(statement, showValues); - + return currentSession().executeAsync(statement); - - } - catch(RuntimeException e) { + + } catch (RuntimeException e) { throw translateException(e); } - + } void log(Statement statement, boolean showValues) { - + if (logger.isInfoEnabled()) { logger.info("Execute statement " + statement); } - - if (isShowCql()) { - - if (statement instanceof BuiltStatement) { - - BuiltStatement builtStatement = (BuiltStatement) statement; - if (showValues) { - RegularStatement regularStatement = builtStatement.setForceNoValues(true); - printCql(regularStatement.getQueryString()); - } - else { - printCql(builtStatement.getQueryString()); - } - - } - else if (statement instanceof RegularStatement) { + if (isShowCql()) { + + if (statement instanceof BuiltStatement) { + + BuiltStatement builtStatement = (BuiltStatement) statement; + + if (showValues) { + RegularStatement regularStatement = builtStatement.setForceNoValues(true); + printCql(regularStatement.getQueryString()); + } else { + printCql(builtStatement.getQueryString()); + } + + } else if (statement instanceof RegularStatement) { RegularStatement regularStatement = (RegularStatement) statement; printCql(regularStatement.getQueryString()); - } - else { + } else { printCql(statement.toString()); } - } } - + + public void cache(String key, Object value) { + } + RuntimeException translateException(RuntimeException e) { - - if (e instanceof CasserException) { + + if (e instanceof HelenusException) { return e; } - - throw new CasserException(e); + + throw new HelenusException(e); } - + void printCql(String cql) { getPrintStream().println(cql); } - + } diff --git a/src/main/java/com/noorq/casser/core/AutoDdl.java b/src/main/java/net/helenus/core/AutoDdl.java similarity index 83% rename from src/main/java/com/noorq/casser/core/AutoDdl.java rename to src/main/java/net/helenus/core/AutoDdl.java index 66af56c..d578cfd 100644 --- a/src/main/java/com/noorq/casser/core/AutoDdl.java +++ b/src/main/java/net/helenus/core/AutoDdl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; public enum AutoDdl { - VALIDATE, - UPDATE, - CREATE, - CREATE_DROP; -} \ No newline at end of file + VALIDATE, UPDATE, CREATE, CREATE_DROP; +} diff --git a/src/main/java/net/helenus/core/ConflictingUnitOfWorkException.java b/src/main/java/net/helenus/core/ConflictingUnitOfWorkException.java new file mode 100644 index 0000000..703cb58 --- /dev/null +++ b/src/main/java/net/helenus/core/ConflictingUnitOfWorkException.java @@ -0,0 +1,11 @@ +package net.helenus.core; + +public class ConflictingUnitOfWorkException extends Exception { + + final UnitOfWork uow; + + ConflictingUnitOfWorkException(UnitOfWork uow) { + this.uow = uow; + } + +} diff --git a/src/main/java/com/noorq/casser/core/DslInstantiator.java b/src/main/java/net/helenus/core/DslInstantiator.java similarity index 69% rename from src/main/java/com/noorq/casser/core/DslInstantiator.java rename to src/main/java/net/helenus/core/DslInstantiator.java index 970ea35..7a61aea 100644 --- a/src/main/java/com/noorq/casser/core/DslInstantiator.java +++ b/src/main/java/net/helenus/core/DslInstantiator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Optional; -import com.noorq.casser.core.reflect.CasserPropertyNode; +import com.datastax.driver.core.Metadata; +import net.helenus.core.reflect.HelenusPropertyNode; public interface DslInstantiator { - E instantiate(Class iface, ClassLoader classLoader, Optional parent); - + E instantiate(Class iface, ClassLoader classLoader, Optional parent, Metadata metadata); + } diff --git a/src/main/java/com/noorq/casser/core/Filter.java b/src/main/java/net/helenus/core/Filter.java similarity index 80% rename from src/main/java/com/noorq/casser/core/Filter.java rename to src/main/java/net/helenus/core/Filter.java index 83d2954..c09200c 100644 --- a/src/main/java/com/noorq/casser/core/Filter.java +++ b/src/main/java/net/helenus/core/Filter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,33 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Objects; import com.datastax.driver.core.querybuilder.Clause; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.value.ColumnValuePreparer; + +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.value.ColumnValuePreparer; public final class Filter { - private final CasserPropertyNode node; + private final HelenusPropertyNode node; private final Postulate postulate; - - private Filter(CasserPropertyNode node, Postulate postulate) { + + private Filter(HelenusPropertyNode node, Postulate postulate) { this.node = node; this.postulate = postulate; } - - public CasserPropertyNode getNode() { + + public HelenusPropertyNode getNode() { return node; } public Clause getClause(ColumnValuePreparer valuePreparer) { return postulate.getClause(node, valuePreparer); } - + public static Filter equal(Getter getter, V val) { return create(getter, Operator.EQ, val); } @@ -47,26 +48,26 @@ public final class Filter { public static Filter in(Getter getter, V... vals) { Objects.requireNonNull(getter, "empty getter"); Objects.requireNonNull(vals, "empty values"); - + if (vals.length == 0) { throw new IllegalArgumentException("values array is empty"); } - + for (int i = 0; i != vals.length; ++i) { Objects.requireNonNull(vals[i], "value[" + i + "] is empty"); } - - CasserPropertyNode node = MappingUtil.resolveMappingProperty(getter); - + + HelenusPropertyNode node = MappingUtil.resolveMappingProperty(getter); + Postulate postulate = Postulate.of(Operator.IN, vals); - + return new Filter(node, postulate); } - + public static Filter greaterThan(Getter getter, V val) { return create(getter, Operator.GT, val); } - + public static Filter lessThan(Getter getter, V val) { return create(getter, Operator.LT, val); } @@ -83,24 +84,24 @@ public final class Filter { Objects.requireNonNull(getter, "empty getter"); Objects.requireNonNull(postulate, "empty operator"); - CasserPropertyNode node = MappingUtil.resolveMappingProperty(getter); - + HelenusPropertyNode node = MappingUtil.resolveMappingProperty(getter); + return new Filter(node, postulate); } - + public static Filter create(Getter getter, Operator op, V val) { Objects.requireNonNull(getter, "empty getter"); Objects.requireNonNull(op, "empty op"); Objects.requireNonNull(val, "empty value"); - + if (op == Operator.IN) { throw new IllegalArgumentException("invalid usage of the 'in' operator, use Filter.in() static method"); } - - CasserPropertyNode node = MappingUtil.resolveMappingProperty(getter); - + + HelenusPropertyNode node = MappingUtil.resolveMappingProperty(getter); + Postulate postulate = Postulate.of(op, val); - + return new Filter(node, postulate); } @@ -108,7 +109,5 @@ public final class Filter { public String toString() { return node.getColumnName() + postulate.toString(); } - - - + } diff --git a/src/main/java/com/noorq/casser/core/Getter.java b/src/main/java/net/helenus/core/Getter.java similarity index 88% rename from src/main/java/com/noorq/casser/core/Getter.java rename to src/main/java/net/helenus/core/Getter.java index fda1480..cad7e03 100644 --- a/src/main/java/com/noorq/casser/core/Getter.java +++ b/src/main/java/net/helenus/core/Getter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; public interface Getter { V get(); - + } diff --git a/src/main/java/net/helenus/core/Helenus.java b/src/main/java/net/helenus/core/Helenus.java new file mode 100644 index 0000000..03f3028 --- /dev/null +++ b/src/main/java/net/helenus/core/Helenus.java @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.core; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.Session; + +import net.helenus.config.DefaultHelenusSettings; +import net.helenus.config.HelenusSettings; +import net.helenus.core.reflect.DslExportable; +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusEntity; +import net.helenus.support.HelenusMappingException; + +public final class Helenus { + + private static volatile HelenusSettings settings = new DefaultHelenusSettings(); + private static final ConcurrentMap, Object> dslCache = new ConcurrentHashMap, Object>(); + private static final ConcurrentMap, Metadata> metadataForEntity = new ConcurrentHashMap, Metadata>(); + private static final Set sessions = new HashSet(); + private static volatile HelenusSession singleton; + + + private Helenus() { + } + + protected static void setSession(HelenusSession session) { + sessions.add(session); + singleton = session; + } + + public static HelenusSession session() { + return singleton; + } + + public static void shutdown() { + sessions.forEach((session) -> { + session.close(); + sessions.remove(session); + }); + dslCache.clear(); + } + + public static HelenusSettings settings() { + return settings; + } + + public static HelenusSettings settings(HelenusSettings overrideSettings) { + HelenusSettings old = settings; + settings = overrideSettings; + return old; + } + + public static SessionInitializer connect(Cluster cluster) { + Session session = cluster.connect(); + return new SessionInitializer(session); + } + + public static SessionInitializer connect(Cluster cluster, String keyspace) { + Session session = cluster.connect(keyspace); + return new SessionInitializer(session); + } + + public static SessionInitializer init(Session session) { + + if (session == null) { + throw new IllegalArgumentException("empty session"); + } + + return new SessionInitializer(session); + } + + public static void clearDslCache() { + dslCache.clear(); + } + + public static E dsl(Class iface) { + return dsl(iface, null); + } + + public static E dsl(Class iface, Metadata metadata) { + return dsl(iface, iface.getClassLoader(), Optional.empty(), metadata); + } + + public static E dsl(Class iface, ClassLoader classLoader, Metadata metadata) { + return dsl(iface, classLoader, Optional.empty(), metadata); + } + + public static E dsl(Class iface, ClassLoader classLoader, Optional parent, + Metadata metadata) { + + Object instance = null; + + if (!parent.isPresent()) { + instance = dslCache.get(iface); + } + + if (instance == null) { + + instance = settings.getDslInstantiator().instantiate(iface, classLoader, parent, metadata); + + if (!parent.isPresent()) { + + Object c = dslCache.putIfAbsent(iface, instance); + if (c != null) { + instance = c; + } + + } + } + + return (E) instance; + } + + public static E map(Class iface, Map src) { + return map(iface, src, iface.getClassLoader()); + } + + public static E map(Class iface, Map src, ClassLoader classLoader) { + return settings.getMapperInstantiator().instantiate(iface, src, classLoader); + } + + public static HelenusEntity entity(Class iface) { + return entity(iface, metadataForEntity.get(iface)); + } + + public static HelenusEntity entity(Class iface, Metadata metadata) { + + Object dsl = dsl(iface, metadata); + + DslExportable e = (DslExportable) dsl; + + return e.getHelenusMappingEntity(); + } + + public static HelenusEntity resolve(Object ifaceOrDsl) { + return resolve(ifaceOrDsl, metadataForEntity.get(ifaceOrDsl)); + } + + public static HelenusEntity resolve(Object ifaceOrDsl, Metadata metadata) { + + if (ifaceOrDsl == null) { + throw new HelenusMappingException("ifaceOrDsl is null"); + } + + if (ifaceOrDsl instanceof DslExportable) { + + DslExportable e = (DslExportable) ifaceOrDsl; + + return e.getHelenusMappingEntity(); + } + + if (ifaceOrDsl instanceof Class) { + + Class iface = (Class) ifaceOrDsl; + + if (!iface.isInterface()) { + throw new HelenusMappingException("class is not an interface " + iface); + } + + metadataForEntity.putIfAbsent(iface, metadata); + return entity(iface, metadata); + + } + + throw new HelenusMappingException("unknown dsl object or mapping interface " + ifaceOrDsl); + } + +} diff --git a/src/main/java/com/noorq/casser/core/CasserSession.java b/src/main/java/net/helenus/core/HelenusSession.java similarity index 52% rename from src/main/java/com/noorq/casser/core/CasserSession.java rename to src/main/java/net/helenus/core/HelenusSession.java index 87d20e3..15cff2b 100644 --- a/src/main/java/com/noorq/casser/core/CasserSession.java +++ b/src/main/java/net/helenus/core/HelenusSession.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,84 +13,87 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.io.Closeable; import java.io.PrintStream; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.function.Function; -import com.datastax.driver.core.CloseFuture; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.noorq.casser.core.operation.CountOperation; -import com.noorq.casser.core.operation.DeleteOperation; -import com.noorq.casser.core.operation.InsertOperation; -import com.noorq.casser.core.operation.SelectOperation; -import com.noorq.casser.core.operation.UpdateOperation; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.value.ColumnValuePreparer; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.mapping.value.RowColumnValueProvider; -import com.noorq.casser.mapping.value.StatementColumnValuePreparer; -import com.noorq.casser.mapping.value.ValueProviderMap; -import com.noorq.casser.support.Fun; -import com.noorq.casser.support.Fun.Tuple1; -import com.noorq.casser.support.Fun.Tuple2; -import com.noorq.casser.support.Fun.Tuple6; +import com.datastax.driver.core.*; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; -public final class CasserSession extends AbstractSessionOperations implements Closeable { +import net.helenus.core.operation.*; +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.value.*; +import net.helenus.support.Fun; +import net.helenus.support.Fun.Tuple1; +import net.helenus.support.Fun.Tuple2; +import net.helenus.support.Fun.Tuple6; + +public final class HelenusSession extends AbstractSessionOperations implements Closeable { + + private final int MAX_CACHE_SIZE = 10000; + private final int MAX_CACHE_EXPIRE_SECONDS = 600; private final Session session; + private final CodecRegistry registry; private volatile String usingKeyspace; private volatile boolean showCql; private final PrintStream printStream; private final SessionRepository sessionRepository; private final Executor executor; private final boolean dropSchemaOnClose; - + private final RowColumnValueProvider valueProvider; private final StatementColumnValuePreparer valuePreparer; - - CasserSession(Session session, - String usingKeyspace, - boolean showCql, - PrintStream printStream, - SessionRepositoryBuilder sessionRepositoryBuilder, - Executor executor, - boolean dropSchemaOnClose) { + private final Metadata metadata; + private final Cache sessionCache; + private UnitOfWork currentUnitOfWork; + + HelenusSession(Session session, String usingKeyspace, CodecRegistry registry, boolean showCql, + PrintStream printStream, SessionRepositoryBuilder sessionRepositoryBuilder, Executor executor, + boolean dropSchemaOnClose) { this.session = session; - this.usingKeyspace = Objects.requireNonNull(usingKeyspace, "keyspace needs to be selected before creating session"); + this.registry = registry == null ? CodecRegistry.DEFAULT_INSTANCE : registry; + this.usingKeyspace = Objects.requireNonNull(usingKeyspace, + "keyspace needs to be selected before creating session"); this.showCql = showCql; this.printStream = printStream; this.sessionRepository = sessionRepositoryBuilder.build(); this.executor = executor; this.dropSchemaOnClose = dropSchemaOnClose; - + this.valueProvider = new RowColumnValueProvider(this.sessionRepository); this.valuePreparer = new StatementColumnValuePreparer(this.sessionRepository); + this.metadata = session.getCluster().getMetadata(); + this.sessionCache = CacheBuilder.newBuilder().maximumSize(MAX_CACHE_SIZE) + .expireAfterAccess(MAX_CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS).recordStats().build(); + this.currentUnitOfWork = null; } - + @Override public Session currentSession() { return session; } - + @Override public String usingKeyspace() { return usingKeyspace; } - - public CasserSession useKeyspace(String keyspace) { + + public HelenusSession useKeyspace(String keyspace) { session.execute(SchemaUtil.use(keyspace, false)); this.usingKeyspace = keyspace; return this; } - + @Override public boolean isShowCql() { return showCql; @@ -101,16 +104,16 @@ public final class CasserSession extends AbstractSessionOperations implements Cl return printStream; } - public CasserSession showCql() { + public HelenusSession showCql() { this.showCql = true; return this; } - - public CasserSession showCql(boolean showCql) { + + public HelenusSession showCql(boolean showCql) { this.showCql = showCql; return this; } - + @Override public Executor getExecutor() { return executor; @@ -125,125 +128,155 @@ public final class CasserSession extends AbstractSessionOperations implements Cl public ColumnValueProvider getValueProvider() { return valueProvider; } - + @Override public ColumnValuePreparer getValuePreparer() { return valuePreparer; } + public Metadata getMetadata() { return metadata; } + + public synchronized UnitOfWork begin() { + if (currentUnitOfWork == null) { + currentUnitOfWork = new UnitOfWork(this); + return currentUnitOfWork; + } else { + return currentUnitOfWork.begin(); + } + } + + public synchronized void commit() throws ConflictingUnitOfWorkException { + if (currentUnitOfWork != null) { + currentUnitOfWork.commit(); + currentUnitOfWork = null; + } + } + + public synchronized void abort() { + if (currentUnitOfWork != null) { + currentUnitOfWork.abort(); + currentUnitOfWork = null; + } + } + + public void cache(String key, Object value) { + sessionCache.put(key, value); // ttl + } + public SelectOperation select(Class entityClass) { - - Objects.requireNonNull(entityClass, "entityClass is empty"); + + Objects.requireNonNull(entityClass, "entityClass is empty"); ColumnValueProvider valueProvider = getValueProvider(); - CasserEntity entity = Casser.entity(entityClass); - + HelenusEntity entity = Helenus.entity(entityClass); + return new SelectOperation(this, entity, (r) -> { - + Map map = new ValueProviderMap(r, valueProvider, entity); - return (E) Casser.map(entityClass, map); - + return (E) Helenus.map(entityClass, map); + }); } - + public SelectOperation select() { return new SelectOperation(this); } - + public SelectOperation selectAll(Class entityClass) { Objects.requireNonNull(entityClass, "entityClass is empty"); - return new SelectOperation(this, Casser.entity(entityClass)); + return new SelectOperation(this, Helenus.entity(entityClass)); } - + public SelectOperation selectAll(Class entityClass, Function rowMapper) { Objects.requireNonNull(entityClass, "entityClass is empty"); Objects.requireNonNull(rowMapper, "rowMapper is empty"); - return new SelectOperation(this, Casser.entity(entityClass), rowMapper); + return new SelectOperation(this, Helenus.entity(entityClass), rowMapper); } - + public SelectOperation> select(Getter getter1) { Objects.requireNonNull(getter1, "field 1 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); return new SelectOperation>(this, new Mappers.Mapper1(getValueProvider(), p1), p1); } public SelectOperation> select(Getter getter1, Getter getter2) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - return new SelectOperation>(this, new Mappers.Mapper2(getValueProvider(), p1, p2), p1, p2); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + return new SelectOperation>(this, new Mappers.Mapper2(getValueProvider(), p1, p2), + p1, p2); } - public SelectOperation> select(Getter getter1, Getter getter2, Getter getter3) { + public SelectOperation> select(Getter getter1, Getter getter2, + Getter getter3) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); Objects.requireNonNull(getter3, "field 3 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - CasserPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); - return new SelectOperation>(this, new Mappers.Mapper3(getValueProvider(), p1, p2, p3), p1, p2, p3); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + HelenusPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); + return new SelectOperation>(this, + new Mappers.Mapper3(getValueProvider(), p1, p2, p3), p1, p2, p3); } - public SelectOperation> select( - Getter getter1, Getter getter2, Getter getter3, Getter getter4) { + public SelectOperation> select(Getter getter1, Getter getter2, + Getter getter3, Getter getter4) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); Objects.requireNonNull(getter3, "field 3 is empty"); Objects.requireNonNull(getter4, "field 4 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - CasserPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); - CasserPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); - return new SelectOperation>(this, new Mappers.Mapper4(getValueProvider(), p1, p2, p3, p4), p1, p2, p3, p4); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + HelenusPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); + HelenusPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); + return new SelectOperation>(this, + new Mappers.Mapper4(getValueProvider(), p1, p2, p3, p4), p1, p2, p3, p4); } - public SelectOperation> select( - Getter getter1, Getter getter2, Getter getter3, Getter getter4, Getter getter5) { + public SelectOperation> select(Getter getter1, + Getter getter2, Getter getter3, Getter getter4, Getter getter5) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); Objects.requireNonNull(getter3, "field 3 is empty"); Objects.requireNonNull(getter4, "field 4 is empty"); Objects.requireNonNull(getter5, "field 5 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - CasserPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); - CasserPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); - CasserPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); - return new SelectOperation>(this, - new Mappers.Mapper5(getValueProvider(), p1, p2, p3, p4, p5), - p1, p2, p3, p4, p5); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + HelenusPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); + HelenusPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); + HelenusPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); + return new SelectOperation>(this, + new Mappers.Mapper5(getValueProvider(), p1, p2, p3, p4, p5), p1, p2, p3, p4, p5); } - - public SelectOperation> select( - Getter getter1, Getter getter2, Getter getter3, - Getter getter4, Getter getter5, Getter getter6) { + + public SelectOperation> select(Getter getter1, + Getter getter2, Getter getter3, Getter getter4, Getter getter5, Getter getter6) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); Objects.requireNonNull(getter3, "field 3 is empty"); Objects.requireNonNull(getter4, "field 4 is empty"); Objects.requireNonNull(getter5, "field 5 is empty"); Objects.requireNonNull(getter6, "field 6 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - CasserPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); - CasserPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); - CasserPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); - CasserPropertyNode p6 = MappingUtil.resolveMappingProperty(getter6); - return new SelectOperation>(this, - new Mappers.Mapper6(getValueProvider(), p1, p2, p3, p4, p5, p6), - p1, p2, p3, p4, p5, p6); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + HelenusPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); + HelenusPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); + HelenusPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); + HelenusPropertyNode p6 = MappingUtil.resolveMappingProperty(getter6); + return new SelectOperation>(this, + new Mappers.Mapper6(getValueProvider(), p1, p2, p3, p4, p5, p6), p1, p2, p3, p4, + p5, p6); } public SelectOperation> select( - Getter getter1, Getter getter2, Getter getter3, - Getter getter4, Getter getter5, Getter getter6, - Getter getter7) { + Getter getter1, Getter getter2, Getter getter3, Getter getter4, Getter getter5, + Getter getter6, Getter getter7) { Objects.requireNonNull(getter1, "field 1 is empty"); Objects.requireNonNull(getter2, "field 2 is empty"); Objects.requireNonNull(getter3, "field 3 is empty"); @@ -251,95 +284,93 @@ public final class CasserSession extends AbstractSessionOperations implements Cl Objects.requireNonNull(getter5, "field 5 is empty"); Objects.requireNonNull(getter6, "field 6 is empty"); Objects.requireNonNull(getter7, "field 7 is empty"); - - CasserPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); - CasserPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); - CasserPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); - CasserPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); - CasserPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); - CasserPropertyNode p6 = MappingUtil.resolveMappingProperty(getter6); - CasserPropertyNode p7 = MappingUtil.resolveMappingProperty(getter7); - return new SelectOperation>(this, - new Mappers.Mapper7( - getValueProvider(), - p1, p2, p3, p4, p5, p6, p7), - p1, p2, p3, p4, p5, p6, p7); + + HelenusPropertyNode p1 = MappingUtil.resolveMappingProperty(getter1); + HelenusPropertyNode p2 = MappingUtil.resolveMappingProperty(getter2); + HelenusPropertyNode p3 = MappingUtil.resolveMappingProperty(getter3); + HelenusPropertyNode p4 = MappingUtil.resolveMappingProperty(getter4); + HelenusPropertyNode p5 = MappingUtil.resolveMappingProperty(getter5); + HelenusPropertyNode p6 = MappingUtil.resolveMappingProperty(getter6); + HelenusPropertyNode p7 = MappingUtil.resolveMappingProperty(getter7); + return new SelectOperation>(this, + new Mappers.Mapper7(getValueProvider(), p1, p2, p3, p4, p5, p6, p7), p1, p2, + p3, p4, p5, p6, p7); } - + public CountOperation count() { return new CountOperation(this); } - + public CountOperation count(Object dsl) { Objects.requireNonNull(dsl, "dsl is empty"); - return new CountOperation(this, Casser.resolve(dsl)); + return new CountOperation(this, Helenus.resolve(dsl)); } - + public UpdateOperation update() { return new UpdateOperation(this); } - + public UpdateOperation update(Getter getter, V v) { Objects.requireNonNull(getter, "field is empty"); Objects.requireNonNull(v, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(getter); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(getter); + return new UpdateOperation(this, p, v); } - + public InsertOperation insert() { return new InsertOperation(this, true); } - + public InsertOperation insert(Object pojo) { Objects.requireNonNull(pojo, "pojo is empty"); - + Class iface = MappingUtil.getMappingInterface(pojo); - CasserEntity entity = Casser.entity(iface); - + HelenusEntity entity = Helenus.entity(iface); + return new InsertOperation(this, entity, pojo, true); } - + public InsertOperation upsert() { return new InsertOperation(this, false); } - + public InsertOperation upsert(Object pojo) { Objects.requireNonNull(pojo, "pojo is empty"); - + Class iface = MappingUtil.getMappingInterface(pojo); - CasserEntity entity = Casser.entity(iface); - + HelenusEntity entity = Helenus.entity(iface); + return new InsertOperation(this, entity, pojo, false); } - + public DeleteOperation delete() { return new DeleteOperation(this); } - + public DeleteOperation delete(Object dsl) { Objects.requireNonNull(dsl, "dsl is empty"); - return new DeleteOperation(this, Casser.resolve(dsl)); + return new DeleteOperation(this, Helenus.resolve(dsl)); } - + public Session getSession() { return session; } public void close() { - + if (session.isClosed()) { return; } - + if (dropSchemaOnClose) { dropSchema(); } - + session.close(); } - + public CloseFuture closeAsync() { if (!session.isClosed() && dropSchemaOnClose) { @@ -348,31 +379,27 @@ public final class CasserSession extends AbstractSessionOperations implements Cl return session.closeAsync(); } - + private void dropSchema() { - + sessionRepository.entities().forEach(e -> dropEntity(e)); - + } - - private void dropEntity(CasserEntity entity) { - - switch(entity.getType()) { - - case TABLE: - execute(SchemaUtil.dropTable(entity), true); - break; - - case UDT: - execute(SchemaUtil.dropUserType(entity), true); - break; - + + private void dropEntity(HelenusEntity entity) { + + switch (entity.getType()) { + + case TABLE : + execute(SchemaUtil.dropTable(entity), true); + break; + + case UDT : + execute(SchemaUtil.dropUserType(entity), true); + break; + } - } - - - } diff --git a/src/main/java/com/noorq/casser/core/CasserValidator.java b/src/main/java/net/helenus/core/HelenusValidator.java similarity index 61% rename from src/main/java/com/noorq/casser/core/CasserValidator.java rename to src/main/java/net/helenus/core/HelenusValidator.java index ddcd9ec..7b176e9 100644 --- a/src/main/java/com/noorq/casser/core/CasserValidator.java +++ b/src/main/java/net/helenus/core/HelenusValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,41 +13,39 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.lang.annotation.Annotation; import javax.validation.ConstraintValidator; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.support.CasserException; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.mapping.HelenusProperty; +import net.helenus.support.HelenusException; +import net.helenus.support.HelenusMappingException; -public enum CasserValidator implements PropertyValueValidator { +public enum HelenusValidator implements PropertyValueValidator { INSTANCE; - - public void validate(CasserProperty prop, Object value) { - + + public void validate(HelenusProperty prop, Object value) { + for (ConstraintValidator validator : prop.getValidators()) { - + ConstraintValidator typeless = (ConstraintValidator) validator; - - + boolean valid = false; - + try { valid = typeless.isValid(value, null); + } catch (ClassCastException e) { + throw new HelenusMappingException("validator was used for wrong type '" + value + "' in " + prop, e); } - catch(ClassCastException e) { - throw new CasserMappingException("validator was used for wrong type '" + value + "' in " + prop, e); - } - + if (!valid) { - throw new CasserException("wrong value '" + value + "' for " + prop); + throw new HelenusException("wrong value '" + value + "' for " + prop); } } - + } - + } diff --git a/src/main/java/com/noorq/casser/core/MapperInstantiator.java b/src/main/java/net/helenus/core/MapperInstantiator.java similarity index 79% rename from src/main/java/com/noorq/casser/core/MapperInstantiator.java rename to src/main/java/net/helenus/core/MapperInstantiator.java index 42c322d..6074212 100644 --- a/src/main/java/com/noorq/casser/core/MapperInstantiator.java +++ b/src/main/java/net/helenus/core/MapperInstantiator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Map; public interface MapperInstantiator { - E instantiate(Class iface, Map src, ClassLoader classLoader); - + E instantiate(Class iface, Map src, ClassLoader classLoader); + } diff --git a/src/main/java/net/helenus/core/Mappers.java b/src/main/java/net/helenus/core/Mappers.java new file mode 100644 index 0000000..09881b8 --- /dev/null +++ b/src/main/java/net/helenus/core/Mappers.java @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.core; + +import java.util.function.Function; + +import com.datastax.driver.core.Row; + +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.value.ColumnValueProvider; +import net.helenus.support.Fun; + +public final class Mappers { + + private Mappers() { + } + + public final static class Mapper1 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1; + + public Mapper1(ColumnValueProvider provider, HelenusPropertyNode p1) { + this.provider = provider; + this.p1 = p1.getProperty(); + } + + @Override + public Fun.Tuple1 apply(Row row) { + return new Fun.Tuple1(provider.getColumnValue(row, 0, p1)); + } + } + + public final static class Mapper2 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1; + private final HelenusProperty p2; + + public Mapper2(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + } + + @Override + public Fun.Tuple2 apply(Row row) { + return new Fun.Tuple2(provider.getColumnValue(row, 0, p1), provider.getColumnValue(row, 1, p2)); + } + } + + public final static class Mapper3 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1; + private final HelenusProperty p2; + private final HelenusProperty p3; + + public Mapper3(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2, + HelenusPropertyNode p3) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + this.p3 = p3.getProperty(); + } + + @Override + public Fun.Tuple3 apply(Row row) { + return new Fun.Tuple3(provider.getColumnValue(row, 0, p1), provider.getColumnValue(row, 1, p2), + provider.getColumnValue(row, 2, p3)); + } + } + + public final static class Mapper4 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1; + private final HelenusProperty p2; + private final HelenusProperty p3; + private final HelenusProperty p4; + + public Mapper4(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2, + HelenusPropertyNode p3, HelenusPropertyNode p4) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + this.p3 = p3.getProperty(); + this.p4 = p4.getProperty(); + } + + @Override + public Fun.Tuple4 apply(Row row) { + return new Fun.Tuple4(provider.getColumnValue(row, 0, p1), provider.getColumnValue(row, 1, p2), + provider.getColumnValue(row, 2, p3), provider.getColumnValue(row, 3, p4)); + } + } + + public final static class Mapper5 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1, p2, p3, p4, p5; + + public Mapper5(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2, + HelenusPropertyNode p3, HelenusPropertyNode p4, HelenusPropertyNode p5) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + this.p3 = p3.getProperty(); + this.p4 = p4.getProperty(); + this.p5 = p5.getProperty(); + } + + @Override + public Fun.Tuple5 apply(Row row) { + return new Fun.Tuple5(provider.getColumnValue(row, 0, p1), + provider.getColumnValue(row, 1, p2), provider.getColumnValue(row, 2, p3), + provider.getColumnValue(row, 3, p4), provider.getColumnValue(row, 4, p5)); + } + } + + public final static class Mapper6 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1, p2, p3, p4, p5, p6; + + public Mapper6(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2, + HelenusPropertyNode p3, HelenusPropertyNode p4, HelenusPropertyNode p5, HelenusPropertyNode p6) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + this.p3 = p3.getProperty(); + this.p4 = p4.getProperty(); + this.p5 = p5.getProperty(); + this.p6 = p6.getProperty(); + } + + @Override + public Fun.Tuple6 apply(Row row) { + return new Fun.Tuple6(provider.getColumnValue(row, 0, p1), + provider.getColumnValue(row, 1, p2), provider.getColumnValue(row, 2, p3), + provider.getColumnValue(row, 3, p4), provider.getColumnValue(row, 4, p5), + provider.getColumnValue(row, 5, p6)); + } + } + + public final static class Mapper7 implements Function> { + + private final ColumnValueProvider provider; + private final HelenusProperty p1, p2, p3, p4, p5, p6, p7; + + public Mapper7(ColumnValueProvider provider, HelenusPropertyNode p1, HelenusPropertyNode p2, + HelenusPropertyNode p3, HelenusPropertyNode p4, HelenusPropertyNode p5, HelenusPropertyNode p6, + HelenusPropertyNode p7) { + this.provider = provider; + this.p1 = p1.getProperty(); + this.p2 = p2.getProperty(); + this.p3 = p3.getProperty(); + this.p4 = p4.getProperty(); + this.p5 = p5.getProperty(); + this.p6 = p6.getProperty(); + this.p7 = p7.getProperty(); + } + + @Override + public Fun.Tuple7 apply(Row row) { + return new Fun.Tuple7(provider.getColumnValue(row, 0, p1), + provider.getColumnValue(row, 1, p2), provider.getColumnValue(row, 2, p3), + provider.getColumnValue(row, 3, p4), provider.getColumnValue(row, 4, p5), + provider.getColumnValue(row, 5, p6), provider.getColumnValue(row, 6, p7)); + } + } + +} diff --git a/src/main/java/com/noorq/casser/core/Operator.java b/src/main/java/net/helenus/core/Operator.java similarity index 92% rename from src/main/java/com/noorq/casser/core/Operator.java rename to src/main/java/net/helenus/core/Operator.java index e096384..ea590f4 100644 --- a/src/main/java/com/noorq/casser/core/Operator.java +++ b/src/main/java/net/helenus/core/Operator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.HashMap; import java.util.Map; @@ -21,7 +21,7 @@ import java.util.Map; public enum Operator { EQ("=="), - + IN("in"), GT(">"), @@ -31,17 +31,17 @@ public enum Operator { GTE(">="), LTE("<="); - + private final String name; - + private final static Map indexByName = new HashMap(); - + static { for (Operator fo : Operator.values()) { indexByName.put(fo.getName(), fo); } } - + private Operator(String name) { this.name = name; } @@ -49,9 +49,9 @@ public enum Operator { public String getName() { return name; } - + public static Operator findByOperator(String name) { return indexByName.get(name); } - + } diff --git a/src/main/java/com/noorq/casser/core/Ordered.java b/src/main/java/net/helenus/core/Ordered.java similarity index 53% rename from src/main/java/com/noorq/casser/core/Ordered.java rename to src/main/java/net/helenus/core/Ordered.java index c85239e..2fd7034 100644 --- a/src/main/java/com/noorq/casser/core/Ordered.java +++ b/src/main/java/net/helenus/core/Ordered.java @@ -1,14 +1,15 @@ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Objects; import com.datastax.driver.core.querybuilder.Ordering; import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.OrderingDirection; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.OrderingDirection; +import net.helenus.support.HelenusMappingException; public final class Ordered { @@ -19,29 +20,30 @@ public final class Ordered { this.getter = getter; this.direction = direction; } - + public Ordering getOrdering() { - + Objects.requireNonNull(getter, "property is null"); Objects.requireNonNull(direction, "direction is null"); - - CasserPropertyNode propNode = MappingUtil.resolveMappingProperty(getter); - + + HelenusPropertyNode propNode = MappingUtil.resolveMappingProperty(getter); + if (propNode.getProperty().getColumnType() != ColumnType.CLUSTERING_COLUMN) { - throw new CasserMappingException("property must be a clustering column " + propNode.getProperty().getPropertyName()); + throw new HelenusMappingException( + "property must be a clustering column " + propNode.getProperty().getPropertyName()); } - - switch(direction) { - - case ASC: + + switch (direction) { + + case ASC : return QueryBuilder.asc(propNode.getColumnName()); - - case DESC: + + case DESC : return QueryBuilder.desc(propNode.getColumnName()); - + } - - throw new CasserMappingException("invalid direction " + direction); + + throw new HelenusMappingException("invalid direction " + direction); } - + } diff --git a/src/main/java/net/helenus/core/Postulate.java b/src/main/java/net/helenus/core/Postulate.java new file mode 100644 index 0000000..3e2f70e --- /dev/null +++ b/src/main/java/net/helenus/core/Postulate.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.core; + +import com.datastax.driver.core.querybuilder.Clause; +import com.datastax.driver.core.querybuilder.QueryBuilder; + +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.value.ColumnValuePreparer; +import net.helenus.support.HelenusMappingException; + +public final class Postulate { + + private final Operator operator; + private final V[] values; + + protected Postulate(Operator op, V[] values) { + this.operator = op; + this.values = values; + } + + public static Postulate of(Operator op, V... values) { + return new Postulate(op, values); + } + + public Clause getClause(HelenusPropertyNode node, ColumnValuePreparer valuePreparer) { + + switch (operator) { + + case EQ : + return QueryBuilder.eq(node.getColumnName(), + valuePreparer.prepareColumnValue(values[0], node.getProperty())); + + case IN : + Object[] preparedValues = new Object[values.length]; + for (int i = 0; i != values.length; ++i) { + preparedValues[i] = valuePreparer.prepareColumnValue(values[i], node.getProperty()); + } + return QueryBuilder.in(node.getColumnName(), preparedValues); + + case LT : + return QueryBuilder.lt(node.getColumnName(), + valuePreparer.prepareColumnValue(values[0], node.getProperty())); + + case LTE : + return QueryBuilder.lte(node.getColumnName(), + valuePreparer.prepareColumnValue(values[0], node.getProperty())); + + case GT : + return QueryBuilder.gt(node.getColumnName(), + valuePreparer.prepareColumnValue(values[0], node.getProperty())); + + case GTE : + return QueryBuilder.gte(node.getColumnName(), + valuePreparer.prepareColumnValue(values[0], node.getProperty())); + + default : + throw new HelenusMappingException("unknown filter operation " + operator); + } + + } + + @Override + public String toString() { + + if (operator == Operator.IN) { + + if (values == null) { + return "in()"; + } + + int len = values.length; + StringBuilder b = new StringBuilder(); + b.append("in("); + for (int i = 0; i != len; i++) { + if (b.length() > 3) { + b.append(", "); + } + b.append(String.valueOf(values[i])); + } + return b.append(')').toString(); + + } + + return operator.getName() + values[0]; + + } + +} diff --git a/src/main/java/com/noorq/casser/core/PropertyValueValidator.java b/src/main/java/net/helenus/core/PropertyValueValidator.java similarity index 77% rename from src/main/java/com/noorq/casser/core/PropertyValueValidator.java rename to src/main/java/net/helenus/core/PropertyValueValidator.java index 33678ed..abf97d1 100644 --- a/src/main/java/com/noorq/casser/core/PropertyValueValidator.java +++ b/src/main/java/net/helenus/core/PropertyValueValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; -import com.noorq.casser.mapping.CasserProperty; +import net.helenus.mapping.HelenusProperty; public interface PropertyValueValidator { - void validate(CasserProperty prop, Object value); - + void validate(HelenusProperty prop, Object value); + } diff --git a/src/main/java/com/noorq/casser/core/Query.java b/src/main/java/net/helenus/core/Query.java similarity index 72% rename from src/main/java/com/noorq/casser/core/Query.java rename to src/main/java/net/helenus/core/Query.java index affb7c8..039ee39 100644 --- a/src/main/java/com/noorq/casser/core/Query.java +++ b/src/main/java/net/helenus/core/Query.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.List; import java.util.Map; @@ -21,10 +21,11 @@ import java.util.Objects; import com.datastax.driver.core.querybuilder.BindMarker; import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.noorq.casser.mapping.OrderingDirection; + +import net.helenus.mapping.OrderingDirection; /** - * Sugar methods for the queries + * Sugar methods for the queries * */ @@ -34,11 +35,11 @@ public final class Query { } public static BindMarker marker() { - return QueryBuilder.bindMarker(); + return QueryBuilder.bindMarker(); } public static BindMarker marker(String name) { - return QueryBuilder.bindMarker(name); + return QueryBuilder.bindMarker(name); } public static Ordered asc(Getter getter) { @@ -52,19 +53,19 @@ public final class Query { public static Postulate eq(V val) { return Postulate.of(Operator.EQ, val); } - + public static Postulate lt(V val) { return Postulate.of(Operator.LT, val); } - + public static Postulate lte(V val) { return Postulate.of(Operator.LTE, val); } - + public static Postulate gt(V val) { return Postulate.of(Operator.GT, val); } - + public static Postulate gte(V val) { return Postulate.of(Operator.GTE, val); } @@ -72,34 +73,32 @@ public final class Query { public static Postulate in(V[] vals) { return new Postulate(Operator.IN, vals); } - - public static Getter getIdx(Getter> listGetter, int index) { - Objects.requireNonNull(listGetter, "listGetter is null"); - - return new Getter() { + + public static Getter getIdx(Getter> listGetter, int index) { + Objects.requireNonNull(listGetter, "listGetter is null"); + + return new Getter() { @Override public V get() { return listGetter.get().get(index); } - - }; - } - - public static Getter get(Getter> mapGetter, K k) { - Objects.requireNonNull(mapGetter, "mapGetter is null"); - Objects.requireNonNull(k, "key is null"); - - return new Getter() { + + }; + } + + public static Getter get(Getter> mapGetter, K k) { + Objects.requireNonNull(mapGetter, "mapGetter is null"); + Objects.requireNonNull(k, "key is null"); + + return new Getter() { @Override public V get() { return mapGetter.get().get(k); } - - }; - } - - + + }; + } } diff --git a/src/main/java/net/helenus/core/SchemaUtil.java b/src/main/java/net/helenus/core/SchemaUtil.java new file mode 100644 index 0000000..f971b2f --- /dev/null +++ b/src/main/java/net/helenus/core/SchemaUtil.java @@ -0,0 +1,365 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.core; + +import java.util.*; +import java.util.stream.Collectors; + +import com.datastax.driver.core.*; +import com.datastax.driver.core.IndexMetadata; +import com.datastax.driver.core.schemabuilder.*; +import com.datastax.driver.core.schemabuilder.Create.Options; + +import net.helenus.mapping.*; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.type.OptionalColumnMetadata; +import net.helenus.support.CqlUtil; +import net.helenus.support.HelenusMappingException; + +public final class SchemaUtil { + + private SchemaUtil() { + } + + public static RegularStatement use(String keyspace, boolean forceQuote) { + if (forceQuote) { + return new SimpleStatement("USE" + CqlUtil.forceQuote(keyspace)); + } else { + return new SimpleStatement("USE " + keyspace); + } + } + + public static SchemaStatement createUserType(HelenusEntity entity) { + + if (entity.getType() != HelenusEntityType.UDT) { + throw new HelenusMappingException("expected UDT entity " + entity); + } + + CreateType create = SchemaBuilder.createType(entity.getName().toCql()); + + for (HelenusProperty prop : entity.getOrderedProperties()) { + + ColumnType columnType = prop.getColumnType(); + + if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { + throw new HelenusMappingException("primary key columns are not supported in UserDefinedType for " + + prop.getPropertyName() + " in entity " + entity); + } + + try { + prop.getDataType().addColumn(create, prop.getColumnName()); + } catch (IllegalArgumentException e) { + throw new HelenusMappingException("invalid column name '" + prop.getColumnName() + "' in entity '" + + entity.getName().getName() + "'", e); + } + } + + return create; + } + + public static List alterUserType(UserType userType, HelenusEntity entity, + boolean dropUnusedColumns) { + + if (entity.getType() != HelenusEntityType.UDT) { + throw new HelenusMappingException("expected UDT entity " + entity); + } + + List result = new ArrayList(); + + /** + * TODO: In future replace SchemaBuilder.alterTable by SchemaBuilder.alterType + * when it will exist + */ + + Alter alter = SchemaBuilder.alterTable(entity.getName().toCql()); + + final Set visitedColumns = dropUnusedColumns ? new HashSet() : Collections.emptySet(); + + for (HelenusProperty prop : entity.getOrderedProperties()) { + + String columnName = prop.getColumnName().getName(); + + if (dropUnusedColumns) { + visitedColumns.add(columnName); + } + + ColumnType columnType = prop.getColumnType(); + + if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { + continue; + } + + DataType dataType = userType.getFieldType(columnName); + SchemaStatement stmt = prop.getDataType().alterColumn(alter, prop.getColumnName(), + optional(columnName, dataType)); + + if (stmt != null) { + result.add(stmt); + } + + } + + if (dropUnusedColumns) { + for (String field : userType.getFieldNames()) { + if (!visitedColumns.contains(field)) { + + result.add(alter.dropColumn(field)); + + } + } + } + + return result; + + } + + public static SchemaStatement dropUserType(HelenusEntity entity) { + + if (entity.getType() != HelenusEntityType.UDT) { + throw new HelenusMappingException("expected UDT entity " + entity); + } + + return SchemaBuilder.dropType(entity.getName().toCql()).ifExists(); + + } + + public static SchemaStatement dropUserType(UserType type) { + + return SchemaBuilder.dropType(type.getTypeName()).ifExists(); + } + + public static SchemaStatement createTable(HelenusEntity entity) { + + if (entity.getType() != HelenusEntityType.TABLE) { + throw new HelenusMappingException("expected table entity " + entity); + } + + // NOTE: There is a bug in the normal path of createTable where the + // "cache" is set too early and never unset preventing more than + // one column on a table. + // SchemaBuilder.createTable(entity.getName().toCql()); + CreateTable create = new CreateTable(entity.getName().toCql()); + + create.ifNotExists(); + + List clusteringColumns = new ArrayList(); + + for (HelenusProperty prop : entity.getOrderedProperties()) { + + ColumnType columnType = prop.getColumnType(); + + if (columnType == ColumnType.CLUSTERING_COLUMN) { + clusteringColumns.add(prop); + } + + prop.getDataType().addColumn(create, prop.getColumnName()); + + } + + if (!clusteringColumns.isEmpty()) { + Options options = create.withOptions(); + clusteringColumns + .forEach(p -> options.clusteringOrder(p.getColumnName().toCql(), mapDirection(p.getOrdering()))); + } + + return create; + + } + + public static List alterTable(TableMetadata tmd, HelenusEntity entity, boolean dropUnusedColumns) { + + if (entity.getType() != HelenusEntityType.TABLE) { + throw new HelenusMappingException("expected table entity " + entity); + } + + List result = new ArrayList(); + + Alter alter = SchemaBuilder.alterTable(entity.getName().toCql()); + + final Set visitedColumns = dropUnusedColumns ? new HashSet() : Collections.emptySet(); + + for (HelenusProperty prop : entity.getOrderedProperties()) { + + String columnName = prop.getColumnName().getName(); + + if (dropUnusedColumns) { + visitedColumns.add(columnName); + } + + ColumnType columnType = prop.getColumnType(); + + if (columnType == ColumnType.PARTITION_KEY || columnType == ColumnType.CLUSTERING_COLUMN) { + continue; + } + + ColumnMetadata columnMetadata = tmd.getColumn(columnName); + SchemaStatement stmt = prop.getDataType().alterColumn(alter, prop.getColumnName(), + optional(columnMetadata)); + + if (stmt != null) { + result.add(stmt); + } + + } + + if (dropUnusedColumns) { + for (ColumnMetadata cm : tmd.getColumns()) { + if (!visitedColumns.contains(cm.getName())) { + + result.add(alter.dropColumn(cm.getName())); + + } + } + } + + return result; + } + + public static SchemaStatement dropTable(HelenusEntity entity) { + + if (entity.getType() != HelenusEntityType.TABLE) { + throw new HelenusMappingException("expected table entity " + entity); + } + + return SchemaBuilder.dropTable(entity.getName().toCql()).ifExists(); + + } + + public static SchemaStatement createIndex(HelenusProperty prop) { + if (prop.caseSensitiveIndex()) { + return SchemaBuilder.createIndex(prop.getIndexName().get().toCql()) + .ifNotExists() + .onTable(prop.getEntity().getName().toCql()) + .andColumn(prop.getColumnName().toCql()); + } else { + return new CreateSasiIndex(prop.getIndexName().get().toCql()) + .ifNotExists() + .onTable(prop.getEntity().getName().toCql()) + .andColumn(prop.getColumnName().toCql()); + } + } + + public static List createIndexes(HelenusEntity entity) { + + return entity.getOrderedProperties().stream().filter(p -> p.getIndexName().isPresent()) + .map(p -> SchemaUtil.createIndex(p)).collect(Collectors.toList()); + + } + + public static List alterIndexes(TableMetadata tmd, HelenusEntity entity, + boolean dropUnusedIndexes) { + + List list = new ArrayList(); + + final Set visitedColumns = dropUnusedIndexes ? new HashSet() : Collections.emptySet(); + + entity.getOrderedProperties().stream().filter(p -> p.getIndexName().isPresent()).forEach(p -> { + + String columnName = p.getColumnName().getName(); + + if (dropUnusedIndexes) { + visitedColumns.add(columnName); + } + + ColumnMetadata cm = tmd.getColumn(columnName); + + if (cm != null) { + IndexMetadata im = tmd.getIndex(columnName); + if (im == null) { + list.add(createIndex(p)); + } + } else { + list.add(createIndex(p)); + } + + }); + + if (dropUnusedIndexes) { + + tmd.getColumns().stream().filter(c -> tmd.getIndex(c.getName()) != null && !visitedColumns.contains(c.getName())) + .forEach(c -> { + list.add(SchemaBuilder.dropIndex(tmd.getIndex(c.getName()).getName()).ifExists()); + + }); + + } + + return list; + + } + + public static SchemaStatement dropIndex(HelenusProperty prop) { + return SchemaBuilder.dropIndex(prop.getIndexName().get().toCql()).ifExists(); + } + + private static SchemaBuilder.Direction mapDirection(OrderingDirection o) { + switch (o) { + case ASC : + return SchemaBuilder.Direction.ASC; + case DESC : + return SchemaBuilder.Direction.DESC; + } + throw new HelenusMappingException("unknown ordering " + o); + } + + public static void throwNoMapping(HelenusProperty prop) { + + throw new HelenusMappingException( + "only primitive types and Set,List,Map collections and UserDefinedTypes are allowed, unknown type for property '" + + prop.getPropertyName() + "' type is '" + prop.getJavaType() + "' in the entity " + + prop.getEntity()); + + } + + private static OptionalColumnMetadata optional(final ColumnMetadata columnMetadata) { + if (columnMetadata != null) { + return new OptionalColumnMetadata() { + + @Override + public String getName() { + return columnMetadata.getName(); + } + + @Override + public DataType getType() { + return columnMetadata.getType(); + } + + }; + } + return null; + } + + private static OptionalColumnMetadata optional(final String name, final DataType dataType) { + if (dataType != null) { + return new OptionalColumnMetadata() { + + @Override + public String getName() { + return name; + } + + @Override + public DataType getType() { + return dataType; + } + + }; + } + return null; + } + +} diff --git a/src/main/java/com/noorq/casser/core/SessionInitializer.java b/src/main/java/net/helenus/core/SessionInitializer.java similarity index 53% rename from src/main/java/com/noorq/casser/core/SessionInitializer.java rename to src/main/java/net/helenus/core/SessionInitializer.java index 580b581..3526c86 100644 --- a/src/main/java/com/noorq/casser/core/SessionInitializer.java +++ b/src/main/java/net/helenus/core/SessionInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,56 +13,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.io.PrintStream; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.function.Consumer; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.TableMetadata; -import com.datastax.driver.core.UserType; +import com.datastax.driver.core.*; import com.google.common.util.concurrent.MoreExecutors; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserEntityType; -import com.noorq.casser.mapping.value.ColumnValuePreparer; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.support.CasserException; -import com.noorq.casser.support.PackageUtil; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusEntityType; +import net.helenus.mapping.value.ColumnValuePreparer; +import net.helenus.mapping.value.ColumnValueProvider; +import net.helenus.support.HelenusException; +import net.helenus.support.PackageUtil; public final class SessionInitializer extends AbstractSessionOperations { private final Session session; + private CodecRegistry registry; private String usingKeyspace; private boolean showCql = false; private PrintStream printStream = System.out; private Executor executor = MoreExecutors.sameThreadExecutor(); - - private SessionRepositoryBuilder sessionRepository = new SessionRepositoryBuilder(); - + + private SessionRepositoryBuilder sessionRepository; + private boolean dropUnusedColumns = false; private boolean dropUnusedIndexes = false; - + private KeyspaceMetadata keyspaceMetadata; - + private final List initList = new ArrayList(); private AutoDdl autoDdl = AutoDdl.UPDATE; - + SessionInitializer(Session session) { this.session = Objects.requireNonNull(session, "empty session"); this.usingKeyspace = session.getLoggedKeyspace(); // can be null + this.sessionRepository = new SessionRepositoryBuilder(session); } - + @Override public Session currentSession() { return session; @@ -72,7 +68,7 @@ public final class SessionInitializer extends AbstractSessionOperations { public String usingKeyspace() { return usingKeyspace; } - + @Override public Executor getExecutor() { return executor; @@ -80,24 +76,24 @@ public final class SessionInitializer extends AbstractSessionOperations { @Override public SessionRepository getSessionRepository() { - throw new CasserException("not expected to call"); + throw new HelenusException("not expected to call"); } @Override public ColumnValueProvider getValueProvider() { - throw new CasserException("not expected to call"); + throw new HelenusException("not expected to call"); } - + @Override public ColumnValuePreparer getValuePreparer() { - throw new CasserException("not expected to call"); + throw new HelenusException("not expected to call"); } public SessionInitializer showCql() { this.showCql = true; return this; } - + public SessionInitializer showCql(boolean enabled) { this.showCql = enabled; return this; @@ -112,7 +108,7 @@ public final class SessionInitializer extends AbstractSessionOperations { this.printStream = out; return this; } - + public SessionInitializer withExecutor(Executor executor) { Objects.requireNonNull(executor, "empty executor"); this.executor = executor; @@ -134,23 +130,26 @@ public final class SessionInitializer extends AbstractSessionOperations { return this; } - @Override + public SessionInitializer withCodecRegistry(CodecRegistry registry) { + this.registry = registry; + return this; + } + + @Override public boolean isShowCql() { return showCql; } - + public SessionInitializer addPackage(String packageName) { try { - PackageUtil.getClasses(packageName) - .stream() - .filter(c -> c.isInterface() && !c.isAnnotation()) - .forEach(initList::add); + PackageUtil.getClasses(packageName).stream().filter(c -> c.isInterface() && !c.isAnnotation()) + .forEach(initList::add); } catch (ClassNotFoundException e) { - throw new CasserException("fail to add package " + packageName, e); + throw new HelenusException("fail to add package " + packageName, e); } return this; } - + public SessionInitializer add(Object... dsls) { Objects.requireNonNull(dsls, "dsls is empty"); int len = dsls.length; @@ -160,7 +159,7 @@ public final class SessionInitializer extends AbstractSessionOperations { } return this; } - + public SessionInitializer autoValidate() { this.autoDdl = AutoDdl.VALIDATE; return this; @@ -185,132 +184,151 @@ public final class SessionInitializer extends AbstractSessionOperations { this.autoDdl = autoDdl; return this; } - + public SessionInitializer use(String keyspace) { session.execute(SchemaUtil.use(keyspace, false)); this.usingKeyspace = keyspace; return this; } - + public SessionInitializer use(String keyspace, boolean forceQuote) { session.execute(SchemaUtil.use(keyspace, forceQuote)); this.usingKeyspace = keyspace; return this; } - + public void singleton() { - Casser.setSession(get()); + + Helenus.setSession(get()); } - - public synchronized CasserSession get() { + + public synchronized HelenusSession get() { initialize(); - return new CasserSession(session, - usingKeyspace, - showCql, - printStream, - sessionRepository, - executor, + return new HelenusSession(session, usingKeyspace, registry, showCql, printStream, sessionRepository, executor, autoDdl == AutoDdl.CREATE_DROP); } private void initialize() { - + Objects.requireNonNull(usingKeyspace, "please define keyspace by 'use' operator"); initList.forEach(dsl -> sessionRepository.add(dsl)); TableOperations tableOps = new TableOperations(this, dropUnusedColumns, dropUnusedIndexes); UserTypeOperations userTypeOps = new UserTypeOperations(this, dropUnusedColumns); - - - switch(autoDdl) { - - case CREATE: - case CREATE_DROP: - eachUserTypeInOrder(userTypeOps, e -> userTypeOps.createUserType(e)); - - sessionRepository.entities().stream().filter(e -> e.getType() == CasserEntityType.TABLE) - .forEach(e -> tableOps.createTable(e)); - - break; - - case VALIDATE: - - eachUserTypeInOrder(userTypeOps, e -> userTypeOps.validateUserType(getUserType(e), e)); - - sessionRepository.entities().stream().filter(e -> e.getType() == CasserEntityType.TABLE) - .forEach(e -> tableOps.validateTable(getTableMetadata(e), e)); - break; - - case UPDATE: - - eachUserTypeInOrder(userTypeOps, e -> userTypeOps.updateUserType(getUserType(e), e)); + switch (autoDdl) { + + case CREATE_DROP : + + // Drop tables first, otherwise a `DROP TYPE ...` will fail as the type is still referenced + // by a table. + sessionRepository.entities().stream().filter(e -> e.getType() == HelenusEntityType.TABLE) + .forEach(e -> tableOps.dropTable(e)); + + eachUserTypeInReverseOrder(userTypeOps, e -> userTypeOps.dropUserType(e)); + + // FALLTHRU to CREATE case (read: the absence of a `break;` statement here is intentional!) + case CREATE : + + eachUserTypeInOrder(userTypeOps, e -> userTypeOps.createUserType(e)); + + sessionRepository.entities().stream().filter(e -> e.getType() == HelenusEntityType.TABLE) + .forEach(e -> tableOps.createTable(e)); + + break; + + case VALIDATE : + + eachUserTypeInOrder(userTypeOps, e -> userTypeOps.validateUserType(getUserType(e), e)); + + sessionRepository.entities().stream().filter(e -> e.getType() == HelenusEntityType.TABLE) + .forEach(e -> tableOps.validateTable(getTableMetadata(e), e)); + break; + + case UPDATE : + + eachUserTypeInOrder(userTypeOps, e -> userTypeOps.updateUserType(getUserType(e), e)); + + sessionRepository.entities().stream().filter(e -> e.getType() == HelenusEntityType.TABLE) + .forEach(e -> tableOps.updateTable(getTableMetadata(e), e)); + break; - sessionRepository.entities().stream().filter(e -> e.getType() == CasserEntityType.TABLE) - .forEach(e -> tableOps.updateTable(getTableMetadata(e), e)); - break; - } - + KeyspaceMetadata km = getKeyspaceMetadata(); - + for (UserType userType : km.getUserTypes()) { sessionRepository.addUserType(userType.getTypeName(), userType); } - - } - - private void eachUserTypeInOrder(UserTypeOperations userTypeOps, Consumer action) { - - Set processedSet = new HashSet(); - Set stack = new HashSet(); - - sessionRepository.entities().stream() - .filter(e -> e.getType() == CasserEntityType.UDT) - .forEach(e -> { - - stack.clear(); - eachUserTypeInRecursion(e, processedSet, stack, userTypeOps, action); - - }); - } - - private void eachUserTypeInRecursion(CasserEntity e, Set processedSet, Set stack, UserTypeOperations userTypeOps, Consumer action) { - + + private void eachUserTypeInOrder(UserTypeOperations userTypeOps, Consumer action) { + + Set processedSet = new HashSet(); + Set stack = new HashSet(); + + sessionRepository.entities().stream().filter(e -> e.getType() == HelenusEntityType.UDT).forEach(e -> { + stack.clear(); + eachUserTypeInRecursion(e, processedSet, stack, userTypeOps, action); + }); + + } + + private void eachUserTypeInReverseOrder(UserTypeOperations userTypeOps, Consumer action) { + ArrayDeque deque = new ArrayDeque<>(); + eachUserTypeInOrder(userTypeOps, e -> deque.addFirst(e)); + deque.stream().forEach(e -> {action.accept(e); }); +/* + Set processedSet = new HashSet(); + Set stack = new HashSet(); + + sessionRepository.entities().stream() + .filter(e -> e.getType() == HelenusEntityType.UDT) + .collect(Collectors.toCollection(ArrayDeque::new)) + .descendingIterator() + .forEachRemaining(e -> { + stack.clear(); + eachUserTypeInRecursion(e, processedSet, stack, userTypeOps, action); + }); +*/ + } + + private void eachUserTypeInRecursion(HelenusEntity e, Set processedSet, Set stack, + UserTypeOperations userTypeOps, Consumer action) { + stack.add(e); - - Collection createBefore = sessionRepository.getUserTypeUses(e); - - for (CasserEntity be : createBefore) { + + Collection createBefore = sessionRepository.getUserTypeUses(e); + + for (HelenusEntity be : createBefore) { if (!processedSet.contains(be) && !stack.contains(be)) { eachUserTypeInRecursion(be, processedSet, stack, userTypeOps, action); processedSet.add(be); } } - + if (!processedSet.contains(e)) { action.accept(e); processedSet.add(e); } - + } - + private KeyspaceMetadata getKeyspaceMetadata() { if (keyspaceMetadata == null) { keyspaceMetadata = session.getCluster().getMetadata().getKeyspace(usingKeyspace.toLowerCase()); } return keyspaceMetadata; } - - private TableMetadata getTableMetadata(CasserEntity entity) { + + private TableMetadata getTableMetadata(HelenusEntity entity) { return getKeyspaceMetadata().getTable(entity.getName().getName()); - + } - private UserType getUserType(CasserEntity entity) { + private UserType getUserType(HelenusEntity entity) { return getKeyspaceMetadata().getUserType(entity.getName().getName()); } } diff --git a/src/main/java/com/noorq/casser/core/SessionRepository.java b/src/main/java/net/helenus/core/SessionRepository.java similarity index 68% rename from src/main/java/com/noorq/casser/core/SessionRepository.java rename to src/main/java/net/helenus/core/SessionRepository.java index 45d8d9e..a07d41d 100644 --- a/src/main/java/com/noorq/casser/core/SessionRepository.java +++ b/src/main/java/net/helenus/core/SessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,37 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Collection; import com.datastax.driver.core.UserType; import com.google.common.collect.ImmutableMap; -import com.noorq.casser.mapping.CasserEntity; + +import net.helenus.mapping.HelenusEntity; public final class SessionRepository { - + private final ImmutableMap userTypeMap; - private final ImmutableMap, CasserEntity> entityMap; + private final ImmutableMap, HelenusEntity> entityMap; public SessionRepository(SessionRepositoryBuilder builder) { - - userTypeMap = ImmutableMap.builder() - .putAll(builder.getUserTypeMap()) - .build(); - entityMap = ImmutableMap., CasserEntity>builder() - .putAll(builder.getEntityMap()) - .build(); + userTypeMap = ImmutableMap.builder().putAll(builder.getUserTypeMap()).build(); + + entityMap = ImmutableMap., HelenusEntity>builder().putAll(builder.getEntityMap()).build(); } - + public UserType findUserType(String name) { return userTypeMap.get(name.toLowerCase()); } - - public Collection entities() { + + public Collection entities() { return entityMap.values(); } - + } diff --git a/src/main/java/com/noorq/casser/core/SessionRepositoryBuilder.java b/src/main/java/net/helenus/core/SessionRepositoryBuilder.java similarity index 52% rename from src/main/java/com/noorq/casser/core/SessionRepositoryBuilder.java rename to src/main/java/net/helenus/core/SessionRepositoryBuilder.java index d493930..26b2995 100644 --- a/src/main/java/com/noorq/casser/core/SessionRepositoryBuilder.java +++ b/src/main/java/net/helenus/core/SessionRepositoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,47 +13,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import com.datastax.driver.core.Session; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserEntityType; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusEntityType; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.support.HelenusMappingException; public final class SessionRepositoryBuilder { - private static final Optional OPTIONAL_UDT = Optional.of(CasserEntityType.UDT); - - private final Map, CasserEntity> entityMap = new HashMap, CasserEntity>(); + private static final Optional OPTIONAL_UDT = Optional.of(HelenusEntityType.UDT); + + private final Map, HelenusEntity> entityMap = new HashMap, HelenusEntity>(); private final Map userTypeMap = new HashMap(); - private final Multimap userTypeUsesMap = HashMultimap.create(); - + private final Multimap userTypeUsesMap = HashMultimap.create(); + + private final Session session; + + + SessionRepositoryBuilder(Session session) { + this.session = session; + } + public SessionRepository build() { return new SessionRepository(this); } - public Collection getUserTypeUses(CasserEntity udtName) { + public Collection getUserTypeUses(HelenusEntity udtName) { return userTypeUsesMap.get(udtName); } - public Collection entities() { + public Collection entities() { return entityMap.values(); } - - protected Map, CasserEntity> getEntityMap() { + + protected Map, HelenusEntity> getEntityMap() { return entityMap; } @@ -65,80 +74,79 @@ public final class SessionRepositoryBuilder { userTypeMap.putIfAbsent(name.toLowerCase(), userType); } - public CasserEntity add(Object dsl) { + public HelenusEntity add(Object dsl) { return add(dsl, Optional.empty()); } - - public void addEntity(CasserEntity entity) { - CasserEntity concurrentEntity = entityMap.putIfAbsent(entity.getMappingInterface(), entity); - + public void addEntity(HelenusEntity entity) { + + HelenusEntity concurrentEntity = entityMap.putIfAbsent(entity.getMappingInterface(), entity); + if (concurrentEntity == null) { addUserDefinedTypes(entity.getOrderedProperties()); } - - } - - public CasserEntity add(Object dsl, Optional type) { - CasserEntity casserEntity = Casser.resolve(dsl); - - Class iface = casserEntity.getMappingInterface(); - - CasserEntity entity = entityMap.get(iface); - + } + + public HelenusEntity add(Object dsl, Optional type) { + + HelenusEntity helenusEntity = Helenus.resolve(dsl, session.getCluster().getMetadata()); + + Class iface = helenusEntity.getMappingInterface(); + + HelenusEntity entity = entityMap.get(iface); + if (entity == null) { - entity = casserEntity; - + entity = helenusEntity; + if (type.isPresent() && entity.getType() != type.get()) { - throw new CasserMappingException("unexpected entity type " + entity.getType() + " for " + entity); + throw new HelenusMappingException("unexpected entity type " + entity.getType() + " for " + entity); } - - CasserEntity concurrentEntity = entityMap.putIfAbsent(iface, entity); - + + HelenusEntity concurrentEntity = entityMap.putIfAbsent(iface, entity); + if (concurrentEntity == null) { addUserDefinedTypes(entity.getOrderedProperties()); - } - else { + } else { entity = concurrentEntity; } } - + return entity; } - - private void addUserDefinedTypes(Collection props) { - - for (CasserProperty prop : props) { - + + private void addUserDefinedTypes(Collection props) { + + for (HelenusProperty prop : props) { + AbstractDataType type = prop.getDataType(); - + if (type instanceof DTDataType) { continue; } - + if (!UDTValue.class.isAssignableFrom(prop.getJavaType())) { - + for (Class udtClass : type.getTypeArguments()) { - + if (UDTValue.class.isAssignableFrom(udtClass)) { continue; } - - CasserEntity addedUserType = add(udtClass, OPTIONAL_UDT); - - if (CasserEntityType.UDT == prop.getEntity().getType()) { + + HelenusEntity addedUserType = add(udtClass, OPTIONAL_UDT); + + if (HelenusEntityType.UDT == prop.getEntity().getType()) { userTypeUsesMap.put(prop.getEntity(), addedUserType); } - + } - + } - + } - + } - + } diff --git a/src/main/java/com/noorq/casser/core/TableOperations.java b/src/main/java/net/helenus/core/TableOperations.java similarity index 70% rename from src/main/java/com/noorq/casser/core/TableOperations.java rename to src/main/java/net/helenus/core/TableOperations.java index 7ca828c..1663bba 100644 --- a/src/main/java/com/noorq/casser/core/TableOperations.java +++ b/src/main/java/net/helenus/core/TableOperations.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,67 +13,76 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.List; import com.datastax.driver.core.TableMetadata; import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.support.CasserException; + +import net.helenus.mapping.HelenusEntity; +import net.helenus.support.HelenusException; public final class TableOperations { private final AbstractSessionOperations sessionOps; private final boolean dropUnusedColumns; private final boolean dropUnusedIndexes; - + public TableOperations(AbstractSessionOperations sessionOps, boolean dropUnusedColumns, boolean dropUnusedIndexes) { this.sessionOps = sessionOps; this.dropUnusedColumns = dropUnusedColumns; this.dropUnusedIndexes = dropUnusedIndexes; } - - public void createTable(CasserEntity entity) { - + + public void createTable(HelenusEntity entity) { + sessionOps.execute(SchemaUtil.createTable(entity), true); - + executeBatch(SchemaUtil.createIndexes(entity)); - + } - - public void validateTable(TableMetadata tmd, CasserEntity entity) { - + + public void dropTable(HelenusEntity entity) { + + sessionOps.execute(SchemaUtil.dropTable(entity), true); + + } + + public void validateTable(TableMetadata tmd, HelenusEntity entity) { + if (tmd == null) { - throw new CasserException("table not exists " + entity.getName() + "for entity " + entity.getMappingInterface()); + throw new HelenusException( + "table not exists " + entity.getName() + "for entity " + entity.getMappingInterface()); } - + List list = SchemaUtil.alterTable(tmd, entity, dropUnusedColumns); - + list.addAll(SchemaUtil.alterIndexes(tmd, entity, dropUnusedIndexes)); - + if (!list.isEmpty()) { - throw new CasserException("schema changed for entity " + entity.getMappingInterface() + ", apply this command: " + list); + throw new HelenusException( + "schema changed for entity " + entity.getMappingInterface() + ", apply this command: " + list); } } - - public void updateTable(TableMetadata tmd, CasserEntity entity) { - + + public void updateTable(TableMetadata tmd, HelenusEntity entity) { + if (tmd == null) { createTable(entity); return; } - + executeBatch(SchemaUtil.alterTable(tmd, entity, dropUnusedColumns)); executeBatch(SchemaUtil.alterIndexes(tmd, entity, dropUnusedIndexes)); } - + private void executeBatch(List list) { - + list.forEach(s -> { sessionOps.execute(s, true); }); - + } - + } diff --git a/src/main/java/net/helenus/core/UnitOfWork.java b/src/main/java/net/helenus/core/UnitOfWork.java new file mode 100644 index 0000000..b0665cd --- /dev/null +++ b/src/main/java/net/helenus/core/UnitOfWork.java @@ -0,0 +1,60 @@ +package net.helenus.core; + +import java.util.ArrayList; + +/** + * Encapsulates the concept of a "transaction" as a unit-of-work. + */ +public class UnitOfWork { + + private final HelenusSession session; + private ArrayList nested; + + UnitOfWork(HelenusSession session) { + this.session = session; + // log.record(txn::start) + } + + /** + * Marks the beginning of a transactional section of work. Will write a record + * to the shared write-ahead log. + * + * @return the handle used to commit or abort the work. + */ + public UnitOfWork begin() { + if (nested == null) { + nested = new ArrayList(); + } + UnitOfWork unitOfWork = new UnitOfWork(session); + nested.add(unitOfWork); + return unitOfWork; + } + + /** + * Checks to see if the work performed between calling begin and now can be + * committed or not. + * + * @throws ConflictingUnitOfWorkException + * when the work overlaps with other concurrent writers. + */ + public void commit() throws ConflictingUnitOfWorkException { + // nested.foreach.commit() + // log.record(txn::provisionalCommit) + // examine log for conflicts in read-set and write-set between begin and + // provisional commit + // if (conflict) { throw new ConflictingUnitOfWorkException(this) } + } + + /** + * Explicitly discard the work and mark it as as such in the log. + */ + public void abort() { + // log.record(txn::abort) + // cache.invalidateSince(txn::start time) + } + + public String describeConflicts() { + return "it's complex..."; + } + +} diff --git a/src/main/java/com/noorq/casser/core/UserTypeOperations.java b/src/main/java/net/helenus/core/UserTypeOperations.java similarity index 66% rename from src/main/java/com/noorq/casser/core/UserTypeOperations.java rename to src/main/java/net/helenus/core/UserTypeOperations.java index 6d7be36..4c3bdd6 100644 --- a/src/main/java/com/noorq/casser/core/UserTypeOperations.java +++ b/src/main/java/net/helenus/core/UserTypeOperations.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,63 +13,71 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core; +package net.helenus.core; import java.util.List; import com.datastax.driver.core.UserType; import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.support.CasserException; + +import net.helenus.mapping.HelenusEntity; +import net.helenus.support.HelenusException; public final class UserTypeOperations { - + private final AbstractSessionOperations sessionOps; private final boolean dropUnusedColumns; - + public UserTypeOperations(AbstractSessionOperations sessionOps, boolean dropUnusedColumns) { this.sessionOps = sessionOps; this.dropUnusedColumns = dropUnusedColumns; } - - public void createUserType(CasserEntity entity) { - + + public void createUserType(HelenusEntity entity) { + sessionOps.execute(SchemaUtil.createUserType(entity), true); - + } - public void validateUserType(UserType userType, CasserEntity entity) { - + public void dropUserType(HelenusEntity entity) { + + sessionOps.execute(SchemaUtil.dropUserType(entity), true); + + } + + public void validateUserType(UserType userType, HelenusEntity entity) { + if (userType == null) { - throw new CasserException("userType not exists " + entity.getName() + "for entity " + entity.getMappingInterface()); + throw new HelenusException( + "userType not exists " + entity.getName() + "for entity " + entity.getMappingInterface()); } - + List list = SchemaUtil.alterUserType(userType, entity, dropUnusedColumns); - + if (!list.isEmpty()) { - throw new CasserException("schema changed for entity " + entity.getMappingInterface() + ", apply this command: " + list); + throw new HelenusException( + "schema changed for entity " + entity.getMappingInterface() + ", apply this command: " + list); } - + } - - public void updateUserType(UserType userType, CasserEntity entity) { - + public void updateUserType(UserType userType, HelenusEntity entity) { + if (userType == null) { createUserType(entity); return; } - + executeBatch(SchemaUtil.alterUserType(userType, entity, dropUnusedColumns)); - + } private void executeBatch(List list) { - + list.forEach(s -> { sessionOps.execute(s, true); }); - + } } diff --git a/src/main/java/net/helenus/core/annotation/Cacheable.java b/src/main/java/net/helenus/core/annotation/Cacheable.java new file mode 100644 index 0000000..9b8c1c1 --- /dev/null +++ b/src/main/java/net/helenus/core/annotation/Cacheable.java @@ -0,0 +1,11 @@ +package net.helenus.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Cacheable { +} diff --git a/src/main/java/net/helenus/core/annotation/Retry.java b/src/main/java/net/helenus/core/annotation/Retry.java new file mode 100644 index 0000000..7db5b20 --- /dev/null +++ b/src/main/java/net/helenus/core/annotation/Retry.java @@ -0,0 +1,17 @@ +package net.helenus.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import net.helenus.core.ConflictingUnitOfWorkException; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Retry { + + Class[] on() default ConflictingUnitOfWorkException.class; + + int times() default 3; +} diff --git a/src/main/java/net/helenus/core/aspect/RetryConcurrentUnitOfWorkAspect.java b/src/main/java/net/helenus/core/aspect/RetryConcurrentUnitOfWorkAspect.java new file mode 100644 index 0000000..d2ad9a4 --- /dev/null +++ b/src/main/java/net/helenus/core/aspect/RetryConcurrentUnitOfWorkAspect.java @@ -0,0 +1,83 @@ +package net.helenus.core.aspect; + +import java.lang.reflect.Method; +import java.util.Arrays; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.Assert; + +import net.helenus.core.annotation.Retry; + +@Aspect +public class RetryConcurrentUnitOfWorkAspect { + + private static final Logger log = LoggerFactory.getLogger(RetryConcurrentUnitOfWorkAspect.class); + + @Around("@annotation(net.helenus.core.annotations.Retry)") + public Object retry(ProceedingJoinPoint pjp) throws Throwable { + Retry retryAnnotation = getRetryAnnotation(pjp); + return (retryAnnotation != null) ? proceed(pjp, retryAnnotation) : proceed(pjp); + } + + private Object proceed(ProceedingJoinPoint pjp) throws Throwable { + return pjp.proceed(); + } + + private Object proceed(ProceedingJoinPoint pjp, Retry retryAnnotation) throws Throwable { + int times = retryAnnotation.times(); + Class[] retryOn = retryAnnotation.on(); + Assert.isTrue(times > 0, "@Retry{times} should be greater than 0!"); + Assert.isTrue(retryOn.length > 0, "@Retry{on} should have at least one Throwable!"); + log.info("Proceed with {} retries on {}", times, Arrays.toString(retryOn)); + return tryProceeding(pjp, times, retryOn); + } + + private Object tryProceeding(ProceedingJoinPoint pjp, int times, Class[] retryOn) + throws Throwable { + try { + return proceed(pjp); + } catch (Throwable throwable) { + if (isRetryThrowable(throwable, retryOn) && times-- > 0) { + log.info("Conflict detected, {} remaining retries on {}", times, Arrays.toString(retryOn)); + return tryProceeding(pjp, times, retryOn); + } + throw throwable; + } + } + + private boolean isRetryThrowable(Throwable throwable, Class[] retryOn) { + Throwable[] causes = ExceptionUtils.getThrowables(throwable); + for (Throwable cause : causes) { + for (Class retryThrowable : retryOn) { + if (retryThrowable.isAssignableFrom(cause.getClass())) { + return true; + } + } + } + return false; + } + + private Retry getRetryAnnotation(ProceedingJoinPoint pjp) throws NoSuchMethodException { + MethodSignature signature = (MethodSignature) pjp.getSignature(); + Method method = signature.getMethod(); + Retry retryAnnotation = AnnotationUtils.findAnnotation(method, Retry.class); + + if (retryAnnotation != null) { + return retryAnnotation; + } + + Class[] argClasses = new Class[pjp.getArgs().length]; + for (int i = 0; i < pjp.getArgs().length; i++) { + argClasses[i] = pjp.getArgs()[i].getClass(); + } + method = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), argClasses); + return AnnotationUtils.findAnnotation(method, Retry.class); + } +} diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractFilterOperation.java b/src/main/java/net/helenus/core/operation/AbstractFilterOperation.java similarity index 84% rename from src/main/java/com/noorq/casser/core/operation/AbstractFilterOperation.java rename to src/main/java/net/helenus/core/operation/AbstractFilterOperation.java index f08d390..13de23e 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractFilterOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractFilterOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.LinkedList; import java.util.List; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.Operator; -import com.noorq.casser.core.Postulate; +import net.helenus.core.*; -public abstract class AbstractFilterOperation> extends AbstractOperation { +public abstract class AbstractFilterOperation> + extends + AbstractOperation { protected List> filters = null; protected List> ifFilters = null; - + public AbstractFilterOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public O where(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } public O where(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O where(Filter filter) { addFilter(filter); @@ -55,54 +53,54 @@ public abstract class AbstractFilterOperation O and(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } - + public O and(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } public O and(Filter filter) { - + addFilter(filter); - + return (O) this; } - + public O onlyIf(Getter getter, Postulate postulate) { - + addIfFilter(Filter.create(getter, postulate)); - + return (O) this; } public O onlyIf(Getter getter, Operator operator, V val) { - + addIfFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O onlyIf(Filter filter) { addIfFilter(filter); return (O) this; } - + private void addFilter(Filter filter) { if (filters == null) { filters = new LinkedList>(); } filters.add(filter); } - + private void addIfFilter(Filter filter) { if (ifFilters == null) { ifFilters = new LinkedList>(); diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractFilterOptionalOperation.java b/src/main/java/net/helenus/core/operation/AbstractFilterOptionalOperation.java similarity index 83% rename from src/main/java/com/noorq/casser/core/operation/AbstractFilterOptionalOperation.java rename to src/main/java/net/helenus/core/operation/AbstractFilterOptionalOperation.java index 2ffaee8..b11939c 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractFilterOptionalOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractFilterOptionalOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.LinkedList; import java.util.List; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.Operator; -import com.noorq.casser.core.Postulate; +import net.helenus.core.*; -public abstract class AbstractFilterOptionalOperation> extends AbstractOptionalOperation { +public abstract class AbstractFilterOptionalOperation> + extends + AbstractOptionalOperation { protected List> filters = null; protected List> ifFilters = null; - + public AbstractFilterOptionalOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public O where(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } public O where(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O where(Filter filter) { addFilter(filter); @@ -55,47 +53,47 @@ public abstract class AbstractFilterOptionalOperation O and(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } - + public O and(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } public O and(Filter filter) { - + addFilter(filter); - + return (O) this; } - + public O onlyIf(Getter getter, Postulate postulate) { - + addIfFilter(Filter.create(getter, postulate)); - + return (O) this; } public O onlyIf(Getter getter, Operator operator, V val) { - + addIfFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O onlyIf(Filter filter) { addIfFilter(filter); return (O) this; } - + private void addFilter(Filter filter) { if (filters == null) { filters = new LinkedList>(); diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractFilterStreamOperation.java b/src/main/java/net/helenus/core/operation/AbstractFilterStreamOperation.java similarity index 84% rename from src/main/java/com/noorq/casser/core/operation/AbstractFilterStreamOperation.java rename to src/main/java/net/helenus/core/operation/AbstractFilterStreamOperation.java index f1eb7dd..65e390d 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractFilterStreamOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractFilterStreamOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.LinkedList; import java.util.List; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.Operator; -import com.noorq.casser.core.Postulate; +import net.helenus.core.*; -public abstract class AbstractFilterStreamOperation> extends AbstractStreamOperation { +public abstract class AbstractFilterStreamOperation> + extends + AbstractStreamOperation { protected List> filters = null; protected List> ifFilters = null; - + public AbstractFilterStreamOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public O where(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } public O where(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O where(Filter filter) { addFilter(filter); @@ -55,47 +53,47 @@ public abstract class AbstractFilterStreamOperation O and(Getter getter, Postulate postulate) { - + addFilter(Filter.create(getter, postulate)); - + return (O) this; } - + public O and(Getter getter, Operator operator, V val) { - + addFilter(Filter.create(getter, operator, val)); - + return (O) this; } public O and(Filter filter) { - + addFilter(filter); - + return (O) this; } - + public O onlyIf(Getter getter, Postulate postulate) { - + addIfFilter(Filter.create(getter, postulate)); - + return (O) this; } public O onlyIf(Getter getter, Operator operator, V val) { - + addIfFilter(Filter.create(getter, operator, val)); - + return (O) this; } - + public O onlyIf(Filter filter) { addIfFilter(filter); return (O) this; } - + private void addFilter(Filter filter) { if (filters == null) { filters = new LinkedList>(); diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractOperation.java b/src/main/java/net/helenus/core/operation/AbstractOperation.java similarity index 83% rename from src/main/java/com/noorq/casser/core/operation/AbstractOperation.java rename to src/main/java/net/helenus/core/operation/AbstractOperation.java index 70abb4b..64d7523 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; - -import scala.concurrent.Future; +package net.helenus.core.operation; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; @@ -23,48 +21,61 @@ import com.datastax.driver.core.ResultSetFuture; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.support.Fun; -import com.noorq.casser.support.Scala; + +import net.helenus.core.AbstractSessionOperations; +import net.helenus.support.Fun; +import net.helenus.support.Scala; +import scala.concurrent.Future; public abstract class AbstractOperation> extends AbstractStatementOperation { public abstract E transform(ResultSet resultSet); - + + public boolean cacheable() { + return false; + } + + public String getCacheKey() { + return ""; + } + public AbstractOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public PreparedOperation prepare() { return new PreparedOperation(prepareStatement(), this); } - + public ListenableFuture> prepareAsync() { final O _this = (O) this; - + return Futures.transform(prepareStatementAsync(), new Function>() { @Override public PreparedOperation apply(PreparedStatement preparedStatement) { return new PreparedOperation(preparedStatement, _this); } - + }); - + } - + public Future> prepareFuture() { return Scala.asFuture(prepareAsync()); } public E sync() { - - ResultSet resultSet = sessionOps.executeAsync(options(buildStatement()), showValues).getUninterruptibly(); - return transform(resultSet); + ResultSet resultSet = sessionOps.executeAsync(options(buildStatement()), showValues).getUninterruptibly(); + E result = transform(resultSet); + if (cacheable()) { + sessionOps.cache(getCacheKey(), result); + } + return result; } - + public ListenableFuture async() { ResultSetFuture resultSetFuture = sessionOps.executeAsync(options(buildStatement()), showValues); @@ -73,18 +84,22 @@ public abstract class AbstractOperation> ex @Override public E apply(ResultSet resultSet) { + E result = transform(resultSet); + if (cacheable()) { + sessionOps.cache(getCacheKey(), result); + } return transform(resultSet); } }, sessionOps.getExecutor()); - + return future; } - + public Future future() { return Scala.asFuture(async()); } - + public Future> future(A a) { return Scala.asFuture(async(), a); } @@ -100,5 +115,5 @@ public abstract class AbstractOperation> ex public Future> future(A a, B b, C c, D d) { return Scala.asFuture(async(), a, b, c, d); } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractOptionalOperation.java b/src/main/java/net/helenus/core/operation/AbstractOptionalOperation.java similarity index 78% rename from src/main/java/com/noorq/casser/core/operation/AbstractOptionalOperation.java rename to src/main/java/net/helenus/core/operation/AbstractOptionalOperation.java index f31c71a..82a4655 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractOptionalOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractOptionalOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,81 +13,84 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.Optional; -import scala.None; -import scala.Option; -import scala.Some; -import scala.concurrent.Future; - import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.support.Fun; -import com.noorq.casser.support.Scala; -public abstract class AbstractOptionalOperation> extends AbstractStatementOperation { +import net.helenus.core.AbstractSessionOperations; +import net.helenus.support.Fun; +import net.helenus.support.Scala; +import scala.Option; +import scala.Some; +import scala.concurrent.Future; + +public abstract class AbstractOptionalOperation> + extends + AbstractStatementOperation { public AbstractOptionalOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public abstract Optional transform(ResultSet resultSet); - + public PreparedOptionalOperation prepare() { return new PreparedOptionalOperation(prepareStatement(), this); } - + public ListenableFuture> prepareAsync() { final O _this = (O) this; - - return Futures.transform(prepareStatementAsync(), new Function>() { - @Override - public PreparedOptionalOperation apply(PreparedStatement preparedStatement) { - return new PreparedOptionalOperation(preparedStatement, _this); - } - - }); - + return Futures.transform(prepareStatementAsync(), + new Function>() { + + @Override + public PreparedOptionalOperation apply(PreparedStatement preparedStatement) { + return new PreparedOptionalOperation(preparedStatement, _this); + } + + }); + } - + public Future> prepareFuture() { return Scala.asFuture(prepareAsync()); } public Optional sync() { - + ResultSet resultSet = sessionOps.executeAsync(options(buildStatement()), showValues).getUninterruptibly(); return transform(resultSet); } - + public ListenableFuture> async() { - + ResultSetFuture resultSetFuture = sessionOps.executeAsync(options(buildStatement()), showValues); - ListenableFuture> future = Futures.transform(resultSetFuture, new Function>() { + ListenableFuture> future = Futures.transform(resultSetFuture, + new Function>() { - @Override - public Optional apply(ResultSet resultSet) { - return transform(resultSet); - } + @Override + public Optional apply(ResultSet resultSet) { + return transform(resultSet); + } + + }, sessionOps.getExecutor()); - }, sessionOps.getExecutor()); - return future; } public ListenableFuture> asyncForScala() { - + ResultSetFuture resultSetFuture = sessionOps.executeAsync(options(buildStatement()), showValues); ListenableFuture> future = Futures.transform(resultSetFuture, new Function>() { @@ -97,14 +100,13 @@ public abstract class AbstractOptionalOperation optional = transform(resultSet); if (optional.isPresent()) { return new Some(optional.get()); - } - else { + } else { return Option.empty(); } } }, sessionOps.getExecutor()); - + return future; } public Future> future() { @@ -126,5 +128,5 @@ public abstract class AbstractOptionalOperation Future, A, B, C, D>> future(A a, B b, C c, D d) { return Scala.asFuture(asyncForScala(), a, b, c, d); } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractStatementOperation.java b/src/main/java/net/helenus/core/operation/AbstractStatementOperation.java similarity index 91% rename from src/main/java/com/noorq/casser/core/operation/AbstractStatementOperation.java rename to src/main/java/net/helenus/core/operation/AbstractStatementOperation.java index 1096346..c360705 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractStatementOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractStatementOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import scala.concurrent.Future; - import com.datastax.driver.core.ConsistencyLevel; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.RegularStatement; @@ -30,18 +28,20 @@ import com.datastax.driver.core.policies.FallthroughRetryPolicy; import com.datastax.driver.core.policies.RetryPolicy; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.google.common.util.concurrent.ListenableFuture; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.support.CasserException; -import com.noorq.casser.support.Scala; + +import net.helenus.core.AbstractSessionOperations; +import net.helenus.support.HelenusException; +import net.helenus.support.Scala; +import scala.concurrent.Future; public abstract class AbstractStatementOperation> { final Logger logger = LoggerFactory.getLogger(getClass()); protected final AbstractSessionOperations sessionOps; - + public abstract Statement buildStatement(); - + protected boolean showValues = true; private ConsistencyLevel consistencyLevel; private ConsistencyLevel serialConsistencyLevel; @@ -49,22 +49,22 @@ public abstract class AbstractStatementOperation prepareStatementAsync() { - + Statement statement = buildStatement(); - + if (statement instanceof RegularStatement) { - + RegularStatement regularStatement = (RegularStatement) statement; - + return sessionOps.prepareAsync(regularStatement); - + } - - throw new CasserException("only RegularStatements can be prepared"); + + throw new HelenusException("only RegularStatements can be prepared"); } - + public Future prepareStatementFuture() { return Scala.asFuture(prepareStatementAsync()); } diff --git a/src/main/java/com/noorq/casser/core/operation/AbstractStreamOperation.java b/src/main/java/net/helenus/core/operation/AbstractStreamOperation.java similarity index 74% rename from src/main/java/com/noorq/casser/core/operation/AbstractStreamOperation.java rename to src/main/java/net/helenus/core/operation/AbstractStreamOperation.java index 2cf6753..dccb7ff 100644 --- a/src/main/java/com/noorq/casser/core/operation/AbstractStreamOperation.java +++ b/src/main/java/net/helenus/core/operation/AbstractStreamOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,62 +13,65 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.stream.Stream; -import scala.concurrent.Future; - import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.support.Fun; -import com.noorq.casser.support.Scala; -public abstract class AbstractStreamOperation> extends AbstractStatementOperation { +import net.helenus.core.AbstractSessionOperations; +import net.helenus.support.Fun; +import net.helenus.support.Scala; +import scala.concurrent.Future; + +public abstract class AbstractStreamOperation> + extends + AbstractStatementOperation { public AbstractStreamOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - + public abstract Stream transform(ResultSet resultSet); - + public PreparedStreamOperation prepare() { return new PreparedStreamOperation(prepareStatement(), this); } - + public ListenableFuture> prepareAsync() { final O _this = (O) this; - - return Futures.transform(prepareStatementAsync(), new Function>() { - @Override - public PreparedStreamOperation apply(PreparedStatement preparedStatement) { - return new PreparedStreamOperation(preparedStatement, _this); - } - - }); - + return Futures.transform(prepareStatementAsync(), + new Function>() { + + @Override + public PreparedStreamOperation apply(PreparedStatement preparedStatement) { + return new PreparedStreamOperation(preparedStatement, _this); + } + + }); + } - + public Future> prepareFuture() { return Scala.asFuture(prepareAsync()); } public Stream sync() { - + ResultSet resultSet = sessionOps.executeAsync(options(buildStatement()), showValues).getUninterruptibly(); return transform(resultSet); } - + public ListenableFuture> async() { - + ResultSetFuture resultSetFuture = sessionOps.executeAsync(options(buildStatement()), showValues); ListenableFuture> future = Futures.transform(resultSetFuture, new Function>() { @@ -79,27 +82,28 @@ public abstract class AbstractStreamOperation> asyncForScala() { - + ResultSetFuture resultSetFuture = sessionOps.executeAsync(options(buildStatement()), showValues); - ListenableFuture> future = Futures.transform(resultSetFuture, new Function>() { + ListenableFuture> future = Futures.transform(resultSetFuture, + new Function>() { - @Override - public scala.collection.immutable.Stream apply(ResultSet resultSet) { - Stream stream = transform(resultSet); - return scala.collection.JavaConversions.asScalaIterator(stream.iterator()).toStream(); - } + @Override + public scala.collection.immutable.Stream apply(ResultSet resultSet) { + Stream stream = transform(resultSet); + return scala.collection.JavaConversions.asScalaIterator(stream.iterator()).toStream(); + } + + }, sessionOps.getExecutor()); - }, sessionOps.getExecutor()); - return future; } - + public Future> future() { return Scala.asFuture(asyncForScala()); } @@ -116,8 +120,9 @@ public abstract class AbstractStreamOperation Future, A, B, C, D>> future(A a, B b, C c, D d) { + public Future, A, B, C, D>> future(A a, B b, C c, + D d) { return Scala.asFuture(asyncForScala(), a, b, c, d); } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/BoundOperation.java b/src/main/java/net/helenus/core/operation/BoundOperation.java similarity index 93% rename from src/main/java/com/noorq/casser/core/operation/BoundOperation.java rename to src/main/java/net/helenus/core/operation/BoundOperation.java index f748a3e..b82dfab 100644 --- a/src/main/java/com/noorq/casser/core/operation/BoundOperation.java +++ b/src/main/java/net/helenus/core/operation/BoundOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.ResultSet; @@ -23,21 +23,21 @@ public final class BoundOperation extends AbstractOperation delegate; - + public BoundOperation(BoundStatement boundStatement, AbstractOperation operation) { super(operation.sessionOps); this.boundStatement = boundStatement; this.delegate = operation; } - + @Override public E transform(ResultSet resultSet) { return delegate.transform(resultSet); } - + @Override public Statement buildStatement() { return boundStatement; } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/BoundOptionalOperation.java b/src/main/java/net/helenus/core/operation/BoundOptionalOperation.java similarity index 93% rename from src/main/java/com/noorq/casser/core/operation/BoundOptionalOperation.java rename to src/main/java/net/helenus/core/operation/BoundOptionalOperation.java index 5daf582..4efc2b0 100644 --- a/src/main/java/com/noorq/casser/core/operation/BoundOptionalOperation.java +++ b/src/main/java/net/helenus/core/operation/BoundOptionalOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.Optional; @@ -25,13 +25,13 @@ public final class BoundOptionalOperation extends AbstractOptionalOperation delegate; - + public BoundOptionalOperation(BoundStatement boundStatement, AbstractOptionalOperation operation) { super(operation.sessionOps); this.boundStatement = boundStatement; this.delegate = operation; } - + @Override public Optional transform(ResultSet resultSet) { return delegate.transform(resultSet); @@ -41,5 +41,5 @@ public final class BoundOptionalOperation extends AbstractOptionalOperation extends AbstractStreamOperation delegate; - + public BoundStreamOperation(BoundStatement boundStatement, AbstractStreamOperation operation) { super(operation.sessionOps); this.boundStatement = boundStatement; this.delegate = operation; } - + @Override public Stream transform(ResultSet resultSet) { return delegate.transform(resultSet); @@ -41,5 +41,5 @@ public final class BoundStreamOperation extends AbstractStreamOperation { - private CasserEntity entity; - + private HelenusEntity entity; + public CountOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - - public CountOperation(AbstractSessionOperations sessionOperations, CasserEntity entity) { + + public CountOperation(AbstractSessionOperations sessionOperations, HelenusEntity entity) { super(sessionOperations); this.entity = entity; } @Override public BuiltStatement buildStatement() { - + if (filters != null && !filters.isEmpty()) { filters.forEach(f -> addPropertyNode(f.getNode())); } - + if (entity == null) { - throw new CasserMappingException("unknown entity"); + throw new HelenusMappingException("unknown entity"); } - + Select select = QueryBuilder.select().countAll().from(entity.getName().toCql()); - + if (filters != null && !filters.isEmpty()) { - + Where where = select.where(); - + for (Filter filter : filters) { where.and(filter.getClause(sessionOps.getValuePreparer())); } } - + return select; } - + @Override public Long transform(ResultSet resultSet) { return resultSet.one().getLong(0); } - - private void addPropertyNode(CasserPropertyNode p) { + + private void addPropertyNode(HelenusPropertyNode p) { if (entity == null) { entity = p.getEntity(); - } - else if (entity != p.getEntity()) { - throw new CasserMappingException("you can count columns only in single entity " + entity.getMappingInterface() + " or " + p.getEntity().getMappingInterface()); + } else if (entity != p.getEntity()) { + throw new HelenusMappingException("you can count columns only in single entity " + + entity.getMappingInterface() + " or " + p.getEntity().getMappingInterface()); } } diff --git a/src/main/java/com/noorq/casser/core/operation/DeleteOperation.java b/src/main/java/net/helenus/core/operation/DeleteOperation.java similarity index 77% rename from src/main/java/com/noorq/casser/core/operation/DeleteOperation.java rename to src/main/java/net/helenus/core/operation/DeleteOperation.java index 1cc7b2d..99770f8 100644 --- a/src/main/java/com/noorq/casser/core/operation/DeleteOperation.java +++ b/src/main/java/net/helenus/core/operation/DeleteOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,71 +13,71 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.datastax.driver.core.querybuilder.Delete; import com.datastax.driver.core.querybuilder.Delete.Where; import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.core.AbstractSessionOperations; +import net.helenus.core.Filter; +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusEntity; +import net.helenus.support.HelenusMappingException; public final class DeleteOperation extends AbstractFilterOperation { - private CasserEntity entity; - + private HelenusEntity entity; + private boolean ifExists = false; - + private int[] ttl; private long[] timestamp; - + public DeleteOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - - public DeleteOperation(AbstractSessionOperations sessionOperations, CasserEntity entity) { + + public DeleteOperation(AbstractSessionOperations sessionOperations, HelenusEntity entity) { super(sessionOperations); - + this.entity = entity; } - + @Override public BuiltStatement buildStatement() { if (filters != null && !filters.isEmpty()) { filters.forEach(f -> addPropertyNode(f.getNode())); } - + if (entity == null) { - throw new CasserMappingException("unknown entity"); + throw new HelenusMappingException("unknown entity"); } - + if (filters != null && !filters.isEmpty()) { Delete delete = QueryBuilder.delete().from(entity.getName().toCql()); - + if (this.ifExists) { delete.ifExists(); } - + Where where = delete.where(); - + for (Filter filter : filters) { where.and(filter.getClause(sessionOps.getValuePreparer())); } - + if (ifFilters != null && !ifFilters.isEmpty()) { - + for (Filter filter : ifFilters) { delete.onlyIf(filter.getClause(sessionOps.getValuePreparer())); } } - + if (this.ttl != null) { delete.using(QueryBuilder.ttl(this.ttl[0])); } @@ -87,8 +87,7 @@ public final class DeleteOperation extends AbstractFilterOperation { - private CasserEntity entity; - - private final List> values = new ArrayList>(); + private HelenusEntity entity; + + private final List> values = new ArrayList>(); private boolean ifNotExists; private int[] ttl; private long[] timestamp; - + public InsertOperation(AbstractSessionOperations sessionOperations, boolean ifNotExists) { super(sessionOperations); - + this.ifNotExists = ifNotExists; } - - public InsertOperation(AbstractSessionOperations sessionOperations, CasserEntity entity, Object pojo, boolean ifNotExists) { + + public InsertOperation(AbstractSessionOperations sessionOperations, HelenusEntity entity, Object pojo, + boolean ifNotExists) { super(sessionOperations); - + this.ifNotExists = ifNotExists; - - for (CasserProperty prop : entity.getOrderedProperties()) { - + + for (HelenusProperty prop : entity.getOrderedProperties()) { + Object value = BeanColumnValueProvider.INSTANCE.getColumnValue(pojo, -1, prop); - + value = sessionOps.getValuePreparer().prepareColumnValue(value, prop); - + if (value != null) { - - CasserPropertyNode node = new CasserPropertyNode(prop, Optional.empty()); - values.add(Tuple2.of(node, value)); + + HelenusPropertyNode node = new HelenusPropertyNode(prop, Optional.empty()); + values.add(Fun.Tuple2.of(node, value)); } - + } - + } public InsertOperation ifNotExists() { this.ifNotExists = true; return this; } - + public InsertOperation ifNotExists(boolean enable) { this.ifNotExists = enable; return this; } - + public InsertOperation value(Getter getter, V val) { - + Objects.requireNonNull(getter, "getter is empty"); - + if (val != null) { - CasserPropertyNode node = MappingUtil.resolveMappingProperty(getter); - + HelenusPropertyNode node = MappingUtil.resolveMappingProperty(getter); + Object value = sessionOps.getValuePreparer().prepareColumnValue(val, node.getProperty()); - + if (value != null) { - values.add(Tuple2.of(node, value)); + values.add(Fun.Tuple2.of(node, value)); } } - + return this; } - + @Override public BuiltStatement buildStatement() { - + values.forEach(t -> addPropertyNode(t._1)); - + if (entity == null) { - throw new CasserMappingException("unknown entity"); + throw new HelenusMappingException("unknown entity"); } - + Insert insert = QueryBuilder.insertInto(entity.getName().toCql()); - + if (ifNotExists) { insert.ifNotExists(); } - + values.forEach(t -> { insert.value(t._1.getColumnName(), t._2); }); - + if (this.ttl != null) { insert.using(QueryBuilder.ttl(this.ttl[0])); } if (this.timestamp != null) { insert.using(QueryBuilder.timestamp(this.timestamp[0])); } - + return insert; } @@ -144,13 +145,13 @@ public final class InsertOperation extends AbstractOperation { private final PreparedStatement preparedStatement; private final AbstractOperation operation; - + public PreparedOperation(PreparedStatement statement, AbstractOperation operation) { this.preparedStatement = statement; this.operation = operation; @@ -33,9 +33,9 @@ public final class PreparedOperation { } public BoundOperation bind(Object... params) { - + BoundStatement boundStatement = preparedStatement.bind(params); - + return new BoundOperation(boundStatement, operation); } @@ -43,5 +43,5 @@ public final class PreparedOperation { public String toString() { return preparedStatement.getQueryString(); } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/PreparedOptionalOperation.java b/src/main/java/net/helenus/core/operation/PreparedOptionalOperation.java similarity index 93% rename from src/main/java/com/noorq/casser/core/operation/PreparedOptionalOperation.java rename to src/main/java/net/helenus/core/operation/PreparedOptionalOperation.java index 8eeb2b6..0e722bc 100644 --- a/src/main/java/com/noorq/casser/core/operation/PreparedOptionalOperation.java +++ b/src/main/java/net/helenus/core/operation/PreparedOptionalOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; @@ -22,27 +22,26 @@ public final class PreparedOptionalOperation { private final PreparedStatement preparedStatement; private final AbstractOptionalOperation operation; - + public PreparedOptionalOperation(PreparedStatement statement, AbstractOptionalOperation operation) { this.preparedStatement = statement; this.operation = operation; } - + public PreparedStatement getPreparedStatement() { return preparedStatement; } - + public BoundOptionalOperation bind(Object... params) { - + BoundStatement boundStatement = preparedStatement.bind(params); - + return new BoundOptionalOperation(boundStatement, operation); } - + @Override public String toString() { return preparedStatement.getQueryString(); } - } diff --git a/src/main/java/com/noorq/casser/core/operation/PreparedStreamOperation.java b/src/main/java/net/helenus/core/operation/PreparedStreamOperation.java similarity index 93% rename from src/main/java/com/noorq/casser/core/operation/PreparedStreamOperation.java rename to src/main/java/net/helenus/core/operation/PreparedStreamOperation.java index 0b234ba..e9d255e 100644 --- a/src/main/java/com/noorq/casser/core/operation/PreparedStreamOperation.java +++ b/src/main/java/net/helenus/core/operation/PreparedStreamOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; @@ -22,27 +22,26 @@ public final class PreparedStreamOperation { private final PreparedStatement preparedStatement; private final AbstractStreamOperation operation; - + public PreparedStreamOperation(PreparedStatement statement, AbstractStreamOperation operation) { this.preparedStatement = statement; this.operation = operation; } - + public PreparedStatement getPreparedStatement() { return preparedStatement; } - + public BoundStreamOperation bind(Object... params) { - + BoundStatement boundStatement = preparedStatement.bind(params); - + return new BoundStreamOperation(boundStatement, operation); } - + @Override public String toString() { return preparedStatement.getQueryString(); } - } diff --git a/src/main/java/com/noorq/casser/core/operation/SelectFirstOperation.java b/src/main/java/net/helenus/core/operation/SelectFirstOperation.java similarity index 90% rename from src/main/java/com/noorq/casser/core/operation/SelectFirstOperation.java rename to src/main/java/net/helenus/core/operation/SelectFirstOperation.java index 8431db7..89b1909 100644 --- a/src/main/java/com/noorq/casser/core/operation/SelectFirstOperation.java +++ b/src/main/java/net/helenus/core/operation/SelectFirstOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.Optional; import java.util.function.Function; @@ -21,23 +21,22 @@ import java.util.function.Function; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.querybuilder.BuiltStatement; - public final class SelectFirstOperation extends AbstractFilterOptionalOperation> { private final SelectOperation src; - + public SelectFirstOperation(SelectOperation src) { super(src.sessionOps); - + this.src = src; this.filters = src.filters; this.ifFilters = src.ifFilters; } - + public SelectFirstTransformingOperation map(Function fn) { return new SelectFirstTransformingOperation(src, fn); } - + @Override public BuiltStatement buildStatement() { return src.buildStatement(); @@ -47,6 +46,5 @@ public final class SelectFirstOperation extends AbstractFilterOptionalOperati public Optional transform(ResultSet resultSet) { return src.transform(resultSet).findFirst(); } - - + } diff --git a/src/main/java/com/noorq/casser/core/operation/SelectFirstTransformingOperation.java b/src/main/java/net/helenus/core/operation/SelectFirstTransformingOperation.java similarity index 81% rename from src/main/java/com/noorq/casser/core/operation/SelectFirstTransformingOperation.java rename to src/main/java/net/helenus/core/operation/SelectFirstTransformingOperation.java index f804532..9b4fd49 100644 --- a/src/main/java/com/noorq/casser/core/operation/SelectFirstTransformingOperation.java +++ b/src/main/java/net/helenus/core/operation/SelectFirstTransformingOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.Optional; import java.util.function.Function; @@ -21,21 +21,22 @@ import java.util.function.Function; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.querybuilder.BuiltStatement; - -public final class SelectFirstTransformingOperation extends AbstractFilterOptionalOperation> { +public final class SelectFirstTransformingOperation + extends + AbstractFilterOptionalOperation> { private final SelectOperation src; private final Function fn; - + public SelectFirstTransformingOperation(SelectOperation src, Function fn) { super(src.sessionOps); - + this.src = src; this.fn = fn; this.filters = src.filters; this.ifFilters = src.ifFilters; } - + @Override public BuiltStatement buildStatement() { return src.buildStatement(); diff --git a/src/main/java/com/noorq/casser/core/operation/SelectOperation.java b/src/main/java/net/helenus/core/operation/SelectOperation.java similarity index 62% rename from src/main/java/com/noorq/casser/core/operation/SelectOperation.java rename to src/main/java/net/helenus/core/operation/SelectOperation.java index 1d239e9..4df5583 100644 --- a/src/main/java/com/noorq/casser/core/operation/SelectOperation.java +++ b/src/main/java/net/helenus/core/operation/SelectOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Spliterator; -import java.util.Spliterators; +import java.util.*; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -35,140 +28,129 @@ import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; import com.datastax.driver.core.querybuilder.Select.Selection; import com.datastax.driver.core.querybuilder.Select.Where; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.Ordered; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.OrderingDirection; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.mapping.value.ValueProviderMap; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Fun.ArrayTuple; +import net.helenus.core.*; +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.OrderingDirection; +import net.helenus.mapping.value.ColumnValueProvider; +import net.helenus.mapping.value.ValueProviderMap; +import net.helenus.support.Fun; +import net.helenus.support.HelenusMappingException; public final class SelectOperation extends AbstractFilterStreamOperation> { protected Function rowMapper = null; - protected final List props = new ArrayList(); - + protected final List props = new ArrayList(); + protected List ordering = null; protected Integer limit = null; protected boolean allowFiltering = false; - + public SelectOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); - + this.rowMapper = new Function() { @Override public E apply(Row source) { - - ColumnValueProvider valueProvider = sessionOps.getValueProvider(); + + ColumnValueProvider valueProvider = sessionOps.getValueProvider(); Object[] arr = new Object[props.size()]; - + int i = 0; - for (CasserPropertyNode p : props) { + for (HelenusPropertyNode p : props) { Object value = valueProvider.getColumnValue(source, -1, p.getProperty()); arr[i++] = value; } - - return (E) ArrayTuple.of(arr); + + return (E) Fun.ArrayTuple.of(arr); } - + }; } - - public SelectOperation(AbstractSessionOperations sessionOperations, - CasserEntity entity) { - + + public SelectOperation(AbstractSessionOperations sessionOperations, HelenusEntity entity) { + super(sessionOperations); - - entity.getOrderedProperties() - .stream() - .map(p -> new CasserPropertyNode(p, Optional.empty())) - .forEach(p -> this.props.add(p)); - - } - - public SelectOperation(AbstractSessionOperations sessionOperations, - CasserEntity entity, - Function rowMapper) { - - super(sessionOperations); - this.rowMapper = rowMapper; - - entity.getOrderedProperties() - .stream() - .map(p -> new CasserPropertyNode(p, Optional.empty())) - .forEach(p -> this.props.add(p)); - + + entity.getOrderedProperties().stream().map(p -> new HelenusPropertyNode(p, Optional.empty())) + .forEach(p -> this.props.add(p)); + } - public SelectOperation(AbstractSessionOperations sessionOperations, - Function rowMapper, - CasserPropertyNode... props) { - + public SelectOperation(AbstractSessionOperations sessionOperations, HelenusEntity entity, + Function rowMapper) { + + super(sessionOperations); + this.rowMapper = rowMapper; + + entity.getOrderedProperties().stream().map(p -> new HelenusPropertyNode(p, Optional.empty())) + .forEach(p -> this.props.add(p)); + + } + + public SelectOperation(AbstractSessionOperations sessionOperations, Function rowMapper, + HelenusPropertyNode... props) { + super(sessionOperations); this.rowMapper = rowMapper; Collections.addAll(this.props, props); } - + public CountOperation count() { - - CasserEntity entity = null; - for (CasserPropertyNode prop : props) { - + + HelenusEntity entity = null; + for (HelenusPropertyNode prop : props) { + if (entity == null) { entity = prop.getEntity(); - } - else if (entity != prop.getEntity()) { - throw new CasserMappingException("you can count records only from a single entity " + entity.getMappingInterface() + " or " + prop.getEntity().getMappingInterface()); + } else if (entity != prop.getEntity()) { + throw new HelenusMappingException("you can count records only from a single entity " + + entity.getMappingInterface() + " or " + prop.getEntity().getMappingInterface()); } } - + return new CountOperation(sessionOps, entity); } - + public SelectFirstOperation single() { limit(1); return new SelectFirstOperation(this); } - + public SelectTransformingOperation mapTo(Class entityClass) { - + Objects.requireNonNull(entityClass, "entityClass is null"); - - CasserEntity entity = Casser.entity(entityClass); - + + HelenusEntity entity = Helenus.entity(entityClass); + this.rowMapper = null; - + return new SelectTransformingOperation(this, (r) -> { Map map = new ValueProviderMap(r, sessionOps.getValueProvider(), entity); - return (R) Casser.map(entityClass, map); - + return (R) Helenus.map(entityClass, map); + }); } - + public SelectTransformingOperation map(Function fn) { return new SelectTransformingOperation(this, fn); } - + public SelectOperation column(Getter getter) { - CasserPropertyNode p = MappingUtil.resolveMappingProperty(getter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(getter); this.props.add(p); return this; } - + public SelectOperation orderBy(Getter getter, OrderingDirection direction) { getOrCreateOrdering().add(new Ordered(getter, direction).getOrdering()); return this; } - + public SelectOperation orderBy(Ordered ordered) { getOrCreateOrdering().add(ordered.getOrdering()); return this; @@ -178,89 +160,91 @@ public final class SelectOperation extends AbstractFilterStreamOperation allowFiltering() { this.allowFiltering = true; return this; } - + @Override public BuiltStatement buildStatement() { - - CasserEntity entity = null; + + HelenusEntity entity = null; Selection selection = QueryBuilder.select(); - - for (CasserPropertyNode prop : props) { + + for (HelenusPropertyNode prop : props) { selection = selection.column(prop.getColumnName()); - + + if (prop.getProperty().caseSensitiveIndex()) { + allowFiltering = true; + } + if (entity == null) { entity = prop.getEntity(); - } - else if (entity != prop.getEntity()) { - throw new CasserMappingException("you can select columns only from a single entity " + entity.getMappingInterface() + " or " + prop.getEntity().getMappingInterface()); + } else if (entity != prop.getEntity()) { + throw new HelenusMappingException("you can select columns only from a single entity " + + entity.getMappingInterface() + " or " + prop.getEntity().getMappingInterface()); } } - + if (entity == null) { - throw new CasserMappingException("no entity or table to select data"); + throw new HelenusMappingException("no entity or table to select data"); } - + Select select = selection.from(entity.getName().toCql()); - + if (ordering != null && !ordering.isEmpty()) { select.orderBy(ordering.toArray(new Ordering[ordering.size()])); } - + if (limit != null) { - select.limit(limit.intValue()); + select.limit(limit); } if (filters != null && !filters.isEmpty()) { - + Where where = select.where(); - + for (Filter filter : filters) { where.and(filter.getClause(sessionOps.getValuePreparer())); } } - + if (ifFilters != null && !ifFilters.isEmpty()) { logger.error("onlyIf conditions " + ifFilters + " would be ignored in the statement " + select); } - + if (allowFiltering) { select.allowFiltering(); } - + return select; } @SuppressWarnings("unchecked") @Override public Stream transform(ResultSet resultSet) { - + if (rowMapper != null) { - - return StreamSupport.stream( - Spliterators.spliteratorUnknownSize(resultSet.iterator(), Spliterator.ORDERED) - , false).map(rowMapper); + + return StreamSupport + .stream(Spliterators.spliteratorUnknownSize(resultSet.iterator(), Spliterator.ORDERED), false) + .map(rowMapper); } - + else { - - return (Stream) StreamSupport.stream( - Spliterators.spliteratorUnknownSize(resultSet.iterator(), Spliterator.ORDERED) - , false); + + return (Stream) StreamSupport + .stream(Spliterators.spliteratorUnknownSize(resultSet.iterator(), Spliterator.ORDERED), false); } } - private List getOrCreateOrdering() { if (ordering == null) { ordering = new ArrayList(); } return ordering; } - + } diff --git a/src/main/java/com/noorq/casser/core/operation/SelectTransformingOperation.java b/src/main/java/net/helenus/core/operation/SelectTransformingOperation.java similarity index 81% rename from src/main/java/com/noorq/casser/core/operation/SelectTransformingOperation.java rename to src/main/java/net/helenus/core/operation/SelectTransformingOperation.java index 83073c7..bfbb2db 100644 --- a/src/main/java/com/noorq/casser/core/operation/SelectTransformingOperation.java +++ b/src/main/java/net/helenus/core/operation/SelectTransformingOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; import java.util.function.Function; import java.util.stream.Stream; @@ -21,21 +21,22 @@ import java.util.stream.Stream; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.querybuilder.BuiltStatement; - -public final class SelectTransformingOperation extends AbstractFilterStreamOperation> { +public final class SelectTransformingOperation + extends + AbstractFilterStreamOperation> { private final SelectOperation src; private final Function fn; - + public SelectTransformingOperation(SelectOperation src, Function fn) { super(src.sessionOps); - + this.src = src; this.fn = fn; this.filters = src.filters; this.ifFilters = src.ifFilters; } - + @Override public BuiltStatement buildStatement() { return src.buildStatement(); @@ -45,6 +46,5 @@ public final class SelectTransformingOperation extends AbstractFilterStrea public Stream transform(ResultSet resultSet) { return src.transform(resultSet).map(fn); } - - + } diff --git a/src/main/java/com/noorq/casser/core/operation/UpdateOperation.java b/src/main/java/net/helenus/core/operation/UpdateOperation.java similarity index 74% rename from src/main/java/com/noorq/casser/core/operation/UpdateOperation.java rename to src/main/java/net/helenus/core/operation/UpdateOperation.java index 4facde3..78a1b9d 100644 --- a/src/main/java/com/noorq/casser/core/operation/UpdateOperation.java +++ b/src/main/java/net/helenus/core/operation/UpdateOperation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.operation; +package net.helenus.core.operation; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.function.Function; import com.datastax.driver.core.ResultSet; @@ -28,77 +23,75 @@ import com.datastax.driver.core.querybuilder.Assignment; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Update; -import com.noorq.casser.core.AbstractSessionOperations; -import com.noorq.casser.core.CasserValidator; -import com.noorq.casser.core.Filter; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Immutables; +import net.helenus.core.AbstractSessionOperations; +import net.helenus.core.Filter; +import net.helenus.core.Getter; +import net.helenus.core.reflect.HelenusPropertyNode; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.MappingUtil; +import net.helenus.support.HelenusMappingException; +import net.helenus.support.Immutables; public final class UpdateOperation extends AbstractFilterOperation { - - private CasserEntity entity = null; - + + private HelenusEntity entity = null; + private final List assignments = new ArrayList(); private int[] ttl; private long[] timestamp; - + public UpdateOperation(AbstractSessionOperations sessionOperations) { super(sessionOperations); } - - public UpdateOperation(AbstractSessionOperations sessionOperations, CasserPropertyNode p, Object v) { + + public UpdateOperation(AbstractSessionOperations sessionOperations, HelenusPropertyNode p, Object v) { super(sessionOperations); - + Object value = sessionOps.getValuePreparer().prepareColumnValue(v, p.getProperty()); assignments.add(QueryBuilder.set(p.getColumnName(), value)); - + addPropertyNode(p); } - + public UpdateOperation set(Getter getter, V v) { Objects.requireNonNull(getter, "getter is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(getter); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(getter); + Object value = sessionOps.getValuePreparer().prepareColumnValue(v, p.getProperty()); assignments.add(QueryBuilder.set(p.getColumnName(), value)); - + addPropertyNode(p); - + return this; } - - + /* - * - * + * + * * COUNTER - * - * + * + * */ - + public UpdateOperation increment(Getter counterGetter) { return increment(counterGetter, 1L); } public UpdateOperation increment(Getter counterGetter, long delta) { - + Objects.requireNonNull(counterGetter, "counterGetter is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(counterGetter); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(counterGetter); + assignments.add(QueryBuilder.incr(p.getColumnName(), delta)); - + addPropertyNode(p); return this; - + } public UpdateOperation decrement(Getter counterGetter) { @@ -106,145 +99,143 @@ public final class UpdateOperation extends AbstractFilterOperation UpdateOperation decrement(Getter counterGetter, long delta) { - + Objects.requireNonNull(counterGetter, "counterGetter is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(counterGetter); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(counterGetter); + assignments.add(QueryBuilder.decr(p.getColumnName(), delta)); - + addPropertyNode(p); return this; - + } - + /* - * - * + * + * * LIST - * + * */ - public UpdateOperation prepend(Getter> listGetter, V value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); Object valueObj = prepareSingleListValue(p, value); assignments.add(QueryBuilder.prepend(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } public UpdateOperation prependAll(Getter> listGetter, List value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); List valueObj = prepareListValue(p, value); - + assignments.add(QueryBuilder.prependAll(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation setIdx(Getter> listGetter, int idx, V value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); Object valueObj = prepareSingleListValue(p, value); - + assignments.add(QueryBuilder.setIdx(p.getColumnName(), idx, valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation append(Getter> listGetter, V value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); Object valueObj = prepareSingleListValue(p, value); assignments.add(QueryBuilder.append(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation appendAll(Getter> listGetter, List value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); List valueObj = prepareListValue(p, value); assignments.add(QueryBuilder.appendAll(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - - + public UpdateOperation discard(Getter> listGetter, V value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); Object valueObj = prepareSingleListValue(p, value); - + assignments.add(QueryBuilder.discard(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation discardAll(Getter> listGetter, List value) { - + Objects.requireNonNull(listGetter, "listGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(listGetter); List valueObj = prepareListValue(p, value); assignments.add(QueryBuilder.discardAll(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - - private Object prepareSingleListValue(CasserPropertyNode p, Object value) { - CasserProperty prop = p.getProperty(); + + private Object prepareSingleListValue(HelenusPropertyNode p, Object value) { + HelenusProperty prop = p.getProperty(); Object valueObj = value; - + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { List convertedList = (List) converter.get().apply(Immutables.listOf(value)); valueObj = convertedList.get(0); } - + return valueObj; } - - private List prepareListValue(CasserPropertyNode p, List value) { - - CasserProperty prop = p.getProperty(); - + + private List prepareListValue(HelenusPropertyNode p, List value) { + + HelenusProperty prop = p.getProperty(); + List valueObj = value; - + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { valueObj = (List) converter.get().apply(value); @@ -252,157 +243,156 @@ public final class UpdateOperation extends AbstractFilterOperation UpdateOperation add(Getter> setGetter, V value) { - + Objects.requireNonNull(setGetter, "setGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); Object valueObj = prepareSingleSetValue(p, value); assignments.add(QueryBuilder.add(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation addAll(Getter> setGetter, Set value) { - + Objects.requireNonNull(setGetter, "setGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); Set valueObj = prepareSetValue(p, value); - + assignments.add(QueryBuilder.addAll(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation remove(Getter> setGetter, V value) { - + Objects.requireNonNull(setGetter, "setGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); Object valueObj = prepareSingleSetValue(p, value); - + assignments.add(QueryBuilder.remove(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - + public UpdateOperation removeAll(Getter> setGetter, Set value) { - + Objects.requireNonNull(setGetter, "setGetter is empty"); Objects.requireNonNull(value, "value is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(setGetter); Set valueObj = prepareSetValue(p, value); - + assignments.add(QueryBuilder.removeAll(p.getColumnName(), valueObj)); - + addPropertyNode(p); return this; } - - private Object prepareSingleSetValue(CasserPropertyNode p, Object value) { - - CasserProperty prop = p.getProperty(); + + private Object prepareSingleSetValue(HelenusPropertyNode p, Object value) { + + HelenusProperty prop = p.getProperty(); Object valueObj = value; - + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { Set convertedSet = (Set) converter.get().apply(Immutables.setOf(value)); valueObj = convertedSet.iterator().next(); } - + return valueObj; } - - private Set prepareSetValue(CasserPropertyNode p, Set value) { - - CasserProperty prop = p.getProperty(); + + private Set prepareSetValue(HelenusPropertyNode p, Set value) { + + HelenusProperty prop = p.getProperty(); Set valueObj = value; - + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { valueObj = (Set) converter.get().apply(value); } - + return valueObj; } - + /* - * - * + * + * * MAP - * - * + * + * */ - - public UpdateOperation put(Getter> mapGetter, K key, V value) { - + + public UpdateOperation put(Getter> mapGetter, K key, V value) { + Objects.requireNonNull(mapGetter, "mapGetter is empty"); Objects.requireNonNull(key, "key is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(mapGetter); - CasserProperty prop = p.getProperty(); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(mapGetter); + HelenusProperty prop = p.getProperty(); + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { - Map convertedMap = (Map) converter.get().apply(Immutables.mapOf(key, value)); + Map convertedMap = (Map) converter.get() + .apply(Immutables.mapOf(key, value)); for (Map.Entry e : convertedMap.entrySet()) { assignments.add(QueryBuilder.put(p.getColumnName(), e.getKey(), e.getValue())); } - } - else { + } else { assignments.add(QueryBuilder.put(p.getColumnName(), key, value)); } - + addPropertyNode(p); return this; - } - - public UpdateOperation putAll(Getter> mapGetter, Map map) { - + } + + public UpdateOperation putAll(Getter> mapGetter, Map map) { + Objects.requireNonNull(mapGetter, "mapGetter is empty"); Objects.requireNonNull(map, "map is empty"); - CasserPropertyNode p = MappingUtil.resolveMappingProperty(mapGetter); - CasserProperty prop = p.getProperty(); - + HelenusPropertyNode p = MappingUtil.resolveMappingProperty(mapGetter); + HelenusProperty prop = p.getProperty(); + Optional> converter = prop.getWriteConverter(sessionOps.getSessionRepository()); if (converter.isPresent()) { Map convertedMap = (Map) converter.get().apply(map); assignments.add(QueryBuilder.putAll(p.getColumnName(), convertedMap)); - } - else { + } else { assignments.add(QueryBuilder.putAll(p.getColumnName(), map)); } - + addPropertyNode(p); return this; - } - + } + @Override public BuiltStatement buildStatement() { - + if (entity == null) { - throw new CasserMappingException("empty update operation"); + throw new HelenusMappingException("empty update operation"); } - + Update update = QueryBuilder.update(entity.getName().toCql()); for (Assignment assignment : assignments) { @@ -410,26 +400,26 @@ public final class UpdateOperation extends AbstractFilterOperation filter : filters) { update.where(filter.getClause(sessionOps.getValuePreparer())); } } - + if (ifFilters != null && !ifFilters.isEmpty()) { - + for (Filter filter : ifFilters) { update.onlyIf(filter.getClause(sessionOps.getValuePreparer())); } } - + if (this.ttl != null) { update.using(QueryBuilder.ttl(this.ttl[0])); } if (this.timestamp != null) { update.using(QueryBuilder.timestamp(this.timestamp[0])); } - + return update; } @@ -437,7 +427,7 @@ public final class UpdateOperation extends AbstractFilterOperation primitiveClass; private final Object defaultValue; - + private final static Map, DefaultPrimitiveTypes> map = new HashMap, DefaultPrimitiveTypes>(); - + static { for (DefaultPrimitiveTypes type : DefaultPrimitiveTypes.values()) { map.put(type.getPrimitiveClass(), type); } } - + private DefaultPrimitiveTypes(Class primitiveClass, Object defaultValue) { this.primitiveClass = primitiveClass; this.defaultValue = defaultValue; @@ -48,7 +42,7 @@ public enum DefaultPrimitiveTypes { public static DefaultPrimitiveTypes lookup(Class primitiveClass) { return map.get(primitiveClass); } - + public Class getPrimitiveClass() { return primitiveClass; } diff --git a/src/main/java/com/noorq/casser/core/reflect/DslExportable.java b/src/main/java/net/helenus/core/reflect/DslExportable.java similarity index 61% rename from src/main/java/com/noorq/casser/core/reflect/DslExportable.java rename to src/main/java/net/helenus/core/reflect/DslExportable.java index afa606a..46e60c7 100644 --- a/src/main/java/com/noorq/casser/core/reflect/DslExportable.java +++ b/src/main/java/net/helenus/core/reflect/DslExportable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; - -import com.noorq.casser.mapping.CasserEntity; +package net.helenus.core.reflect; +import net.helenus.mapping.HelenusEntity; public interface DslExportable { - - public static final String GET_ENTITY_METHOD = "getCasserMappingEntity"; - public static final String GET_PARENT_METHOD = "getParentDslCasserPropertyNode"; - - CasserEntity getCasserMappingEntity(); - - CasserPropertyNode getParentDslCasserPropertyNode(); - + + public static final String GET_ENTITY_METHOD = "getHelenusMappingEntity"; + public static final String GET_PARENT_METHOD = "getParentDslHelenusPropertyNode"; + + HelenusEntity getHelenusMappingEntity(); + + HelenusPropertyNode getParentDslHelenusPropertyNode(); + } diff --git a/src/main/java/com/noorq/casser/core/reflect/DslInvocationHandler.java b/src/main/java/net/helenus/core/reflect/DslInvocationHandler.java similarity index 55% rename from src/main/java/com/noorq/casser/core/reflect/DslInvocationHandler.java rename to src/main/java/net/helenus/core/reflect/DslInvocationHandler.java index b309081..7446da9 100644 --- a/src/main/java/com/noorq/casser/core/reflect/DslInvocationHandler.java +++ b/src/main/java/net/helenus/core/reflect/DslInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -22,72 +24,69 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TupleType; -import com.datastax.driver.core.TupleValue; -import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.Casser; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserMappingEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.mapping.type.UDTDataType; -import com.noorq.casser.support.CasserException; -import com.noorq.casser.support.DslPropertyException; +import com.datastax.driver.core.*; + +import net.helenus.core.Helenus; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusMappingEntity; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.mapping.type.UDTDataType; +import net.helenus.support.DslPropertyException; +import net.helenus.support.HelenusException; public class DslInvocationHandler implements InvocationHandler { - private final CasserEntity entity; - private final Optional parent; - - private final Map map = new HashMap(); - + private final HelenusEntity entity; + private final Optional parent; + + private final Map map = new HashMap(); + private final Map udtMap = new HashMap(); private final Map tupleMap = new HashMap(); - public DslInvocationHandler(Class iface, ClassLoader classLoader, Optional parent) { - - this.entity = new CasserMappingEntity(iface); + public DslInvocationHandler(Class iface, ClassLoader classLoader, Optional parent, Metadata metadata) { + + this.entity = new HelenusMappingEntity(iface, metadata); this.parent = parent; - - for (CasserProperty prop : entity.getOrderedProperties()) { - + + for (HelenusProperty prop : entity.getOrderedProperties()) { + map.put(prop.getGetterMethod(), prop); - + AbstractDataType type = prop.getDataType(); Class javaType = prop.getJavaType(); - + if (type instanceof UDTDataType && !UDTValue.class.isAssignableFrom(javaType)) { - Object childDsl = Casser.dsl(javaType, classLoader, - Optional.of(new CasserPropertyNode(prop, parent))); - + Object childDsl = Helenus.dsl(javaType, classLoader, + Optional.of(new HelenusPropertyNode(prop, parent)), metadata); + udtMap.put(prop.getGetterMethod(), childDsl); } - + if (type instanceof DTDataType) { DTDataType dataType = (DTDataType) type; - + if (dataType.getDataType() instanceof TupleType && !TupleValue.class.isAssignableFrom(javaType)) { - - Object childDsl = Casser.dsl(javaType, classLoader, - Optional.of(new CasserPropertyNode(prop, parent))); - + + Object childDsl = Helenus.dsl(javaType, classLoader, + Optional.of(new HelenusPropertyNode(prop, parent)), metadata); + tupleMap.put(prop.getGetterMethod(), childDsl); - + } } - + } } - + @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - - String methodName = method.getName(); - + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + String methodName = method.getName(); + if ("equals".equals(methodName) && method.getParameterCount() == 1) { Object otherObj = args[0]; if (otherObj == null) { @@ -98,80 +97,83 @@ public class DslInvocationHandler implements InvocationHandler { } return false; } - + if (method.getParameterCount() != 0 || method.getReturnType() == void.class) { - throw new CasserException("invalid getter method " + method); + throw new HelenusException("invalid getter method " + method); } - + if ("hashCode".equals(methodName)) { return hashCode(); } - + if ("toString".equals(methodName)) { return entity.toString(); } - + if (DslExportable.GET_ENTITY_METHOD.equals(methodName)) { return entity; } - + if (DslExportable.GET_PARENT_METHOD.equals(methodName)) { return parent.get(); } - - CasserProperty prop = map.get(method); - + + + HelenusProperty prop = map.get(method); + if (prop == null) { + prop = entity.getProperty(methodName); + } + if (prop != null) { - + AbstractDataType type = prop.getDataType(); - + if (type instanceof UDTDataType) { - + Object childDsl = udtMap.get(method); - + if (childDsl != null) { return childDsl; } - + } - + if (type instanceof DTDataType) { DTDataType dataType = (DTDataType) type; DataType dt = dataType.getDataType(); - - switch(dt.getName()) { - - case TUPLE: - - Object childDsl = tupleMap.get(method); - - if (childDsl != null) { - return childDsl; - } - - break; - - case SET: - return new SetDsl(new CasserPropertyNode(prop, parent)); - - case LIST: - return new ListDsl(new CasserPropertyNode(prop, parent)); - case MAP: - return new MapDsl(new CasserPropertyNode(prop, parent)); + switch (dt.getName()) { + + case TUPLE : + + Object childDsl = tupleMap.get(method); + + if (childDsl != null) { + return childDsl; + } + + break; + + case SET : + return new SetDsl(new HelenusPropertyNode(prop, parent)); + + case LIST : + return new ListDsl(new HelenusPropertyNode(prop, parent)); + + case MAP : + return new MapDsl(new HelenusPropertyNode(prop, parent)); + + default : + break; - default: - break; - } - } - - throw new DslPropertyException(new CasserPropertyNode(prop, parent)); + + throw new DslPropertyException(new HelenusPropertyNode(prop, parent)); } - - throw new CasserException("invalid method call " + method); + + throw new HelenusException("invalid method call " + method); } } diff --git a/src/main/java/com/noorq/casser/core/reflect/CasserNamedProperty.java b/src/main/java/net/helenus/core/reflect/HelenusNamedProperty.java similarity index 60% rename from src/main/java/com/noorq/casser/core/reflect/CasserNamedProperty.java rename to src/main/java/net/helenus/core/reflect/HelenusNamedProperty.java index aeea817..5affe00 100644 --- a/src/main/java/com/noorq/casser/core/reflect/CasserNamedProperty.java +++ b/src/main/java/net/helenus/core/reflect/HelenusNamedProperty.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -22,27 +22,22 @@ import java.util.function.Function; import javax.validation.ConstraintValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.OrderingDirection; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.*; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.support.HelenusMappingException; -public final class CasserNamedProperty implements CasserProperty { +public final class HelenusNamedProperty implements HelenusProperty { private final String name; - - public CasserNamedProperty(String name) { + + public HelenusNamedProperty(String name) { this.name = name; } @Override - public CasserEntity getEntity() { - throw new CasserMappingException("will never called"); + public HelenusEntity getEntity() { + throw new HelenusMappingException("will never called"); } @Override @@ -52,7 +47,7 @@ public final class CasserNamedProperty implements CasserProperty { @Override public Method getGetterMethod() { - throw new CasserMappingException("will never called"); + throw new HelenusMappingException("will never called"); } @Override @@ -65,14 +60,17 @@ public final class CasserNamedProperty implements CasserProperty { return Optional.empty(); } + @Override + public boolean caseSensitiveIndex() { return false; } + @Override public Class getJavaType() { - throw new CasserMappingException("will never called"); + throw new HelenusMappingException("will never called"); } @Override public AbstractDataType getDataType() { - throw new CasserMappingException("will never called"); + throw new HelenusMappingException("will never called"); } @Override @@ -91,17 +89,15 @@ public final class CasserNamedProperty implements CasserProperty { } @Override - public Optional> getReadConverter( - SessionRepository repository) { + public Optional> getReadConverter(SessionRepository repository) { return Optional.empty(); } @Override - public Optional> getWriteConverter( - SessionRepository repository) { + public Optional> getWriteConverter(SessionRepository repository) { return Optional.empty(); } - + @Override public ConstraintValidator[] getValidators() { return MappingUtil.EMPTY_VALIDATORS; diff --git a/src/main/java/com/noorq/casser/core/reflect/CasserPropertyNode.java b/src/main/java/net/helenus/core/reflect/HelenusPropertyNode.java similarity index 54% rename from src/main/java/com/noorq/casser/core/reflect/CasserPropertyNode.java rename to src/main/java/net/helenus/core/reflect/HelenusPropertyNode.java index cbf8e73..26050a5 100644 --- a/src/main/java/com/noorq/casser/core/reflect/CasserPropertyNode.java +++ b/src/main/java/net/helenus/core/reflect/HelenusPropertyNode.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; +import java.util.*; import java.util.stream.Collectors; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusProperty; -public final class CasserPropertyNode implements Iterable { +public final class HelenusPropertyNode implements Iterable { - private final CasserProperty prop; - private final Optional next; - - public CasserPropertyNode(CasserProperty prop, Optional next) { + private final HelenusProperty prop; + private final Optional next; + + public HelenusPropertyNode(HelenusProperty prop, Optional next) { this.prop = prop; this.next = next; } @@ -39,77 +35,74 @@ public final class CasserPropertyNode implements Iterable { if (next.isPresent()) { List columnNames = new ArrayList(); - for (CasserProperty p : this) { + for (HelenusProperty p : this) { columnNames.add(p.getColumnName().toCql(true)); } Collections.reverse(columnNames); - - if (prop instanceof CasserNamedProperty) { + + if (prop instanceof HelenusNamedProperty) { int size = columnNames.size(); StringBuilder str = new StringBuilder(); - for (int i = 0; i != size -1; ++i) { + for (int i = 0; i != size - 1; ++i) { if (str.length() != 0) { str.append("."); } str.append(columnNames.get(i)); } - str.append("[").append(columnNames.get(size-1)).append("]"); + str.append("[").append(columnNames.get(size - 1)).append("]"); return str.toString(); - } - else { + } else { return columnNames.stream().collect(Collectors.joining(".")); } - } - else { + } else { return prop.getColumnName().toCql(); } } - - public CasserEntity getEntity() { + + public HelenusEntity getEntity() { if (next.isPresent()) { - CasserProperty last = prop; - for (CasserProperty p : this) { + HelenusProperty last = prop; + for (HelenusProperty p : this) { last = p; } return last.getEntity(); - } - else { + } else { return prop.getEntity(); } } - - public CasserProperty getProperty() { + + public HelenusProperty getProperty() { return prop; } - public Optional getNext() { + public Optional getNext() { return next; } - - public Iterator iterator() { + + public Iterator iterator() { return new PropertyNodeIterator(Optional.of(this)); } - private static class PropertyNodeIterator implements Iterator { + private static class PropertyNodeIterator implements Iterator { - private Optional next; - - public PropertyNodeIterator(Optional next) { + private Optional next; + + public PropertyNodeIterator(Optional next) { this.next = next; } - + @Override public boolean hasNext() { return next.isPresent(); } @Override - public CasserProperty next() { - CasserPropertyNode node = next.get(); + public HelenusProperty next() { + HelenusPropertyNode node = next.get(); next = node.next; return node.prop; } - + } - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/ListDsl.java b/src/main/java/net/helenus/core/reflect/ListDsl.java similarity index 79% rename from src/main/java/com/noorq/casser/core/reflect/ListDsl.java rename to src/main/java/net/helenus/core/reflect/ListDsl.java index 2d01239..3a8755f 100644 --- a/src/main/java/com/noorq/casser/core/reflect/ListDsl.java +++ b/src/main/java/net/helenus/core/reflect/ListDsl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,34 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Optional; +import java.util.*; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.DslPropertyException; +import net.helenus.mapping.HelenusProperty; +import net.helenus.support.DslPropertyException; +import net.helenus.support.HelenusMappingException; public final class ListDsl implements List { - private final CasserPropertyNode parent; - - public ListDsl(CasserPropertyNode parent) { + private final HelenusPropertyNode parent; + + public ListDsl(HelenusPropertyNode parent) { this.parent = parent; } - - public CasserPropertyNode getParent() { + + public HelenusPropertyNode getParent() { return parent; } - + @Override public V get(int index) { - CasserProperty prop = new CasserNamedProperty(Integer.toString(index)); - throw new DslPropertyException(new CasserPropertyNode(prop, Optional.of(parent))); + HelenusProperty prop = new HelenusNamedProperty(Integer.toString(index)); + throw new DslPropertyException(new HelenusPropertyNode(prop, Optional.of(parent))); } @Override @@ -172,9 +168,9 @@ public final class ListDsl implements List { throwShouldNeverCall(); return null; } - + private void throwShouldNeverCall() { - throw new CasserMappingException("should be never called"); + throw new HelenusMappingException("should be never called"); } @Override diff --git a/src/main/java/com/noorq/casser/core/reflect/MapDsl.java b/src/main/java/net/helenus/core/reflect/MapDsl.java similarity index 76% rename from src/main/java/com/noorq/casser/core/reflect/MapDsl.java rename to src/main/java/net/helenus/core/reflect/MapDsl.java index 23662a4..3dbf5c8 100644 --- a/src/main/java/com/noorq/casser/core/reflect/MapDsl.java +++ b/src/main/java/net/helenus/core/reflect/MapDsl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,35 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.Set; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.DslPropertyException; +import net.helenus.mapping.HelenusProperty; +import net.helenus.support.DslPropertyException; +import net.helenus.support.HelenusMappingException; public final class MapDsl implements Map { - private final CasserPropertyNode parent; - - public MapDsl(CasserPropertyNode parent) { + private final HelenusPropertyNode parent; + + public MapDsl(HelenusPropertyNode parent) { this.parent = parent; } - public CasserPropertyNode getParent() { + public HelenusPropertyNode getParent() { return parent; } @Override public V get(Object key) { - CasserProperty prop = new CasserNamedProperty(key.toString()); - throw new DslPropertyException(new CasserPropertyNode(prop, Optional.of(parent))); + HelenusProperty prop = new HelenusNamedProperty(key.toString()); + throw new DslPropertyException(new HelenusPropertyNode(prop, Optional.of(parent))); } - + @Override public int size() { throwShouldNeverCall(); @@ -107,12 +107,12 @@ public final class MapDsl implements Map { } private void throwShouldNeverCall() { - throw new CasserMappingException("should be never called"); + throw new HelenusMappingException("should be never called"); } @Override public String toString() { return "MapDsl"; } - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/MapExportable.java b/src/main/java/net/helenus/core/reflect/MapExportable.java similarity index 89% rename from src/main/java/com/noorq/casser/core/reflect/MapExportable.java rename to src/main/java/net/helenus/core/reflect/MapExportable.java index c965a31..1e91946 100644 --- a/src/main/java/com/noorq/casser/core/reflect/MapExportable.java +++ b/src/main/java/net/helenus/core/reflect/MapExportable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.util.Map; public interface MapExportable { public static final String TO_MAP_METHOD = "toMap"; - + Map toMap(); - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/MapperInvocationHandler.java b/src/main/java/net/helenus/core/reflect/MapperInvocationHandler.java similarity index 54% rename from src/main/java/com/noorq/casser/core/reflect/MapperInvocationHandler.java rename to src/main/java/net/helenus/core/reflect/MapperInvocationHandler.java index b7261e9..4a1b1f8 100644 --- a/src/main/java/com/noorq/casser/core/reflect/MapperInvocationHandler.java +++ b/src/main/java/net/helenus/core/reflect/MapperInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Map; -import com.noorq.casser.support.CasserException; +import net.helenus.support.HelenusException; public class MapperInvocationHandler implements InvocationHandler { private final Map src; private final Class iface; - + public MapperInvocationHandler(Class iface, Map src) { this.src = src; this.iface = iface; } - + @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + if (method.isDefault()) { + // NOTE: This is reflection magic to invoke (non-recursively) a default method implemented on an interface + // that we've proxied (in ReflectionDslInstantiator). I found the answer in this article. + // https://zeroturnaround.com/rebellabs/recognize-and-conquer-java-proxies-default-methods-and-method-handles/ + + // First, we need an instance of a private inner-class found in MethodHandles. + Constructor constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); + constructor.setAccessible(true); + + // Now we need to lookup and invoke special the default method on the interface class. + final Class declaringClass = method.getDeclaringClass(); + Object result = constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE) + .unreflectSpecial(method, declaringClass) + .bindTo(proxy) + .invokeWithArguments(args); + return result; + } String methodName = method.getName(); @@ -49,9 +69,9 @@ public class MapperInvocationHandler implements InvocationHandler { } return false; } - + if (method.getParameterCount() != 0 || method.getReturnType() == void.class) { - throw new CasserException("invalid getter method " + method); + throw new HelenusException("invalid getter method " + method); } if ("hashCode".equals(methodName)) { @@ -67,25 +87,25 @@ public class MapperInvocationHandler implements InvocationHandler { } Object value = src.get(methodName); - + if (value == null) { - - Class returnType = method.getReturnType(); - + + Class returnType = method.getReturnType(); + if (returnType.isPrimitive()) { - + DefaultPrimitiveTypes type = DefaultPrimitiveTypes.lookup(returnType); if (type == null) { - throw new CasserException("unknown primitive type " + returnType); + throw new HelenusException("unknown primitive type " + returnType); } - + return type.getDefaultValue(); - + } - + } - + return value; } - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/ReflectionDslInstantiator.java b/src/main/java/net/helenus/core/reflect/ReflectionDslInstantiator.java similarity index 69% rename from src/main/java/com/noorq/casser/core/reflect/ReflectionDslInstantiator.java rename to src/main/java/net/helenus/core/reflect/ReflectionDslInstantiator.java index 2786547..48d0ffe 100644 --- a/src/main/java/com/noorq/casser/core/reflect/ReflectionDslInstantiator.java +++ b/src/main/java/net/helenus/core/reflect/ReflectionDslInstantiator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.lang.reflect.Proxy; import java.util.Optional; -import com.noorq.casser.core.DslInstantiator; +import com.datastax.driver.core.Metadata; +import net.helenus.core.DslInstantiator; public enum ReflectionDslInstantiator implements DslInstantiator { INSTANCE; - + @Override @SuppressWarnings("unchecked") - public E instantiate(Class iface, ClassLoader classLoader, Optional parent) { - DslInvocationHandler handler = new DslInvocationHandler(iface, classLoader, parent); - E proxy = (E) Proxy.newProxyInstance( - classLoader, - new Class[] { iface, DslExportable.class }, - handler); + public E instantiate(Class iface, ClassLoader classLoader, Optional parent, Metadata metadata) { + DslInvocationHandler handler = new DslInvocationHandler(iface, classLoader, parent, metadata); + E proxy = (E) Proxy.newProxyInstance(classLoader, new Class[]{iface, DslExportable.class}, handler); return proxy; } - - } diff --git a/src/main/java/com/noorq/casser/core/reflect/ReflectionInstantiator.java b/src/main/java/net/helenus/core/reflect/ReflectionInstantiator.java similarity index 79% rename from src/main/java/com/noorq/casser/core/reflect/ReflectionInstantiator.java rename to src/main/java/net/helenus/core/reflect/ReflectionInstantiator.java index d108c00..ee4d24c 100644 --- a/src/main/java/com/noorq/casser/core/reflect/ReflectionInstantiator.java +++ b/src/main/java/net/helenus/core/reflect/ReflectionInstantiator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.support.HelenusMappingException; public final class ReflectionInstantiator { @@ -23,13 +23,13 @@ public final class ReflectionInstantiator { } public static T instantiateClass(Class clazz) { - + try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { - throw new CasserMappingException("invalid class " + clazz, e); + throw new HelenusMappingException("invalid class " + clazz, e); } - + } - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/ReflectionMapperInstantiator.java b/src/main/java/net/helenus/core/reflect/ReflectionMapperInstantiator.java similarity index 71% rename from src/main/java/com/noorq/casser/core/reflect/ReflectionMapperInstantiator.java rename to src/main/java/net/helenus/core/reflect/ReflectionMapperInstantiator.java index 5d73ee7..7393a45 100644 --- a/src/main/java/com/noorq/casser/core/reflect/ReflectionMapperInstantiator.java +++ b/src/main/java/net/helenus/core/reflect/ReflectionMapperInstantiator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.lang.reflect.Proxy; import java.util.Map; -import com.noorq.casser.core.MapperInstantiator; +import net.helenus.core.MapperInstantiator; public enum ReflectionMapperInstantiator implements MapperInstantiator { @@ -26,18 +26,12 @@ public enum ReflectionMapperInstantiator implements MapperInstantiator { @Override @SuppressWarnings("unchecked") - public E instantiate(Class iface, Map src, - ClassLoader classLoader) { + public E instantiate(Class iface, Map src, ClassLoader classLoader) { MapperInvocationHandler handler = new MapperInvocationHandler(iface, src); - E proxy = (E) Proxy.newProxyInstance( - classLoader, - new Class[] { iface, MapExportable.class }, - handler); + E proxy = (E) Proxy.newProxyInstance(classLoader, new Class[]{iface, MapExportable.class}, handler); return proxy; } - - - + } diff --git a/src/main/java/com/noorq/casser/core/reflect/SetDsl.java b/src/main/java/net/helenus/core/reflect/SetDsl.java similarity index 85% rename from src/main/java/com/noorq/casser/core/reflect/SetDsl.java rename to src/main/java/net/helenus/core/reflect/SetDsl.java index b5bb877..663b945 100644 --- a/src/main/java/com/noorq/casser/core/reflect/SetDsl.java +++ b/src/main/java/net/helenus/core/reflect/SetDsl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.core.reflect; +package net.helenus.core.reflect; import java.util.Collection; import java.util.Iterator; import java.util.Set; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.support.HelenusMappingException; public final class SetDsl implements Set { - private final CasserPropertyNode parent; - - public SetDsl(CasserPropertyNode parent) { + private final HelenusPropertyNode parent; + + public SetDsl(HelenusPropertyNode parent) { this.parent = parent; } - public CasserPropertyNode getParent() { + public HelenusPropertyNode getParent() { return parent; } - + @Override public int size() { throwShouldNeverCall(); @@ -109,9 +109,9 @@ public final class SetDsl implements Set { public void clear() { throwShouldNeverCall(); } - + private void throwShouldNeverCall() { - throw new CasserMappingException("should be never called"); + throw new HelenusMappingException("should be never called"); } @Override diff --git a/src/main/java/com/noorq/casser/mapping/ColumnInformation.java b/src/main/java/net/helenus/mapping/ColumnInformation.java similarity index 84% rename from src/main/java/com/noorq/casser/mapping/ColumnInformation.java rename to src/main/java/net/helenus/mapping/ColumnInformation.java index f178b05..b6dead1 100644 --- a/src/main/java/com/noorq/casser/mapping/ColumnInformation.java +++ b/src/main/java/net/helenus/mapping/ColumnInformation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.lang.reflect.Method; -import com.noorq.casser.mapping.annotation.ClusteringColumn; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.StaticColumn; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.mapping.annotation.ClusteringColumn; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.StaticColumn; +import net.helenus.support.HelenusMappingException; public final class ColumnInformation { @@ -29,7 +29,7 @@ public final class ColumnInformation { private final ColumnType columnType; private final int ordinal; private final OrderingDirection ordering; - + public ColumnInformation(Method getter) { String columnName = null; @@ -37,18 +37,16 @@ public final class ColumnInformation { ColumnType columnTypeLocal = ColumnType.COLUMN; int ordinalLocal = 0; OrderingDirection orderingLocal = OrderingDirection.ASC; - + PartitionKey partitionKey = getter.getDeclaredAnnotation(PartitionKey.class); - if (partitionKey != null) { columnName = partitionKey.value(); forceQuote = partitionKey.forceQuote(); columnTypeLocal = ColumnType.PARTITION_KEY; ordinalLocal = partitionKey.ordinal(); } - + ClusteringColumn clusteringColumn = getter.getDeclaredAnnotation(ClusteringColumn.class); - if (clusteringColumn != null) { ensureSingleColumnType(columnTypeLocal, getter); columnName = clusteringColumn.value(); @@ -66,7 +64,7 @@ public final class ColumnInformation { columnTypeLocal = ColumnType.STATIC_COLUMN; ordinalLocal = staticColumn.ordinal(); } - + Column column = getter.getDeclaredAnnotation(Column.class); if (column != null) { ensureSingleColumnType(columnTypeLocal, getter); @@ -75,17 +73,17 @@ public final class ColumnInformation { columnTypeLocal = ColumnType.COLUMN; ordinalLocal = column.ordinal(); } - + if (columnName == null || columnName.isEmpty()) { columnName = MappingUtil.getDefaultColumnName(getter); } - + this.columnName = new IdentityName(columnName, forceQuote); this.columnType = columnTypeLocal; this.ordinal = ordinalLocal; this.ordering = orderingLocal; } - + public IdentityName getColumnName() { return columnName; } @@ -101,21 +99,19 @@ public final class ColumnInformation { public OrderingDirection getOrdering() { return ordering; } - + private void ensureSingleColumnType(ColumnType columnTypeLocal, Method getter) { - + if (columnTypeLocal != ColumnType.COLUMN) { - throw new CasserMappingException("property can be annotated only by a single column type " + getter); + throw new HelenusMappingException("property can be annotated only by a single column type " + getter); } - + } @Override public String toString() { - return "ColumnInformation [columnName=" + columnName + ", columnType=" - + columnType + ", ordinal=" + ordinal + ", ordering=" - + ordering + "]"; + return "ColumnInformation [columnName=" + columnName + ", columnType=" + columnType + ", ordinal=" + ordinal + + ", ordering=" + ordering + "]"; } - - + } diff --git a/src/main/java/com/noorq/casser/mapping/ColumnType.java b/src/main/java/net/helenus/mapping/ColumnType.java similarity index 89% rename from src/main/java/com/noorq/casser/mapping/ColumnType.java rename to src/main/java/net/helenus/mapping/ColumnType.java index 223988b..e56b079 100644 --- a/src/main/java/com/noorq/casser/mapping/ColumnType.java +++ b/src/main/java/net/helenus/mapping/ColumnType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; public enum ColumnType { PARTITION_KEY, CLUSTERING_COLUMN, STATIC_COLUMN, COLUMN; diff --git a/src/main/java/com/noorq/casser/mapping/CasserEntity.java b/src/main/java/net/helenus/mapping/HelenusEntity.java similarity index 71% rename from src/main/java/com/noorq/casser/mapping/CasserEntity.java rename to src/main/java/net/helenus/mapping/HelenusEntity.java index cec2b5d..a4c258d 100644 --- a/src/main/java/com/noorq/casser/mapping/CasserEntity.java +++ b/src/main/java/net/helenus/mapping/HelenusEntity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.util.Collection; -public interface CasserEntity { +public interface HelenusEntity { + + HelenusEntityType getType(); + + boolean isCacheable(); - CasserEntityType getType(); - Class getMappingInterface(); - + IdentityName getName(); - - Collection getOrderedProperties(); - - CasserProperty getProperty(String name); - + + Collection getOrderedProperties(); + + HelenusProperty getProperty(String name); + } diff --git a/src/main/java/com/noorq/casser/mapping/CasserEntityType.java b/src/main/java/net/helenus/mapping/HelenusEntityType.java similarity index 84% rename from src/main/java/com/noorq/casser/mapping/CasserEntityType.java rename to src/main/java/net/helenus/mapping/HelenusEntityType.java index 8390bd3..4094d63 100644 --- a/src/main/java/com/noorq/casser/mapping/CasserEntityType.java +++ b/src/main/java/net/helenus/mapping/HelenusEntityType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; -public enum CasserEntityType { +public enum HelenusEntityType { TABLE, TUPLE, UDT; } diff --git a/src/main/java/net/helenus/mapping/HelenusMappingEntity.java b/src/main/java/net/helenus/mapping/HelenusMappingEntity.java new file mode 100644 index 0000000..e67539b --- /dev/null +++ b/src/main/java/net/helenus/mapping/HelenusMappingEntity.java @@ -0,0 +1,270 @@ +/* + * + * Copyright (C) 2015 The Helenus Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping; + +import java.lang.reflect.Method; +import java.util.*; + +import com.datastax.driver.core.*; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.TypeToken; +import net.helenus.config.HelenusSettings; +import net.helenus.core.Helenus; +import net.helenus.core.annotation.Cacheable; +import net.helenus.mapping.annotation.*; +import net.helenus.support.HelenusMappingException; + +public final class HelenusMappingEntity implements HelenusEntity { + + private final Class iface; + private final HelenusEntityType type; + private final IdentityName name; + private final boolean cacheable; + private final ImmutableMap methods; + private final ImmutableMap props; + private final ImmutableList orderedProps; + + public HelenusMappingEntity(Class iface, Metadata metadata) { + this(iface, autoDetectType(iface), metadata); + } + + public HelenusMappingEntity(Class iface, HelenusEntityType type, Metadata metadata) { + + if (iface == null || !iface.isInterface()) { + throw new IllegalArgumentException("invalid parameter " + iface); + } + + this.iface = iface; + this.type = Objects.requireNonNull(type, "type is empty"); + this.name = resolveName(iface, type); + + HelenusSettings settings = Helenus.settings(); + + + List methods = new ArrayList(); + + methods.addAll(Arrays.asList(iface.getDeclaredMethods())); + for (Class c : iface.getInterfaces()) { + methods.addAll(Arrays.asList(c.getDeclaredMethods())); + } + + List propsLocal = new ArrayList(); + ImmutableMap.Builder propsBuilder = ImmutableMap.builder(); + ImmutableMap.Builder methodsBuilder = ImmutableMap.builder(); + + for (Method method : methods) { + + if (settings.getGetterMethodDetector().apply(method)) { + + methodsBuilder.put(method.getName(), method); + + if (metadata != null) { + HelenusProperty prop = new HelenusMappingProperty(this, method, metadata); + + propsBuilder.put(prop.getPropertyName(), prop); + propsLocal.add(prop); + } + + } + + } + + this.methods = methodsBuilder.build(); + this.props = propsBuilder.build(); + + Collections.sort(propsLocal, TypeAndOrdinalColumnComparator.INSTANCE); + this.orderedProps = ImmutableList.copyOf(propsLocal); + + validateOrdinals(); + + cacheable = (null != iface.getDeclaredAnnotation(Cacheable.class)); + } + + @Override + public HelenusEntityType getType() { + return type; + } + + @Override + public boolean isCacheable() { + return cacheable; + } + + @Override + public Class getMappingInterface() { + return iface; + } + + @Override + public Collection getOrderedProperties() { + return orderedProps; + } + + @Override + public HelenusProperty getProperty(String name) { + HelenusProperty property = props.get(name); + if (property == null && methods.containsKey(name)) { + property = new HelenusMappingProperty(this, methods.get(name), new DefaultMetadata()); + return property; //TODO(gburd): review adding these into the props map... + } + return props.get(name); + } + + @Override + public IdentityName getName() { + return name; + } + + private static IdentityName resolveName(Class iface, HelenusEntityType type) { + + switch (type) { + + case TABLE : + return MappingUtil.getTableName(iface, true); + + case TUPLE : + return IdentityName.of(MappingUtil.getDefaultEntityName(iface), false); + + case UDT : + return MappingUtil.getUserDefinedTypeName(iface, true); + } + + throw new HelenusMappingException("invalid entity type " + type + " in " + type); + + } + + private static HelenusEntityType autoDetectType(Class iface) { + + Objects.requireNonNull(iface, "empty iface"); + + if (null != iface.getDeclaredAnnotation(Table.class)) { + return HelenusEntityType.TABLE; + } + + else if (null != iface.getDeclaredAnnotation(Tuple.class)) { + return HelenusEntityType.TUPLE; + } + + else if (null != iface.getDeclaredAnnotation(UDT.class)) { + return HelenusEntityType.UDT; + } + + throw new HelenusMappingException("entity must be annotated by @Table or @Tuple or @UserDefinedType " + iface); + } + + private void validateOrdinals() { + + switch (getType()) { + + case TABLE : + validateOrdinalsForTable(); + break; + + case TUPLE : + validateOrdinalsInTuple(); + break; + + default : + break; + } + + } + + private void validateOrdinalsForTable() { + + BitSet partitionKeys = new BitSet(); + BitSet clusteringColumns = new BitSet(); + + for (HelenusProperty prop : getOrderedProperties()) { + + ColumnType type = prop.getColumnType(); + + int ordinal = prop.getOrdinal(); + + switch (type) { + + case PARTITION_KEY : + if (partitionKeys.get(ordinal)) { + throw new HelenusMappingException( + "detected two or more partition key columns with the same ordinal " + ordinal + " in " + + prop.getEntity()); + } + partitionKeys.set(ordinal); + break; + + case CLUSTERING_COLUMN : + if (clusteringColumns.get(ordinal)) { + throw new HelenusMappingException("detected two or clustering columns with the same ordinal " + + ordinal + " in " + prop.getEntity()); + } + clusteringColumns.set(ordinal); + break; + + default : + break; + } + + } + + } + + private void validateOrdinalsInTuple() { + boolean[] ordinals = new boolean[props.size()]; + + getOrderedProperties().forEach(p -> { + + int ordinal = p.getOrdinal(); + + if (ordinal < 0 || ordinal >= ordinals.length) { + throw new HelenusMappingException("invalid ordinal " + ordinal + " found for property " + + p.getPropertyName() + " in " + p.getEntity()); + } + + if (ordinals[ordinal]) { + throw new HelenusMappingException( + "detected two or more properties with the same ordinal " + ordinal + " in " + p.getEntity()); + } + + ordinals[ordinal] = true; + + }); + + for (int i = 0; i != ordinals.length; ++i) { + if (!ordinals[i]) { + throw new HelenusMappingException("detected absent ordinal " + i + " in " + this); + } + } + + } + + @Override + public String toString() { + + StringBuilder str = new StringBuilder(); + str.append(iface.getSimpleName()).append("(").append(name.getName()).append(") ") + .append(type.name().toLowerCase()).append(":\n"); + + for (HelenusProperty prop : getOrderedProperties()) { + str.append(prop.toString()); + str.append("\n"); + } + return str.toString(); + } + +} diff --git a/src/main/java/com/noorq/casser/mapping/CasserMappingProperty.java b/src/main/java/net/helenus/mapping/HelenusMappingProperty.java similarity index 73% rename from src/main/java/com/noorq/casser/mapping/CasserMappingProperty.java rename to src/main/java/net/helenus/mapping/HelenusMappingProperty.java index b192d15..eb216e2 100644 --- a/src/main/java/com/noorq/casser/mapping/CasserMappingProperty.java +++ b/src/main/java/net/helenus/mapping/HelenusMappingProperty.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -23,51 +23,55 @@ import java.util.function.Function; import javax.validation.ConstraintValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.javatype.AbstractJavaType; -import com.noorq.casser.mapping.javatype.MappingJavaTypes; -import com.noorq.casser.mapping.type.AbstractDataType; +import com.datastax.driver.core.Metadata; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.javatype.AbstractJavaType; +import net.helenus.mapping.javatype.MappingJavaTypes; +import net.helenus.mapping.type.AbstractDataType; -public final class CasserMappingProperty implements CasserProperty { +public final class HelenusMappingProperty implements HelenusProperty { - private final CasserEntity entity; + private final HelenusEntity entity; private final Method getter; - + private final String propertyName; private final Optional indexName; + private final boolean caseSensitiveIndex; private final ColumnInformation columnInfo; - + private final Type genericJavaType; private final Class javaType; private final AbstractJavaType abstractJavaType; private final AbstractDataType dataType; - + private volatile Optional> readConverter = null; private volatile Optional> writeConverter = null; - + private final ConstraintValidator[] validators; - - public CasserMappingProperty(CasserMappingEntity entity, Method getter) { + + public HelenusMappingProperty(HelenusMappingEntity entity, Method getter, Metadata metadata) { this.entity = entity; this.getter = getter; - + this.propertyName = MappingUtil.getPropertyName(getter); this.indexName = MappingUtil.getIndexName(getter); - + this.caseSensitiveIndex = MappingUtil.caseSensitiveIndex(getter); + this.columnInfo = new ColumnInformation(getter); - + this.genericJavaType = getter.getGenericReturnType(); this.javaType = getter.getReturnType(); this.abstractJavaType = MappingJavaTypes.resolveJavaType(this.javaType); - this.dataType = abstractJavaType.resolveDataType(this.getter, this.genericJavaType, this.columnInfo.getColumnType()); - + this.dataType = abstractJavaType.resolveDataType(this.getter, this.genericJavaType, + this.columnInfo.getColumnType(), metadata); + this.validators = MappingUtil.getValidators(getter); } - + @Override - public CasserEntity getEntity() { + public HelenusEntity getEntity() { return entity; } @@ -75,7 +79,7 @@ public final class CasserMappingProperty implements CasserProperty { public Class getJavaType() { return (Class) javaType; } - + @Override public AbstractDataType getDataType() { return dataType; @@ -85,7 +89,7 @@ public final class CasserMappingProperty implements CasserProperty { public ColumnType getColumnType() { return columnInfo.getColumnType(); } - + @Override public int getOrdinal() { return columnInfo.getOrdinal(); @@ -105,7 +109,12 @@ public final class CasserMappingProperty implements CasserProperty { public Optional getIndexName() { return indexName; } - + + @Override + public boolean caseSensitiveIndex() { + return caseSensitiveIndex; + } + @Override public String getPropertyName() { return propertyName; @@ -115,24 +124,24 @@ public final class CasserMappingProperty implements CasserProperty { public Method getGetterMethod() { return getter; } - + @Override public Optional> getReadConverter(SessionRepository repository) { if (readConverter == null) { readConverter = abstractJavaType.resolveReadConverter(this.dataType, repository); } - + return readConverter; } - + @Override public Optional> getWriteConverter(SessionRepository repository) { - + if (writeConverter == null) { writeConverter = abstractJavaType.resolveWriteConverter(this.dataType, repository); } - + return writeConverter; } @@ -143,9 +152,9 @@ public final class CasserMappingProperty implements CasserProperty { @Override public String toString() { - + StringBuilder str = new StringBuilder(); - + String columnName = this.getColumnName().getName(); str.append(" "); str.append(this.getDataType()); @@ -156,43 +165,42 @@ public final class CasserMappingProperty implements CasserProperty { str.append(columnName); } str.append(") "); - + ColumnType type = this.getColumnType(); - - switch(type) { - - case PARTITION_KEY: - str.append("partition_key["); - str.append(this.getOrdinal()); - str.append("] "); - break; - - case CLUSTERING_COLUMN: - str.append("clustering_column["); - str.append(this.getOrdinal()); - str.append("] "); - OrderingDirection od = this.getOrdering(); - if (od != null) { - str.append(od.name().toLowerCase()).append(" "); - } - break; - - case STATIC_COLUMN: - str.append("static "); - break; - - case COLUMN: - break; - + + switch (type) { + + case PARTITION_KEY : + str.append("partition_key["); + str.append(this.getOrdinal()); + str.append("] "); + break; + + case CLUSTERING_COLUMN : + str.append("clustering_column["); + str.append(this.getOrdinal()); + str.append("] "); + OrderingDirection od = this.getOrdering(); + if (od != null) { + str.append(od.name().toLowerCase()).append(" "); + } + break; + + case STATIC_COLUMN : + str.append("static "); + break; + + case COLUMN : + break; + } - + Optional idx = this.getIndexName(); if (idx.isPresent()) { - str.append("index(").append(idx.get().getName()).append(") "); + str.append("index(").append(idx.get().getName()).append(") "); } - + return str.toString(); } - } diff --git a/src/main/java/com/noorq/casser/mapping/CasserProperty.java b/src/main/java/net/helenus/mapping/HelenusProperty.java similarity index 80% rename from src/main/java/com/noorq/casser/mapping/CasserProperty.java rename to src/main/java/net/helenus/mapping/HelenusProperty.java index 774d49b..10a7bea 100644 --- a/src/main/java/com/noorq/casser/mapping/CasserProperty.java +++ b/src/main/java/net/helenus/mapping/HelenusProperty.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -22,35 +22,37 @@ import java.util.function.Function; import javax.validation.ConstraintValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.type.AbstractDataType; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.type.AbstractDataType; -public interface CasserProperty { +public interface HelenusProperty { - CasserEntity getEntity(); + HelenusEntity getEntity(); + + String getPropertyName(); - String getPropertyName(); - Method getGetterMethod(); - + IdentityName getColumnName(); - + Optional getIndexName(); - + + boolean caseSensitiveIndex(); + Class getJavaType(); - + AbstractDataType getDataType(); - + ColumnType getColumnType(); - + int getOrdinal(); - + OrderingDirection getOrdering(); - + Optional> getReadConverter(SessionRepository repository); - + Optional> getWriteConverter(SessionRepository repository); ConstraintValidator[] getValidators(); - + } diff --git a/src/main/java/com/noorq/casser/mapping/IdentityName.java b/src/main/java/net/helenus/mapping/IdentityName.java similarity index 90% rename from src/main/java/com/noorq/casser/mapping/IdentityName.java rename to src/main/java/net/helenus/mapping/IdentityName.java index 1a7d2dd..571f498 100644 --- a/src/main/java/com/noorq/casser/mapping/IdentityName.java +++ b/src/main/java/net/helenus/mapping/IdentityName.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; -import com.noorq.casser.support.CqlUtil; +import net.helenus.support.CqlUtil; public final class IdentityName { private final String name; - + private final boolean forceQuote; - + public IdentityName(String name, boolean forceQuote) { this.name = name.toLowerCase(); this.forceQuote = forceQuote; @@ -31,7 +31,7 @@ public final class IdentityName { public static IdentityName of(String name, boolean forceQuote) { return new IdentityName(name, forceQuote); } - + public String getName() { return name; } @@ -43,12 +43,11 @@ public final class IdentityName { public String toCql(boolean overrideForceQuote) { if (overrideForceQuote) { return CqlUtil.forceQuote(name); - } - else { + } else { return name; } } - + public String toCql() { return toCql(forceQuote); } diff --git a/src/main/java/com/noorq/casser/mapping/MappingUtil.java b/src/main/java/net/helenus/mapping/MappingUtil.java similarity index 68% rename from src/main/java/com/noorq/casser/mapping/MappingUtil.java rename to src/main/java/net/helenus/mapping/MappingUtil.java index bde114c..cbba03d 100644 --- a/src/main/java/com/noorq/casser/mapping/MappingUtil.java +++ b/src/main/java/net/helenus/mapping/MappingUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -24,96 +24,90 @@ import java.util.Optional; import javax.validation.Constraint; import javax.validation.ConstraintValidator; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.core.reflect.DslExportable; -import com.noorq.casser.core.reflect.ListDsl; -import com.noorq.casser.core.reflect.MapDsl; -import com.noorq.casser.core.reflect.MapExportable; -import com.noorq.casser.core.reflect.ReflectionInstantiator; -import com.noorq.casser.core.reflect.SetDsl; -import com.noorq.casser.mapping.annotation.Index; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Tuple; -import com.noorq.casser.mapping.annotation.UDT; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.DslPropertyException; - +import net.helenus.core.Getter; +import net.helenus.core.Helenus; +import net.helenus.core.reflect.*; +import net.helenus.mapping.annotation.Index; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Tuple; +import net.helenus.mapping.annotation.UDT; +import net.helenus.support.DslPropertyException; +import net.helenus.support.HelenusMappingException; public final class MappingUtil { @SuppressWarnings("unchecked") public static final ConstraintValidator[] EMPTY_VALIDATORS = new ConstraintValidator[0]; - + private MappingUtil() { } - + public static ConstraintValidator[] getValidators(Method getterMethod) { List> list = null; - + for (Annotation constraintAnnotation : getterMethod.getDeclaredAnnotations()) { - + list = addValidators(constraintAnnotation, list); - + Class annotationType = constraintAnnotation.annotationType(); - + for (Annotation possibleConstraint : annotationType.getDeclaredAnnotations()) { - + list = addValidators(possibleConstraint, list); - + } - + } - + if (list == null) { return EMPTY_VALIDATORS; - } - else { + } else { return list.toArray(EMPTY_VALIDATORS); } } - - private static List> addValidators(Annotation constraintAnnotation, List> list) { - + + private static List> addValidators(Annotation constraintAnnotation, + List> list) { + Class annotationType = constraintAnnotation.annotationType(); - + for (Annotation possibleConstraint : annotationType.getDeclaredAnnotations()) { - + if (possibleConstraint instanceof Constraint) { - - Constraint constraint = (Constraint) possibleConstraint; - + + Constraint constraint = (Constraint) possibleConstraint; + for (Class> clazz : constraint.validatedBy()) { - ConstraintValidator validator = ReflectionInstantiator.instantiateClass(clazz); - + ConstraintValidator validator = ReflectionInstantiator + .instantiateClass(clazz); + ((ConstraintValidator) validator).initialize(constraintAnnotation); - + if (list == null) { list = new ArrayList>(); } - + list.add(validator); } - + } - + } - + return list; - + } - + public static Optional getIndexName(Method getterMethod) { String indexName = null; boolean forceQuote = false; Index index = getterMethod.getDeclaredAnnotation(Index.class); - + if (index != null) { indexName = index.value(); forceQuote = index.forceQuote(); @@ -127,63 +121,68 @@ public final class MappingUtil { return indexName != null ? Optional.of(new IdentityName(indexName, forceQuote)) : Optional.empty(); } + public static boolean caseSensitiveIndex(Method getterMethod) { + Index index = getterMethod.getDeclaredAnnotation(Index.class); + + if (index != null) { + return index.caseSensitive(); + } + + return false; + } + public static String getPropertyName(Method getter) { return getter.getName(); } public static String getDefaultColumnName(Method getter) { - return Casser.settings().getPropertyToColumnConverter() - .apply(getPropertyName(getter)); + return Helenus.settings().getPropertyToColumnConverter().apply(getPropertyName(getter)); } public static IdentityName getUserDefinedTypeName(Class iface, boolean required) { String userTypeName = null; boolean forceQuote = false; - - UDT userDefinedType = iface - .getDeclaredAnnotation(UDT.class); + + UDT userDefinedType = iface.getDeclaredAnnotation(UDT.class); if (userDefinedType != null) { - + userTypeName = userDefinedType.value(); forceQuote = userDefinedType.forceQuote(); - + if (userTypeName == null || userTypeName.isEmpty()) { userTypeName = getDefaultEntityName(iface); } - + return new IdentityName(userTypeName, forceQuote); - } - + } + if (required) { - throw new CasserMappingException( - "entity must have annotation @UserDefinedType " + iface); + throw new HelenusMappingException("entity must have annotation @UserDefinedType " + iface); } return null; } - + public static boolean isTuple(Class iface) { - - Tuple tuple = iface - .getDeclaredAnnotation(Tuple.class); - + + Tuple tuple = iface.getDeclaredAnnotation(Tuple.class); + return tuple != null; - + } public static boolean isUDT(Class iface) { - - UDT udt = iface - .getDeclaredAnnotation(UDT.class); - + + UDT udt = iface.getDeclaredAnnotation(UDT.class); + return udt != null; - + } - + public static IdentityName getTableName(Class iface, boolean required) { String tableName = null; @@ -196,8 +195,7 @@ public final class MappingUtil { forceQuote = table.forceQuote(); } else if (required) { - throw new CasserMappingException( - "entity must have annotation @Table " + iface); + throw new HelenusMappingException("entity must have annotation @Table " + iface); } if (tableName == null || tableName.isEmpty()) { @@ -208,8 +206,7 @@ public final class MappingUtil { } public static String getDefaultEntityName(Class iface) { - return Casser.settings().getPropertyToColumnConverter() - .apply(iface.getSimpleName()); + return Helenus.settings().getPropertyToColumnConverter().apply(iface.getSimpleName()); } public static Class getMappingInterface(Object pojo) { @@ -220,53 +217,50 @@ public final class MappingUtil { iface = (Class) pojo; if (!iface.isInterface()) { - throw new CasserMappingException("expected interface " + iface); + throw new HelenusMappingException("expected interface " + iface); } } else { Class[] ifaces = pojo.getClass().getInterfaces(); - + int len = ifaces.length; for (int i = 0; i != len; ++i) { - + iface = ifaces[0]; - + if (MapExportable.class.isAssignableFrom(iface)) { continue; } - - if (iface.getDeclaredAnnotation(Table.class) != null || - iface.getDeclaredAnnotation(UDT.class) != null || - iface.getDeclaredAnnotation(Tuple.class) != null) { - + + if (iface.getDeclaredAnnotation(Table.class) != null || iface.getDeclaredAnnotation(UDT.class) != null + || iface.getDeclaredAnnotation(Tuple.class) != null) { + break; - + } - + } - } if (iface == null) { - throw new CasserMappingException("dsl interface not found for " + pojo); + throw new HelenusMappingException("dsl interface not found for " + pojo); } - + return iface; } - public static CasserPropertyNode resolveMappingProperty( - Getter getter) { + public static HelenusPropertyNode resolveMappingProperty(Getter getter) { try { Object childDsl = getter.get(); - + if (childDsl instanceof DslExportable) { DslExportable e = (DslExportable) childDsl; - return e.getParentDslCasserPropertyNode(); + return e.getParentDslHelenusPropertyNode(); } - + else if (childDsl instanceof MapDsl) { MapDsl mapDsl = (MapDsl) childDsl; return mapDsl.getParent(); @@ -282,14 +276,12 @@ public final class MappingUtil { return setDsl.getParent(); } - throw new CasserMappingException( - "getter must reference to the dsl object " + getter); - + throw new HelenusMappingException("getter must reference to the dsl object " + getter); + } catch (DslPropertyException e) { return e.getPropertyNode(); } } - } diff --git a/src/main/java/com/noorq/casser/mapping/OrderingDirection.java b/src/main/java/net/helenus/mapping/OrderingDirection.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/OrderingDirection.java rename to src/main/java/net/helenus/mapping/OrderingDirection.java index 6f14812..1ce2e16 100644 --- a/src/main/java/com/noorq/casser/mapping/OrderingDirection.java +++ b/src/main/java/net/helenus/mapping/OrderingDirection.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.support.HelenusMappingException; public enum OrderingDirection { @@ -32,10 +32,9 @@ public enum OrderingDirection { public String cql() { return cql; } - - + public static OrderingDirection parseString(String name) { - + if (ASC.cql.equalsIgnoreCase(name)) { return ASC; } @@ -43,8 +42,8 @@ public enum OrderingDirection { else if (DESC.cql.equalsIgnoreCase(name)) { return DESC; } - - throw new CasserMappingException("invalid ordering direction name " + name); + + throw new HelenusMappingException("invalid ordering direction name " + name); } -} \ No newline at end of file +} diff --git a/src/main/java/com/noorq/casser/mapping/TypeAndOrdinalColumnComparator.java b/src/main/java/net/helenus/mapping/TypeAndOrdinalColumnComparator.java similarity index 83% rename from src/main/java/com/noorq/casser/mapping/TypeAndOrdinalColumnComparator.java rename to src/main/java/net/helenus/mapping/TypeAndOrdinalColumnComparator.java index 37aef7f..13c60a1 100644 --- a/src/main/java/com/noorq/casser/mapping/TypeAndOrdinalColumnComparator.java +++ b/src/main/java/net/helenus/mapping/TypeAndOrdinalColumnComparator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping; +package net.helenus.mapping; import java.util.Comparator; -public enum TypeAndOrdinalColumnComparator implements Comparator { +public enum TypeAndOrdinalColumnComparator implements Comparator { INSTANCE; - public int compare(CasserProperty thisVal, CasserProperty anotherVal) { + public int compare(HelenusProperty thisVal, HelenusProperty anotherVal) { int c = Integer.compare(thisVal.getColumnType().ordinal(), anotherVal.getColumnType().ordinal()); - + if (c == 0) { c = Integer.compare(thisVal.getOrdinal(), anotherVal.getOrdinal()); } return c; } - + } diff --git a/src/main/java/net/helenus/mapping/annotation/ClusteringColumn.java b/src/main/java/net/helenus/mapping/annotation/ClusteringColumn.java new file mode 100644 index 0000000..996f50b --- /dev/null +++ b/src/main/java/net/helenus/mapping/annotation/ClusteringColumn.java @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import net.helenus.mapping.OrderingDirection; + +/** + * ClusteringColumn is the family column in legacy Cassandra API + * + * The purpose of this column is have additional dimension in the table. + * Both @PartitionKey and @ClusteringColumn together are parts of the primary + * key of the table. The primary difference between them is that the first one + * is using for routing purposes in order to locate a data node in the cluster, + * otherwise the second one is using inside the node to locate peace of data in + * concrete machine. + * + * ClusteringColumn can be represented as a Key in SortedMap that fully stored + * in a single node. All developers must be careful for selecting fields for + * clustering columns, because all data inside this SortedMap must fit in to one + * node. + * + * ClusteringColumn can have more than one part and the order of parts is + * important. This order defines the way how Cassandra joins the parts and + * influence of data retrieval operations. Each part can have ordering property + * that defines default ascending or descending order of data. In case of two + * and more parts in select queries developer needs to have consisdent order of + * all parts as they defined in table. + * + * For example, first part is ASC ordering, second is also ASC, so Cassandra + * will sort entries like this: a-a a-b b-a b-b In this case we are able run + * queries: ORDER BY first ASC, second ASC ORDER BY first DESC, second DESC + * WHERE first=? ORDER BY second ASC WHERE first=? ORDER BY second DESC WHERE + * first=? AND second=? + * + * But, we can not run queries: ORDER BY first DESC, second ASC ORDER BY first + * ASC, second DESC WHERE second=? ORDER BY first (ASC,DESC) + * + * + */ + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +public @interface ClusteringColumn { + + /** + * Default value is the name of the method normalized to underscore + * + * @return name of the column + */ + + String value() default ""; + + /** + * ClusteringColumn parts must be ordered in the @Table. It is the requirement + * of Cassandra. Cassandra joins all parts to the final clustering key that is + * stored in column family name. Additionally all parts can have some ordering + * (ASC, DESC) that with sequence of parts determines key comparison function, + * so Cassandra storing column family names always in sorted order. + * + * Be default ordinal has 0 value, that's because in most cases @Table have + * single column for ClusteringColumn If you have 2 and more parts of the + * ClusteringColumn, then you need to use ordinal() to define the sequence of + * the parts + * + * @return number that used to sort clustering columns + */ + + int ordinal() default 0; + + /** + * Default order of values in the ClusteringColumn This ordering is using for + * comparison of the clustering column values when Cassandra stores it in the + * sorted order. + * + * Default value is the ascending order + * + * @return ascending order or descending order of clustering column values + */ + + OrderingDirection ordering() default OrderingDirection.ASC; + + /** + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * + * Default value is false, we are quoting only selected names. + * + * @return true if name have to be quoted + */ + + boolean forceQuote() default false; + +} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Column.java b/src/main/java/net/helenus/mapping/annotation/Column.java similarity index 67% rename from src/main/java/com/noorq/casser/mapping/annotation/Column.java rename to src/main/java/net/helenus/mapping/annotation/Column.java index c2bef86..7f3015b 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/Column.java +++ b/src/main/java/net/helenus/mapping/annotation/Column.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,61 +13,58 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** - * Column annotation is used to define additional properties of the column - * in entity mapping interfaces: @Table, @UDT, @Tuple - * + * Column annotation is used to define additional properties of the column in + * entity mapping interfaces: @Table, @UDT, @Tuple + * * Column annotation can be used to override default name of the column or to * setup order of the columns in the mapping - * + * * Usually for @Table and @UDT types it is not important to define order of the - * columns, but in @Tuple mapping it is required, because tuple itself represents the - * sequence of the types with particular order in the table's column - * - * @author Alex Shvid + * columns, but in @Tuple mapping it is required, because tuple itself + * represents the sequence of the types with particular order in the table's + * column + * * */ @Documented @Retention(RetentionPolicy.RUNTIME) -@Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Column { /** - * Default value is the name of the method normalized to underscore - * + * Default value is the name of the method normalized to underscore + * * @return name of the column */ - + String value() default ""; /** * Ordinal will be used for ascending sorting of columns - * - * Default value is 0, because not all mapping entities require all fields to have - * unique ordinals, only @Tuple mapping entity requires all of them to be unique. - * + * + * Default value is 0, because not all mapping entities require all fields to + * have unique ordinals, only @Tuple mapping entity requires all of them to be + * unique. + * * @return number that used to sort columns, usually for @Tuple only */ - + int ordinal() default 0; /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted */ - + boolean forceQuote() default false; } diff --git a/src/main/java/net/helenus/mapping/annotation/Constraints.java b/src/main/java/net/helenus/mapping/annotation/Constraints.java new file mode 100644 index 0000000..7040969 --- /dev/null +++ b/src/main/java/net/helenus/mapping/annotation/Constraints.java @@ -0,0 +1,270 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.annotation; + +import java.lang.annotation.*; + +import javax.validation.Constraint; + +import net.helenus.mapping.validator.*; + +/** + * Constraint annotations are using for data integrity mostly + * for @java.lang.String types. The place of the annotation is the particular + * method in model interface. + * + * All of them does not have effect on selects and data retrieval operations. + * + * Support types: - @NotNull supports any @java.lang.Object type - All + * annotations support @java.lang.String type + * + * + */ + +public final class Constraints { + + private Constraints() { + } + + /** + * NotNull annotation is using to check that value is not null before storing it + * + * Applicable to use in any @java.lang.Object + * + * It does not check on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = NotNullValidator.class) + public @interface NotNull { + + } + + /** + * NotEmpty annotation is using to check that value has text before storing it + * + * Also checks for the null and it is more strict annotation then @NotNull + * + * Can be used for @java.lang.CharSequence, @ByteBuffer and any array + * + * It does not check on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = NotEmptyValidator.class) + public @interface NotEmpty { + + } + + /** + * Email annotation is using to check that value has a valid email before + * storing it + * + * Can be used only for @CharSequence + * + * It does not check on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = EmailValidator.class) + public @interface Email { + + } + + /** + * Number annotation is using to check that all letters in value are digits + * before storing it + * + * Can be used only for @java.lang.CharSequence + * + * It does not check on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = NumberValidator.class) + public @interface Number { + + } + + /** + * Alphabet annotation is using to check that all letters in value are in + * specific alphabet before storing it + * + * Can be used only for @java.lang.CharSequence + * + * It does not check on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = AlphabetValidator.class) + public @interface Alphabet { + + /** + * Defines alphabet that will be used to check value + * + * @return alphabet characters in the string + */ + + String value(); + + } + + /** + * Length annotation is using to ensure that value has exact length before + * storing it + * + * Can be used for @java.lang.CharSequence, @ByteBuffer and any array + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = LengthValidator.class) + public @interface Length { + + int value(); + + } + + /** + * MaxLength annotation is using to ensure that value has length less or equal + * to some threshold before storing it + * + * Can be used for @java.lang.CharSequence, @ByteBuffer and byte[] + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = MaxLengthValidator.class) + public @interface MaxLength { + + int value(); + + } + + /** + * MinLength annotation is using to ensure that value has length greater or + * equal to some threshold before storing it + * + * Can be used for @java.lang.CharSequence, @ByteBuffer and byte[] + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = MinLengthValidator.class) + public @interface MinLength { + + int value(); + + } + + /** + * LowerCase annotation is using to ensure that value is in lower case before + * storing it + * + * Can be used only for @java.lang.CharSequence + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = LowerCaseValidator.class) + public @interface LowerCase { + + } + + /** + * UpperCase annotation is using to ensure that value is in upper case before + * storing it + * + * Can be used only for @java.lang.CharSequence + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = UpperCaseValidator.class) + public @interface UpperCase { + + } + + /** + * Pattern annotation is LowerCase annotation is using to ensure that value is + * upper case before storing it + * + * Can be used only for @java.lang.CharSequence + * + * It does not have effect on selects and data retrieval operations + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Constraint(validatedBy = PatternValidator.class) + public @interface Pattern { + + /** + * User defined regex expression to check match of the value + * + * @return Java regex pattern + */ + + String value(); + + /** + * Regex flags composition + * + * @return Java regex flags + */ + + int flags(); + + } + +} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Index.java b/src/main/java/net/helenus/mapping/annotation/Index.java similarity index 60% rename from src/main/java/com/noorq/casser/mapping/annotation/Index.java rename to src/main/java/net/helenus/mapping/annotation/Index.java index d30282e..e122cba 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/Index.java +++ b/src/main/java/net/helenus/mapping/annotation/Index.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,50 +13,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** - * Index annotation is using under the specific column or method in entity interface with @Table annotation. - * - * The corresponding secondary index will be created in the underline @Table for the specific column. - * - * Currently Cassandra supports only single column index, so this index works only for single column. - * - * Make sure that you are using low cardinality columns for this index, that is the requirement of the Cassandra. - * Low cardinality fields examples: gender, country, age, status and etc - * High cardinality fields examples: id, email, timestamp, UUID and etc - * - * @author Alex Shvid + * Index annotation is using under the specific column or method in entity + * interface with @Table annotation. + * + * The corresponding secondary index will be created in the underline @Table for + * the specific column. + * + * Currently Cassandra supports only single column index, so this index works + * only for single column. + * + * Make sure that you are using low cardinality columns for this index, that is + * the requirement of the Cassandra. Low cardinality fields examples: gender, + * country, age, status and etc High cardinality fields examples: id, email, + * timestamp, UUID and etc + * * */ @Documented @Retention(RetentionPolicy.RUNTIME) -@Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Index { /** * Defined the name of the index. By default will be used the column name. - * + * * @return name of the index */ - + String value() default ""; - + /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted - */ - + */ + boolean forceQuote() default false; + + /** + * Create a case-insensitive index using Cassandra 3.x+ support for SASI indexing. + * + * @return true if the index should ignore case when comparing + */ + + boolean caseSensitive() default true; } diff --git a/src/main/java/net/helenus/mapping/annotation/InheritedTable.java b/src/main/java/net/helenus/mapping/annotation/InheritedTable.java new file mode 100644 index 0000000..ceb4c2c --- /dev/null +++ b/src/main/java/net/helenus/mapping/annotation/InheritedTable.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.annotation; + +import java.lang.annotation.*; + +/** + * Inherited Entity annotation + * + * Inherited Table annotation is used to indicate that the methods should also be mapped + * + */ + +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface InheritedTable { + String value() default ""; +} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/PartitionKey.java b/src/main/java/net/helenus/mapping/annotation/PartitionKey.java similarity index 58% rename from src/main/java/com/noorq/casser/mapping/annotation/PartitionKey.java rename to src/main/java/net/helenus/mapping/annotation/PartitionKey.java index 87797ee..090e99c 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/PartitionKey.java +++ b/src/main/java/net/helenus/mapping/annotation/PartitionKey.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -21,57 +21,58 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * PartitionKey annotation is using to define that particular column is the part of - * partition key in the table. - * - * Partition Key is the routing key. Cassandra is using it to find the primary data node - * in the cluster that holds data. Cassandra combines all parts of the partition key to - * byte array and then calculates hash function by using good distribution algorithm (by default - * MurMur3). After that it uses hash number as a token in the ring to find a virtual - * and then a physical data server. - * - * For @Table mapping entity it is required to have as minimum one PartitionKey column. - * For @UDT and @Tuple mapping entities @PartitionKey annotation is not using. - * - * @author Alex Shvid + * PartitionKey annotation is using to define that particular column is the part + * of partition key in the table. + * + * Partition Key is the routing key. Cassandra is using it to find the primary + * data node in the cluster that holds data. Cassandra combines all parts of the + * partition key to byte array and then calculates hash function by using good + * distribution algorithm (by default MurMur3). After that it uses hash number + * as a token in the ring to find a virtual and then a physical data server. + * + * For @Table mapping entity it is required to have as minimum one PartitionKey + * column. For @UDT and @Tuple mapping entities @PartitionKey annotation is not + * using. + * * */ @Retention(value = RetentionPolicy.RUNTIME) -@Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface PartitionKey { /** - * Default value is the name of the method normalized to underscore - * + * Default value is the name of the method normalized to underscore + * * @return name of the column */ - + String value() default ""; /** - * PartitionKey parts must be ordered in the @Table. It is the requirement of Cassandra. - * That is how the partition key calculation works, column parts will be joined based on some order - * and final hash/token will be calculated. - * - * Be default ordinal has 0 value, that's because in most cases @Table have single column for @PartitionKey - * If you have 2 and more parts of the PartitionKey, then you need to use ordinal() to - * define the sequence of the parts - * + * PartitionKey parts must be ordered in the @Table. It is the requirement of + * Cassandra. That is how the partition key calculation works, column parts will + * be joined based on some order and final hash/token will be calculated. + * + * Be default ordinal has 0 value, that's because in most cases @Table have + * single column for @PartitionKey If you have 2 and more parts of the + * PartitionKey, then you need to use ordinal() to define the sequence of the + * parts + * * @return number that used to sort columns in PartitionKey */ - + int ordinal() default 0; - + /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted */ - + boolean forceQuote() default false; } diff --git a/src/main/java/com/noorq/casser/mapping/annotation/StaticColumn.java b/src/main/java/net/helenus/mapping/annotation/StaticColumn.java similarity index 76% rename from src/main/java/com/noorq/casser/mapping/annotation/StaticColumn.java rename to src/main/java/net/helenus/mapping/annotation/StaticColumn.java index d7b1885..2621bad 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/StaticColumn.java +++ b/src/main/java/net/helenus/mapping/annotation/StaticColumn.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -22,45 +22,46 @@ import java.lang.annotation.Target; /** * StaticColumn annotation is using to define a static column in Cassandra Table - * - * It does not have effect in @UDT and @Tuple types and in @Table-s that does not have @ClusteringColumn-s - * - * In case of using @ClusteringColumn we can repeat some information that is unique for a row. - * For this purpose we can define @StaticColumn annotation, that will create static column in the table - * - * @author Alex Shvid + * + * It does not have effect in @UDT and @Tuple types and in @Table-s that does + * not have @ClusteringColumn-s + * + * In case of using @ClusteringColumn we can repeat some information that is + * unique for a row. For this purpose we can define @StaticColumn annotation, + * that will create static column in the table + * * */ @Retention(value = RetentionPolicy.RUNTIME) -@Target(value = { ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface StaticColumn { /** - * Default value is the name of the method normalized to underscore - * + * Default value is the name of the method normalized to underscore + * * @return name of the column */ - + String value() default ""; - + /** * Ordinal will be used for ascending sorting of static columns - * + * * @return number that used to sort columns in PartitionKey */ - + int ordinal() default 0; /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted */ - + boolean forceQuote() default false; } diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Table.java b/src/main/java/net/helenus/mapping/annotation/Table.java similarity index 65% rename from src/main/java/com/noorq/casser/mapping/annotation/Table.java rename to src/main/java/net/helenus/mapping/annotation/Table.java index 3a27fd3..a4775a1 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/Table.java +++ b/src/main/java/net/helenus/mapping/annotation/Table.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,49 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Entity annotation - * + * * Table annotation is used to define Table mapping to some interface - * - * There are three types of Entity mapping annotations: @Table, @UDT, @Tuple - * - * For each @Table annotated interface Casser will create/update/verify Cassandra Table and some indexes if needed on startup. - * - * @author Alex Shvid + * + * There are three types of Entity mapping annotations: @Table, @UDT, @Tuple + * + * For each @Table annotated interface Helenus will create/update/verify + * Cassandra Table and some indexes if needed on startup. + * * */ @Inherited @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) public @interface Table { /** - * Default value is the SimpleName of the interface normalized to underscore - * + * Default value is the SimpleName of the interface normalized to underscore + * * @return name of the UDT type - */ - + */ + String value() default ""; /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted - */ - + */ + boolean forceQuote() default false; - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/ColumnValuePreparer.java b/src/main/java/net/helenus/mapping/annotation/Transient.java similarity index 61% rename from src/main/java/com/noorq/casser/mapping/value/ColumnValuePreparer.java rename to src/main/java/net/helenus/mapping/annotation/Transient.java index d547b0a..b867b41 100644 --- a/src/main/java/com/noorq/casser/mapping/value/ColumnValuePreparer.java +++ b/src/main/java/net/helenus/mapping/annotation/Transient.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.annotation; -import com.noorq.casser.mapping.CasserProperty; +import java.lang.annotation.*; -public interface ColumnValuePreparer { +/** + * Transient annotation is used to mark properties that are need not be mapped + * to the database. + */ - Object prepareColumnValue(Object source, CasserProperty prop); - +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +public @interface Transient { } diff --git a/src/main/java/com/noorq/casser/mapping/annotation/Tuple.java b/src/main/java/net/helenus/mapping/annotation/Tuple.java similarity index 68% rename from src/main/java/com/noorq/casser/mapping/annotation/Tuple.java rename to src/main/java/net/helenus/mapping/annotation/Tuple.java index fa21b7e..9aceb6e 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/Tuple.java +++ b/src/main/java/net/helenus/mapping/annotation/Tuple.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,32 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Entity annotation - * + * * Tuple annotation is used to define Tuple type mapping to some interface * - * There are three types of Entity mapping annotations: @Table, @UDT, @Tuple - * + * There are three types of Entity mapping annotations: @Table, @UDT, @Tuple + * * Tuple is fully embedded type, it is the sequence of the underline types and - * the order of the sub-types is important, therefore all @Column-s must have ordinal() - * and only @Column annotation supported for underline types - * - * @author Alex Shvid + * the order of the sub-types is important, therefore all @Column-s must have + * ordinal() and only @Column annotation supported for underline types + * * */ @Inherited @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) public @interface Tuple { - + } diff --git a/src/main/java/net/helenus/mapping/annotation/Types.java b/src/main/java/net/helenus/mapping/annotation/Types.java new file mode 100644 index 0000000..3e8e4d7 --- /dev/null +++ b/src/main/java/net/helenus/mapping/annotation/Types.java @@ -0,0 +1,556 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.annotation; + +import java.lang.annotation.*; + +import com.datastax.driver.core.DataType; + +/** + * Types annotations are using for clarification of Cassandra data type for + * particular Java type. + * + * Sometimes it is possible to have for single Java type multiple Cassandra data + * types: - @String can be @DataType.Name.ASCII or @DataType.Name.TEXT + * or @DataType.Name.VARCHAR - @Long can be @DataType.Name.BIGINT + * or @DataType.Name.COUNTER + * + * All those type annotations simplify mapping between Java types and Cassandra + * data types. They are not required, for each Java type there is a default + * Cassandra data type in Helenus, but in some cases you would like to control + * mapping to make sure that the right Cassandra data type is using. + * + * For complex types like collections, UDF and Tuple types all those annotations + * are using to clarify the sub-type(s) or class/UDF names. + * + * Has significant effect on schema operations. + * + * + */ + +public final class Types { + + private Types() { + } + + /** + * Says to use @DataType.Name.ASCII data type in schema Java type is @String + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Ascii { + + } + + /** + * Says to use @DataType.Name.BIGINT data type in schema Java type is @Long + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Bigint { + + } + + /** + * Says to use @DataType.Name.BLOB data type in schema Java type is @ByteBuffer + * or @byte[] Using by default + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Blob { + + } + + /** + * Says to use @DataType.Name.LIST data type in schema with specific sub-type + * Java type is @List + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: prepend, prependAll, setIdx, + * append, appendAll, discard and discardAll in @UpdateOperation + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface List { + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT sub-type in the list, consider @UDTList annotation + * + * @return data type name of the value + */ + + DataType.Name value(); + + } + + /** + * Says to use @DataType.Name.MAP data type in schema with specific sub-types + * Java type is @Map + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: put and putAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Map { + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT key sub-type in the map, consider @UDTKeyMap + * or @UDTMap annotations + * + * @return data type name of the key + */ + + DataType.Name key(); + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT value sub-type in the map, consider @UDTValueMap + * or @UDTMap annotations + * + * @return data type name of the value + */ + + DataType.Name value(); + + } + + /** + * Says to use @DataType.Name.COUNTER type in schema Java type is @Long + * + * For this type there are special operations: increment and decrement + * in @UpdateOperation. You do not need to initialize counter value, it will be + * done automatically by Cassandra. + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Counter { + + } + + /** + * Says to use @DataType.Name.SET data type in schema with specific sub-type + * Java type is @Set + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: add, addAll, remove and removeAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Set { + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT sub-type in the set, consider @UDTSet annotation + * + * @return data type name of the value + */ + + DataType.Name value(); + + } + + /** + * Says to use @DataType.Name.CUSTOM type in schema Java type is @ByteBuffer + * or @byte[] + * + * Uses for custom user types that has special implementation. Helenus does not + * deal with this class directly for now, uses only in serialized form. + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Custom { + + /** + * Class name of the custom user type that is implementation of the type + * + * @return class name of the custom type implementation + */ + + String className(); + + } + + /** + * Says to use @DataType.Name.TEXT type in schema Java type is @String Using by + * default + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Text { + + } + + /** + * Says to use @DataType.Name.TIMESTAMP type in schema Java type is @Date Using + * by default + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Timestamp { + + } + + /** + * Says to use @DataType.Name.TIMEUUID type in schema Java type is @UUID + * or @Date + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Timeuuid { + + } + + /** + * Says to use @DataType.Name.TUPLE type in schema Java type is @TupleValue or + * model interface with @Tuple annotation + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + public @interface Tuple { + + /** + * If Java type is the @TupleValue then this field is required. Any Cassandra + * Tuple is the sequence of Cassandra types. For now Helenus supports only + * simple data types in tuples for @TupleValue Java type + * + * In case if Java type is the model interface with @Tuple annotation then all + * methods in this interface can have Types annotations that can be complex + * types as well. + * + * @return data type name sequence + */ + + DataType.Name[] value() default {}; + + } + + /** + * Says to use @DataType.Name.UDT type in schema Java type is @UDTValue or model + * interface with @UDT annotation + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDT { + + /** + * If Java type is the @UDTValue then this field is required. Any Cassandra UDT + * has name and must be created before this use as a Cassandra Type. + * + * This value is the UDT name of the Cassandra Type that was already created in + * the schema + * + * In case of Java type is the model interface with @UDT annotation then this + * field is not using since model interface defines UserDefinedType with + * specific name + * + * @return UDT name + */ + + String value() default ""; + + /** + * Only used for JavaType @UDTValue + * + * In case if value() method returns reserved word that can not be used as a + * name of UDT then forceQuote will add additional quotes around this name in + * all CQL queries. + * + * Default value is false. + * + * @return true if quotation is needed + */ + + boolean forceQuote() default false; + + } + + /** + * Says to use @DataType.Name.MAP data type in schema with specific UDT sub-type + * as a key and simple sub-type as a value Java type is @Map + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: put and putAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDTKeyMap { + + /** + * Clarification of using the UDT data type as a key sub-type in the collection. + * + * @return annotation of UDT type + */ + + UDT key(); + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT value sub-type in the map, consider @UDTMap + * annotations + * + * @return data type name of the value + */ + + DataType.Name value(); + + } + + /** + * Says to use @DataType.Name.LIST data type in schema with specific UDT + * sub-type Java type is @List + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: prepend, prependAll, setIdx, + * append, appendAll, discard and discardAll in @UpdateOperation + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDTList { + + /** + * Clarification of using the UDT data type as a sub-type in the collection. + * + * @return annotation of the UDT value + */ + + UDT value(); + + } + + /** + * Says to use @DataType.Name.MAP data type in schema with specific UDT + * sub-types Java type is @Map + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: put and putAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDTMap { + + /** + * Clarification of using the UDT data type as a key sub-type in the collection. + * + * @return annotation of the UDT key + */ + + UDT key(); + + /** + * Clarification of using the UDT data type as a value sub-type in the + * collection. + * + * @return annotation of the UDT value + */ + + UDT value(); + + } + + /** + * Says to use @DataType.Name.SET data type in schema with specific UDT sub-type + * Java type is @Set + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: add, addAll, remove and removeAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDTSet { + + /** + * Clarification of using the UDT data type as a sub-type in the collection. + * + * @return annotation of the UDT value + */ + + UDT value(); + + } + + /** + * Says to use @DataType.Name.MAP data type in schema with specific simple + * sub-type as a key and UDT sub-type as a value Java type is @Map + * + * Helenus does not allow to use a specific implementation of the collection + * thereof data retrieval operation result can be a collection with another + * implementation. + * + * This annotation is usually used only for sub-types clarification and only in + * case if sub-type is Java type that corresponds to multiple Cassandra data + * types. + * + * For this type there are special operations: put and putAll + * in @UpdateOperation. + * + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface UDTValueMap { + + /** + * Clarification of using the sub-type data type in the collection. It supports + * only simple data type (not Collection, UDT or Tuple) + * + * In case if you need UDT key sub-type in the map, consider @UDTMap annotations + * + * @return data type name of the key + */ + + DataType.Name key(); + + /** + * Clarification of using the UDT data type as a value sub-type in the + * collection. + * + * @return annotation of the UDT value + */ + + UDT value(); + + } + + /** + * Says to use @DataType.Name.UUID type in schema Java type is @UUID Using by + * default + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Uuid { + + } + + /** + * Says to use @DataType.Name.VARCHAR type in schema Java type is @String + */ + + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface Varchar { + + } + +} diff --git a/src/main/java/com/noorq/casser/mapping/annotation/UDT.java b/src/main/java/net/helenus/mapping/annotation/UDT.java similarity index 67% rename from src/main/java/com/noorq/casser/mapping/annotation/UDT.java rename to src/main/java/net/helenus/mapping/annotation/UDT.java index 926d428..42a03fc 100644 --- a/src/main/java/com/noorq/casser/mapping/annotation/UDT.java +++ b/src/main/java/net/helenus/mapping/annotation/UDT.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,48 +13,43 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.annotation; +package net.helenus.mapping.annotation; /** * Entity annotation - * + * * UDT annotation is used to define the UDT (User Defined Type) mapping for some interface - * + * * There are three types of Entity mapping annotations: @Table, @UDT, @Tuple - * - * For each annotated @UDT type Casser will create/update/verify Cassandra Type on startup - * - * @author Alex Shvid + * + * For each annotated @UDT type Helenus will create/update/verify Cassandra Type on startup + * */ -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Inherited @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) public @interface UDT { /** - * Default value is the SimpleName of the interface normalized to underscore - * + * Default value is the SimpleName of the interface normalized to underscore + * * @return name of the UDT type */ - + String value() default ""; /** - * For reserved words in Cassandra we need quotation in CQL queries. This property marks that - * the name of the UDT type needs to be quoted. - * + * For reserved words in Cassandra we need quotation in CQL queries. This + * property marks that the name of the UDT type needs to be quoted. + * * Default value is false, we are quoting only selected names. - * + * * @return true if name have to be quoted */ - + boolean forceQuote() default false; - + } diff --git a/src/main/java/com/noorq/casser/mapping/convert/AbstractEntityValueWriter.java b/src/main/java/net/helenus/mapping/convert/AbstractEntityValueWriter.java similarity index 65% rename from src/main/java/com/noorq/casser/mapping/convert/AbstractEntityValueWriter.java rename to src/main/java/net/helenus/mapping/convert/AbstractEntityValueWriter.java index a7c3e6a..7db2ada 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/AbstractEntityValueWriter.java +++ b/src/main/java/net/helenus/mapping/convert/AbstractEntityValueWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,69 +13,66 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.Map; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.reflect.MapExportable; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.value.BeanColumnValueProvider; +import net.helenus.core.Helenus; +import net.helenus.core.reflect.MapExportable; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.value.BeanColumnValueProvider; public abstract class AbstractEntityValueWriter { - abstract void writeColumn(V outValue, Object value, - CasserProperty prop); + abstract void writeColumn(V outValue, Object value, HelenusProperty prop); + + final HelenusEntity entity; - final CasserEntity entity; - public AbstractEntityValueWriter(Class iface) { - this.entity = Casser.entity(iface); + this.entity = Helenus.entity(iface); } - + public void write(V outValue, Object source) { - + if (source instanceof MapExportable) { - + MapExportable exportable = (MapExportable) source; - + Map propertyToValueMap = exportable.toMap(); - + for (Map.Entry entry : propertyToValueMap.entrySet()) { - + Object value = entry.getValue(); - + if (value == null) { continue; } - - CasserProperty prop = entity.getProperty(entry.getKey()); - - if (prop != null) { - - writeColumn(outValue, value, prop); - - } - - } - - } - else { - for (CasserProperty prop : entity.getOrderedProperties()) { - + HelenusProperty prop = entity.getProperty(entry.getKey()); + + if (prop != null) { + + writeColumn(outValue, value, prop); + + } + + } + + } else { + + for (HelenusProperty prop : entity.getOrderedProperties()) { + Object value = BeanColumnValueProvider.INSTANCE.getColumnValue(source, -1, prop); - + if (value != null) { writeColumn(outValue, value, prop); } - + } - + } } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/ByteArrayToByteBufferConverter.java b/src/main/java/net/helenus/mapping/convert/ByteArrayToByteBufferConverter.java similarity index 87% rename from src/main/java/com/noorq/casser/mapping/convert/ByteArrayToByteBufferConverter.java rename to src/main/java/net/helenus/mapping/convert/ByteArrayToByteBufferConverter.java index ec134a9..5dfef48 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/ByteArrayToByteBufferConverter.java +++ b/src/main/java/net/helenus/mapping/convert/ByteArrayToByteBufferConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.nio.ByteBuffer; import java.util.function.Function; -public enum ByteArrayToByteBufferConverter implements Function{ +public enum ByteArrayToByteBufferConverter implements Function { INSTANCE; @Override public ByteBuffer apply(byte[] t) { - + if (t == null) { return null; } - + return ByteBuffer.wrap(t); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/convert/ByteBufferToByteArrayConverter.java b/src/main/java/net/helenus/mapping/convert/ByteBufferToByteArrayConverter.java similarity index 87% rename from src/main/java/com/noorq/casser/mapping/convert/ByteBufferToByteArrayConverter.java rename to src/main/java/net/helenus/mapping/convert/ByteBufferToByteArrayConverter.java index 9b9fbcf..a88f811 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/ByteBufferToByteArrayConverter.java +++ b/src/main/java/net/helenus/mapping/convert/ByteBufferToByteArrayConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.nio.ByteBuffer; import java.util.function.Function; -public enum ByteBufferToByteArrayConverter implements Function{ +public enum ByteBufferToByteArrayConverter implements Function { INSTANCE; - + @Override public byte[] apply(ByteBuffer t) { - + if (t == null) { return null; } - + return t.array(); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/CamelCaseToUnderscoreConverter.java b/src/main/java/net/helenus/mapping/convert/CamelCaseToUnderscoreConverter.java similarity index 88% rename from src/main/java/com/noorq/casser/mapping/convert/CamelCaseToUnderscoreConverter.java rename to src/main/java/net/helenus/mapping/convert/CamelCaseToUnderscoreConverter.java index 602afe5..d8d8448 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/CamelCaseToUnderscoreConverter.java +++ b/src/main/java/net/helenus/mapping/convert/CamelCaseToUnderscoreConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.function.Function; @@ -25,12 +25,12 @@ public enum CamelCaseToUnderscoreConverter implements Function { @Override public String apply(String source) { - + if (source == null) { throw new IllegalArgumentException("empty parameter"); } - + return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, source); } -} \ No newline at end of file +} diff --git a/src/main/java/com/noorq/casser/mapping/convert/DateToTimeuuidConverter.java b/src/main/java/net/helenus/mapping/convert/DateToTimeuuidConverter.java similarity index 87% rename from src/main/java/com/noorq/casser/mapping/convert/DateToTimeuuidConverter.java rename to src/main/java/net/helenus/mapping/convert/DateToTimeuuidConverter.java index b676846..9885f2b 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/DateToTimeuuidConverter.java +++ b/src/main/java/net/helenus/mapping/convert/DateToTimeuuidConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.Date; import java.util.UUID; import java.util.function.Function; -import com.noorq.casser.support.Timeuuid; +import net.helenus.support.Timeuuid; /** * Simple Date to TimeUUID Converter - * + * */ public enum DateToTimeuuidConverter implements Function { diff --git a/src/main/java/com/noorq/casser/mapping/convert/EnumToStringConverter.java b/src/main/java/net/helenus/mapping/convert/EnumToStringConverter.java similarity index 89% rename from src/main/java/com/noorq/casser/mapping/convert/EnumToStringConverter.java rename to src/main/java/net/helenus/mapping/convert/EnumToStringConverter.java index 2996740..cab94d5 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/EnumToStringConverter.java +++ b/src/main/java/net/helenus/mapping/convert/EnumToStringConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.function.Function; /** * Enum to String Converter - * + * */ public enum EnumToStringConverter implements Function { diff --git a/src/main/java/com/noorq/casser/mapping/convert/ProxyValueReader.java b/src/main/java/net/helenus/mapping/convert/ProxyValueReader.java similarity index 67% rename from src/main/java/com/noorq/casser/mapping/convert/ProxyValueReader.java rename to src/main/java/net/helenus/mapping/convert/ProxyValueReader.java index 49353e0..c0bed94 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/ProxyValueReader.java +++ b/src/main/java/net/helenus/mapping/convert/ProxyValueReader.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,36 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.Map; import java.util.function.Function; -import com.noorq.casser.core.Casser; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.value.ColumnValueProvider; -import com.noorq.casser.mapping.value.ValueProviderMap; +import net.helenus.core.Helenus; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.value.ColumnValueProvider; +import net.helenus.mapping.value.ValueProviderMap; public class ProxyValueReader implements Function { private final Class iface; - private final CasserEntity entity; + private final HelenusEntity entity; private final ColumnValueProvider valueProvider; - + public ProxyValueReader(Class iface, ColumnValueProvider valueProvider) { this.iface = iface; - this.entity = Casser.entity(iface); + this.entity = Helenus.entity(iface); this.valueProvider = valueProvider; } - + @Override public Object apply(T source) { if (source != null) { - Map map = new ValueProviderMap(source, - valueProvider, - entity); - - return Casser.map(iface, map); + Map map = new ValueProviderMap(source, valueProvider, entity); + + return Helenus.map(iface, map); } return null; } diff --git a/src/main/java/com/noorq/casser/mapping/convert/StringToEnumConverter.java b/src/main/java/net/helenus/mapping/convert/StringToEnumConverter.java similarity index 91% rename from src/main/java/com/noorq/casser/mapping/convert/StringToEnumConverter.java rename to src/main/java/net/helenus/mapping/convert/StringToEnumConverter.java index e35ab49..ee64a55 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/StringToEnumConverter.java +++ b/src/main/java/net/helenus/mapping/convert/StringToEnumConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.function.Function; diff --git a/src/main/java/com/noorq/casser/mapping/convert/TimeuuidToDateConverter.java b/src/main/java/net/helenus/mapping/convert/TimeuuidToDateConverter.java similarity index 86% rename from src/main/java/com/noorq/casser/mapping/convert/TimeuuidToDateConverter.java rename to src/main/java/net/helenus/mapping/convert/TimeuuidToDateConverter.java index 64e88f2..25ca901 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/TimeuuidToDateConverter.java +++ b/src/main/java/net/helenus/mapping/convert/TimeuuidToDateConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.Date; import java.util.UUID; import java.util.function.Function; -import com.noorq.casser.support.Timeuuid; +import net.helenus.support.Timeuuid; public enum TimeuuidToDateConverter implements Function { diff --git a/src/main/java/com/noorq/casser/mapping/convert/TupleValueWriter.java b/src/main/java/net/helenus/mapping/convert/TupleValueWriter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/TupleValueWriter.java rename to src/main/java/net/helenus/mapping/convert/TupleValueWriter.java index f2ff664..5840f5f 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/TupleValueWriter.java +++ b/src/main/java/net/helenus/mapping/convert/TupleValueWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.nio.ByteBuffer; import java.util.function.Function; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.value.TupleColumnValuePreparer; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.value.TupleColumnValuePreparer; public class TupleValueWriter extends AbstractEntityValueWriter implements Function { private final TupleType tupleType; private final TupleColumnValuePreparer valuePreparer; - + public TupleValueWriter(Class iface, TupleType tupleType, SessionRepository repository) { super(iface); - + this.tupleType = tupleType; this.valuePreparer = new TupleColumnValuePreparer(tupleType, repository); } @Override - void writeColumn(TupleValue udtValue, Object value, - CasserProperty prop) { - + void writeColumn(TupleValue udtValue, Object value, HelenusProperty prop) { + ByteBuffer bytes = (ByteBuffer) valuePreparer.prepareColumnValue(value, prop); - + if (bytes != null) { udtValue.setBytesUnsafe(prop.getOrdinal(), bytes); } } - + @Override public TupleValue apply(Object source) { if (source != null) { @@ -56,5 +56,5 @@ public class TupleValueWriter extends AbstractEntityValueWriter impl } return null; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/convert/TypedConverter.java b/src/main/java/net/helenus/mapping/convert/TypedConverter.java similarity index 79% rename from src/main/java/com/noorq/casser/mapping/convert/TypedConverter.java rename to src/main/java/net/helenus/mapping/convert/TypedConverter.java index 3416082..6f27118 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/TypedConverter.java +++ b/src/main/java/net/helenus/mapping/convert/TypedConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,51 +13,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.util.function.Function; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.support.HelenusMappingException; public class TypedConverter implements Function { private final Class inputType; private final Class outputType; private final Function delegate; - + public TypedConverter(Class inputType, Class outputType, Function delegate) { this.inputType = inputType; this.outputType = outputType; this.delegate = delegate; } - + public static TypedConverter create(Class inputType, Class outputType, Function delegate) { return new TypedConverter(inputType, outputType, delegate); } - + @Override public Object apply(Object inputUnknown) { - + if (inputUnknown == null) { return null; } - + if (!inputType.isAssignableFrom(inputUnknown.getClass())) { - throw new CasserMappingException("expected " + inputType + " type for input parameter " + inputUnknown.getClass()); + throw new HelenusMappingException( + "expected " + inputType + " type for input parameter " + inputUnknown.getClass()); } - + I input = (I) inputUnknown; - + O outputUnknown = delegate.apply(input); - + if (outputUnknown == null) { return null; } - + if (!outputType.isAssignableFrom(outputUnknown.getClass())) { - throw new CasserMappingException("expected " + outputType + " type for output result " + outputUnknown.getClass()); + throw new HelenusMappingException( + "expected " + outputType + " type for output result " + outputUnknown.getClass()); } - + return outputUnknown; } diff --git a/src/main/java/com/noorq/casser/mapping/convert/UDTValueWriter.java b/src/main/java/net/helenus/mapping/convert/UDTValueWriter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/UDTValueWriter.java rename to src/main/java/net/helenus/mapping/convert/UDTValueWriter.java index 030077d..29ece05 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/UDTValueWriter.java +++ b/src/main/java/net/helenus/mapping/convert/UDTValueWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert; +package net.helenus.mapping.convert; import java.nio.ByteBuffer; import java.util.function.Function; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.value.UDTColumnValuePreparer; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.value.UDTColumnValuePreparer; public class UDTValueWriter extends AbstractEntityValueWriter implements Function { final UserType userType; final UDTColumnValuePreparer valuePreparer; - + public UDTValueWriter(Class iface, UserType userType, SessionRepository repository) { super(iface); - + this.userType = userType; this.valuePreparer = new UDTColumnValuePreparer(userType, repository); } - + @Override - void writeColumn(UDTValue udtValue, Object value, - CasserProperty prop) { - + void writeColumn(UDTValue udtValue, Object value, HelenusProperty prop) { + ByteBuffer bytes = (ByteBuffer) valuePreparer.prepareColumnValue(value, prop); - + if (bytes != null) { udtValue.setBytesUnsafe(prop.getColumnName().getName(), bytes); } } - + @Override public UDTValue apply(Object source) { if (source != null) { @@ -56,5 +56,5 @@ public class UDTValueWriter extends AbstractEntityValueWriter implemen } return null; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/EntityToTupleValueConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/EntityToTupleValueConverter.java similarity index 82% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/EntityToTupleValueConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/EntityToTupleValueConverter.java index f404c81..2ec1ec5 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/EntityToTupleValueConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/EntityToTupleValueConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.function.Function; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; public final class EntityToTupleValueConverter extends TupleValueWriter implements Function { - + public EntityToTupleValueConverter(Class iface, TupleType tupleType, SessionRepository repository) { super(iface, tupleType, repository); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleKeyMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleKeyMapConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleKeyMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/MapToTupleKeyMapConverter.java index 67afda2..59a71f7 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleKeyMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleKeyMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; +import net.helenus.support.Transformers; public final class MapToTupleKeyMapConverter implements Function { final TupleValueWriter writer; - + public MapToTupleKeyMapConverter(Class iface, TupleType tupleType, SessionRepository repository) { this.writer = new TupleValueWriter(iface, tupleType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMapKey((Map) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/MapToTupleMapConverter.java index 8323304..724114c 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; +import net.helenus.support.Transformers; public final class MapToTupleMapConverter implements Function { final TupleValueWriter keyWriter; final TupleValueWriter valueWriter; - - public MapToTupleMapConverter(Class keyClass, TupleType keyType, Class valueClass, TupleType valueType, SessionRepository repository) { + + public MapToTupleMapConverter(Class keyClass, TupleType keyType, Class valueClass, TupleType valueType, + SessionRepository repository) { this.keyWriter = new TupleValueWriter(keyClass, keyType, repository); this.valueWriter = new TupleValueWriter(valueClass, valueType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMap((Map) t, keyWriter, valueWriter); diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleValueMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleValueMapConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleValueMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/MapToTupleValueMapConverter.java index 5844c33..053acfd 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/MapToTupleValueMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/MapToTupleValueMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; +import net.helenus.support.Transformers; public final class MapToTupleValueMapConverter implements Function { final TupleValueWriter writer; - + public MapToTupleValueMapConverter(Class iface, TupleType tupleType, SessionRepository repository) { this.writer = new TupleValueWriter(iface, tupleType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMapValue((Map) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/SetToTupleSetConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/SetToTupleSetConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/SetToTupleSetConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/SetToTupleSetConverter.java index 66a0469..49c5251 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/SetToTupleSetConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/SetToTupleSetConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Set; import java.util.function.Function; import com.datastax.driver.core.TupleType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; +import net.helenus.support.Transformers; public final class SetToTupleSetConverter implements Function { final TupleValueWriter writer; - + public SetToTupleSetConverter(Class iface, TupleType tupleType, SessionRepository repository) { this.writer = new TupleValueWriter(iface, tupleType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformSet((Set) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleKeyMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleKeyMapToMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleKeyMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleKeyMapToMapConverter.java index eef1265..9e439ef 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleKeyMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleKeyMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; +import net.helenus.support.Transformers; public final class TupleKeyMapToMapConverter implements Function { final ProxyValueReader reader; - + public TupleKeyMapToMapConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new TupleColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleListToListConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleListToListConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleListToListConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleListToListConverter.java index 088e052..0cc30ac 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleListToListConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleListToListConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.List; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; +import net.helenus.support.Transformers; public final class TupleListToListConverter implements Function { final ProxyValueReader reader; - + public TupleListToListConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new TupleColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleMapToMapConverter.java similarity index 80% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleMapToMapConverter.java index 4a94744..ee9e838 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; +import net.helenus.support.Transformers; public final class TupleMapToMapConverter implements Function { final ProxyValueReader keyReader; final ProxyValueReader valueReader; - + public TupleMapToMapConverter(Class keyClass, Class valueClass, SessionRepository repository) { this.keyReader = new ProxyValueReader(keyClass, new TupleColumnValueProvider(repository)); this.valueReader = new ProxyValueReader(valueClass, new TupleColumnValueProvider(repository)); diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleSetToSetConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleSetToSetConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleSetToSetConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleSetToSetConverter.java index c186a1e..05d3e47 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleSetToSetConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleSetToSetConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Set; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; +import net.helenus.support.Transformers; public final class TupleSetToSetConverter implements Function { final ProxyValueReader reader; - + public TupleSetToSetConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new TupleColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleValueMapToMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleValueMapToMapConverter.java index 568eafc..8b6229a 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleValueMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; +import net.helenus.support.Transformers; public final class TupleValueMapToMapConverter implements Function { final ProxyValueReader reader; - + public TupleValueMapToMapConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new TupleColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueToEntityConverter.java b/src/main/java/net/helenus/mapping/convert/tuple/TupleValueToEntityConverter.java similarity index 72% rename from src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueToEntityConverter.java rename to src/main/java/net/helenus/mapping/convert/tuple/TupleValueToEntityConverter.java index ae48252..8203b9d 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/tuple/TupleValueToEntityConverter.java +++ b/src/main/java/net/helenus/mapping/convert/tuple/TupleValueToEntityConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.tuple; +package net.helenus.mapping.convert.tuple; import java.util.function.Function; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.TupleColumnValueProvider; -public final class TupleValueToEntityConverter extends ProxyValueReader implements Function { +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.TupleColumnValueProvider; + +public final class TupleValueToEntityConverter extends ProxyValueReader + implements + Function { public TupleValueToEntityConverter(Class iface, SessionRepository repository) { super(iface, new TupleColumnValueProvider(repository)); diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/EntityToUDTValueConverter.java b/src/main/java/net/helenus/mapping/convert/udt/EntityToUDTValueConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/udt/EntityToUDTValueConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/EntityToUDTValueConverter.java index 6af5b42..721f3b5 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/EntityToUDTValueConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/EntityToUDTValueConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; public final class EntityToUDTValueConverter extends UDTValueWriter { diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/ListToUDTListConverter.java b/src/main/java/net/helenus/mapping/convert/udt/ListToUDTListConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/udt/ListToUDTListConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/ListToUDTListConverter.java index 57ec294..06c6ae9 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/ListToUDTListConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/ListToUDTListConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.List; import java.util.function.Function; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; +import net.helenus.support.Transformers; public final class ListToUDTListConverter implements Function { final UDTValueWriter writer; - + public ListToUDTListConverter(Class iface, UserType userType, SessionRepository repository) { this.writer = new UDTValueWriter(iface, userType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformList((List) t, writer); diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTKeyMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTKeyMapConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTKeyMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/MapToUDTKeyMapConverter.java index 6839b05..a1bc555 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTKeyMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTKeyMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; +import net.helenus.support.Transformers; public final class MapToUDTKeyMapConverter implements Function { final UDTValueWriter writer; - + public MapToUDTKeyMapConverter(Class iface, UserType userType, SessionRepository repository) { this.writer = new UDTValueWriter(iface, userType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMapKey((Map) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/MapToUDTMapConverter.java index 9d770b4..3a5ea61 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; +import net.helenus.support.Transformers; public final class MapToUDTMapConverter implements Function { final UDTValueWriter keyWriter; final UDTValueWriter valueWriter; - - public MapToUDTMapConverter(Class keyClass, UserType keyType, Class valueClass, UserType valueType, SessionRepository repository) { + + public MapToUDTMapConverter(Class keyClass, UserType keyType, Class valueClass, UserType valueType, + SessionRepository repository) { this.keyWriter = new UDTValueWriter(keyClass, keyType, repository); this.valueWriter = new UDTValueWriter(valueClass, valueType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMap((Map) t, keyWriter, valueWriter); diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTValueMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTValueMapConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTValueMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/MapToUDTValueMapConverter.java index 02c4dc4..8b43e13 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/MapToUDTValueMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/MapToUDTValueMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; +import net.helenus.support.Transformers; public final class MapToUDTValueMapConverter implements Function { final UDTValueWriter writer; - + public MapToUDTValueMapConverter(Class iface, UserType userType, SessionRepository repository) { this.writer = new UDTValueWriter(iface, userType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformMapValue((Map) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/SetToUDTSetConverter.java b/src/main/java/net/helenus/mapping/convert/udt/SetToUDTSetConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/convert/udt/SetToUDTSetConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/SetToUDTSetConverter.java index 445e799..f9dbd30 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/SetToUDTSetConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/SetToUDTSetConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Set; import java.util.function.Function; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.UDTValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.UDTValueWriter; +import net.helenus.support.Transformers; public final class SetToUDTSetConverter implements Function { final UDTValueWriter writer; - + public SetToUDTSetConverter(Class iface, UserType userType, SessionRepository repository) { this.writer = new UDTValueWriter(iface, userType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformSet((Set) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTKeyMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTKeyMapToMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTKeyMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTKeyMapToMapConverter.java index 0d54c58..6747ea9 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTKeyMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTKeyMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; +import net.helenus.support.Transformers; public final class UDTKeyMapToMapConverter implements Function { final ProxyValueReader reader; - + public UDTKeyMapToMapConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new UDTColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTListToListConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTListToListConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTListToListConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTListToListConverter.java index 65b3063..09bf19e 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTListToListConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTListToListConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.List; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; +import net.helenus.support.Transformers; public final class UDTListToListConverter implements Function { final ProxyValueReader reader; - + public UDTListToListConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new UDTColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTMapToMapConverter.java similarity index 80% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTMapToMapConverter.java index ca1c213..1f72fbb 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; +import net.helenus.support.Transformers; public final class UDTMapToMapConverter implements Function { final ProxyValueReader keyReader; final ProxyValueReader valueReader; - + public UDTMapToMapConverter(Class keyClass, Class valueClass, SessionRepository repository) { this.keyReader = new ProxyValueReader(keyClass, new UDTColumnValueProvider(repository)); this.valueReader = new ProxyValueReader(valueClass, new UDTColumnValueProvider(repository)); diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTSetToSetConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTSetToSetConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTSetToSetConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTSetToSetConverter.java index 9472f0b..043811d 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTSetToSetConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTSetToSetConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Set; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; +import net.helenus.support.Transformers; public final class UDTSetToSetConverter implements Function { final ProxyValueReader reader; - + public UDTSetToSetConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new UDTColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueMapToMapConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTValueMapToMapConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueMapToMapConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTValueMapToMapConverter.java index a8bee77..2ab5e83 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueMapToMapConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTValueMapToMapConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.Map; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; +import net.helenus.support.Transformers; public final class UDTValueMapToMapConverter implements Function { final ProxyValueReader reader; - + public UDTValueMapToMapConverter(Class iface, SessionRepository repository) { this.reader = new ProxyValueReader(iface, new UDTColumnValueProvider(repository)); } diff --git a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueToEntityConverter.java b/src/main/java/net/helenus/mapping/convert/udt/UDTValueToEntityConverter.java similarity index 78% rename from src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueToEntityConverter.java rename to src/main/java/net/helenus/mapping/convert/udt/UDTValueToEntityConverter.java index 826a095..544274a 100644 --- a/src/main/java/com/noorq/casser/mapping/convert/udt/UDTValueToEntityConverter.java +++ b/src/main/java/net/helenus/mapping/convert/udt/UDTValueToEntityConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.convert.udt; +package net.helenus.mapping.convert.udt; import java.util.function.Function; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.ProxyValueReader; -import com.noorq.casser.mapping.value.UDTColumnValueProvider; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.ProxyValueReader; +import net.helenus.mapping.value.UDTColumnValueProvider; public final class UDTValueToEntityConverter extends ProxyValueReader implements Function { diff --git a/src/main/java/com/noorq/casser/mapping/javatype/AbstractJavaType.java b/src/main/java/net/helenus/mapping/javatype/AbstractJavaType.java similarity index 77% rename from src/main/java/com/noorq/casser/mapping/javatype/AbstractJavaType.java rename to src/main/java/net/helenus/mapping/javatype/AbstractJavaType.java index cc41e32..cf7aa08 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/AbstractJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/AbstractJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; @@ -22,24 +22,26 @@ import java.util.Optional; import java.util.function.Function; import com.datastax.driver.core.DataType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Either; + +import com.datastax.driver.core.Metadata; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.support.Either; +import net.helenus.support.HelenusMappingException; public abstract class AbstractJavaType { public abstract Class getJavaClass(); - + public boolean isApplicable(Class javaClass) { return false; } - - public abstract AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType); + + public abstract AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata); public Optional> getPrimitiveJavaClass() { return Optional.empty(); @@ -54,27 +56,27 @@ public abstract class AbstractJavaType { SessionRepository repository) { return Optional.empty(); } - + static IdentityName resolveUDT(Types.UDT annotation) { return IdentityName.of(annotation.value(), annotation.forceQuote()); } - + static DataType resolveSimpleType(Method getter, DataType.Name typeName) { DataType dataType = SimpleJavaTypes.getDataTypeByName(typeName); if (dataType == null) { - throw new CasserMappingException( + throw new HelenusMappingException( "only primitive types are allowed inside collections for the property " + getter); } return dataType; } - + static void ensureTypeArguments(Method getter, int args, int expected) { if (args != expected) { - throw new CasserMappingException("expected " + expected + " of typed arguments for the property " - + getter); + throw new HelenusMappingException( + "expected " + expected + " of typed arguments for the property " + getter); } } - + static class DataTypeInfo { final DataType dataType; final Class typeArgument; @@ -83,53 +85,53 @@ public abstract class AbstractJavaType { this.dataType = dataType; this.typeArgument = null; } - + DataTypeInfo(DataType dataType, Class typeArgument) { this.dataType = dataType; this.typeArgument = typeArgument; } } - - static Either autodetectParameterType(Method getter, Type type) { - + + static Either autodetectParameterType(Method getter, Type type, Metadata metadata) { + DataType dataType = null; - + if (type instanceof Class) { - + Class javaType = (Class) type; dataType = SimpleJavaTypes.getDataTypeByJavaClass(javaType); if (dataType != null) { return Either.left(dataType); } - + if (MappingUtil.isTuple(javaType)) { - dataType = TupleValueJavaType.toTupleType(javaType); + dataType = TupleValueJavaType.toTupleType(javaType, metadata); return Either.left(dataType); } - + IdentityName udtName = MappingUtil.getUserDefinedTypeName(javaType, false); - + if (udtName != null) { return Either.right(udtName); } } - throw new CasserMappingException( - "unknown parameter type " + type + " in the collection for the property " + getter); + throw new HelenusMappingException( + "unknown parameter type " + type + " in the collection for the property " + getter); } - + static Type[] getTypeParameters(Type genericJavaType) { - + if (genericJavaType instanceof ParameterizedType) { - + ParameterizedType type = (ParameterizedType) genericJavaType; - + return type.getActualTypeArguments(); } - - return new Type[] {}; + + return new Type[]{}; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/ByteArrayJavaType.java b/src/main/java/net/helenus/mapping/javatype/ByteArrayJavaType.java similarity index 55% rename from src/main/java/com/noorq/casser/mapping/javatype/ByteArrayJavaType.java rename to src/main/java/net/helenus/mapping/javatype/ByteArrayJavaType.java index c4322f0..4254294 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/ByteArrayJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/ByteArrayJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -22,14 +22,16 @@ import java.util.Optional; import java.util.function.Function; import com.datastax.driver.core.DataType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.ByteArrayToByteBufferConverter; -import com.noorq.casser.mapping.convert.ByteBufferToByteArrayConverter; -import com.noorq.casser.mapping.convert.TypedConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.ByteArrayToByteBufferConverter; +import net.helenus.mapping.convert.ByteBufferToByteArrayConverter; +import net.helenus.mapping.convert.TypedConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class ByteArrayJavaType extends AbstractJavaType { @@ -39,42 +41,36 @@ public final class ByteArrayJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Blob.class)) { - return new DTDataType(columnType, DataType.blob()); + return new DTDataType(columnType, DataType.blob()); } Types.Custom custom = getter.getDeclaredAnnotation(Types.Custom.class); - + if (null != custom) { - return new DTDataType(columnType, DataType.custom(custom.className())); + return new DTDataType(columnType, DataType.custom(custom.className())); } return new DTDataType(columnType, DataType.blob()); } @Override - public Optional> resolveReadConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveReadConverter(AbstractDataType dataType, + SessionRepository repository) { + + return Optional + .of(TypedConverter.create(ByteBuffer.class, byte[].class, ByteBufferToByteArrayConverter.INSTANCE)); - return Optional.of(TypedConverter.create( - ByteBuffer.class, - byte[].class, - ByteBufferToByteArrayConverter.INSTANCE)); - } @Override - public Optional> resolveWriteConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType dataType, + SessionRepository repository) { - return Optional.of(TypedConverter.create( - byte[].class, - ByteBuffer.class, - ByteArrayToByteBufferConverter.INSTANCE)); + return Optional + .of(TypedConverter.create(byte[].class, ByteBuffer.class, ByteArrayToByteBufferConverter.INSTANCE)); } - - - + } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/ByteBufferJavaType.java b/src/main/java/net/helenus/mapping/javatype/ByteBufferJavaType.java similarity index 70% rename from src/main/java/com/noorq/casser/mapping/javatype/ByteBufferJavaType.java rename to src/main/java/net/helenus/mapping/javatype/ByteBufferJavaType.java index 7c12763..198357d 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/ByteBufferJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/ByteBufferJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.nio.ByteBuffer; import com.datastax.driver.core.DataType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class ByteBufferJavaType extends AbstractJavaType { @@ -33,19 +35,19 @@ public final class ByteBufferJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Blob.class)) { - return new DTDataType(columnType, DataType.blob()); + return new DTDataType(columnType, DataType.blob()); } Types.Custom custom = getter.getDeclaredAnnotation(Types.Custom.class); - + if (null != custom) { - return new DTDataType(columnType, DataType.custom(custom.className())); + return new DTDataType(columnType, DataType.custom(custom.className())); } return new DTDataType(columnType, DataType.blob()); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/DateJavaType.java b/src/main/java/net/helenus/mapping/javatype/DateJavaType.java similarity index 60% rename from src/main/java/com/noorq/casser/mapping/javatype/DateJavaType.java rename to src/main/java/net/helenus/mapping/javatype/DateJavaType.java index 1250b94..cdc008a 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/DateJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/DateJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -23,14 +23,16 @@ import java.util.UUID; import java.util.function.Function; import com.datastax.driver.core.DataType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.DateToTimeuuidConverter; -import com.noorq.casser.mapping.convert.TimeuuidToDateConverter; -import com.noorq.casser.mapping.convert.TypedConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.DateToTimeuuidConverter; +import net.helenus.mapping.convert.TimeuuidToDateConverter; +import net.helenus.mapping.convert.TypedConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class DateJavaType extends AbstractJavaType { @@ -40,52 +42,44 @@ public final class DateJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Timestamp.class)) { - return new DTDataType(columnType, DataType.timestamp()); + return new DTDataType(columnType, DataType.timestamp()); } if (null != getter.getDeclaredAnnotation(Types.Timeuuid.class)) { - return new DTDataType(columnType, DataType.timeuuid()); + return new DTDataType(columnType, DataType.timeuuid()); } return new DTDataType(columnType, DataType.timestamp()); } @Override - public Optional> resolveReadConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveReadConverter(AbstractDataType dataType, + SessionRepository repository) { DataType dt = ((DTDataType) dataType).getDataType(); - + if (dt.getName() == DataType.Name.TIMEUUID) { - return Optional.of(TypedConverter.create( - UUID.class, - Date.class, - TimeuuidToDateConverter.INSTANCE)); + return Optional.of(TypedConverter.create(UUID.class, Date.class, TimeuuidToDateConverter.INSTANCE)); } - + return Optional.empty(); } @Override - public Optional> resolveWriteConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType dataType, + SessionRepository repository) { DataType dt = ((DTDataType) dataType).getDataType(); - + if (dt.getName() == DataType.Name.TIMEUUID) { - return Optional.of(TypedConverter.create( - Date.class, - UUID.class, - DateToTimeuuidConverter.INSTANCE)); + return Optional.of(TypedConverter.create(Date.class, UUID.class, DateToTimeuuidConverter.INSTANCE)); } - + return Optional.empty(); - + } - - } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/EnumJavaType.java b/src/main/java/net/helenus/mapping/javatype/EnumJavaType.java similarity index 58% rename from src/main/java/com/noorq/casser/mapping/javatype/EnumJavaType.java rename to src/main/java/net/helenus/mapping/javatype/EnumJavaType.java index d88f352..65720d2 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/EnumJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/EnumJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -21,13 +21,15 @@ import java.util.Optional; import java.util.function.Function; import com.datastax.driver.core.DataType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.convert.EnumToStringConverter; -import com.noorq.casser.mapping.convert.StringToEnumConverter; -import com.noorq.casser.mapping.convert.TypedConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.convert.EnumToStringConverter; +import net.helenus.mapping.convert.StringToEnumConverter; +import net.helenus.mapping.convert.TypedConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class EnumJavaType extends AbstractJavaType { @@ -37,31 +39,26 @@ public final class EnumJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.ascii(), (Class) genericJavaType); } @Override - public Optional> resolveReadConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveReadConverter(AbstractDataType dataType, + SessionRepository repository) { DTDataType dt = (DTDataType) dataType; - - return Optional.of(TypedConverter.create( - String.class, - Enum.class, - new StringToEnumConverter(dt.getJavaClass()))); + + return Optional + .of(TypedConverter.create(String.class, Enum.class, new StringToEnumConverter(dt.getJavaClass()))); } @Override - public Optional> resolveWriteConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType dataType, + SessionRepository repository) { + + return Optional.of(TypedConverter.create(Enum.class, String.class, EnumToStringConverter.INSTANCE)); - return Optional.of(TypedConverter.create( - Enum.class, - String.class, - EnumToStringConverter.INSTANCE)); - } } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/ListJavaType.java b/src/main/java/net/helenus/mapping/javatype/ListJavaType.java similarity index 65% rename from src/main/java/com/noorq/casser/mapping/javatype/ListJavaType.java rename to src/main/java/net/helenus/mapping/javatype/ListJavaType.java index ecf30f5..ec24a86 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/ListJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/ListJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -21,24 +21,21 @@ import java.util.List; import java.util.Optional; import java.util.function.Function; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TupleType; -import com.datastax.driver.core.TupleValue; -import com.datastax.driver.core.UDTValue; -import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.tuple.TupleListToListConverter; -import com.noorq.casser.mapping.convert.udt.ListToUDTListConverter; -import com.noorq.casser.mapping.convert.udt.UDTListToListConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.mapping.type.ListToTupleListConverter; -import com.noorq.casser.mapping.type.UDTListDataType; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Either; +import com.datastax.driver.core.*; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.tuple.TupleListToListConverter; +import net.helenus.mapping.convert.udt.ListToUDTListConverter; +import net.helenus.mapping.convert.udt.UDTListToListConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.mapping.type.ListToTupleListConverter; +import net.helenus.mapping.type.UDTListDataType; +import net.helenus.support.Either; +import net.helenus.support.HelenusMappingException; public final class ListJavaType extends AbstractJavaType { @@ -48,116 +45,111 @@ public final class ListJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { Types.List clist = getter.getDeclaredAnnotation(Types.List.class); if (clist != null) { - return new DTDataType(columnType, - DataType.list(resolveSimpleType(getter, clist.value()))); + return new DTDataType(columnType, DataType.list(resolveSimpleType(getter, clist.value()))); } Types.UDTList udtList = getter.getDeclaredAnnotation(Types.UDTList.class); if (udtList != null) { - return new UDTListDataType(columnType, - resolveUDT(udtList.value()), - UDTValue.class); + return new UDTListDataType(columnType, resolveUDT(udtList.value()), UDTValue.class); } Type[] args = getTypeParameters(genericJavaType); ensureTypeArguments(getter, args.length, 1); - - Either parameterType = autodetectParameterType(getter, args[0]); + + Either parameterType = autodetectParameterType(getter, args[0], metadata); if (parameterType.isLeft()) { return DTDataType.list(columnType, parameterType.getLeft(), args[0]); + } else { + return new UDTListDataType(columnType, parameterType.getRight(), (Class) args[0]); } - else { - return new UDTListDataType(columnType, - parameterType.getRight(), - (Class) args[0]); - } - + } - + @Override - public Optional> resolveReadConverter( - AbstractDataType abstractDataType, SessionRepository repository) { - + public Optional> resolveReadConverter(AbstractDataType abstractDataType, + SessionRepository repository) { + if (abstractDataType instanceof DTDataType) { - + DTDataType dt = (DTDataType) abstractDataType; DataType elementType = dt.getDataType().getTypeArguments().get(0); if (elementType instanceof TupleType) { - + Class tupleClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(tupleClass)) { return Optional.empty(); } - + return Optional.of(new TupleListToListConverter(tupleClass, repository)); } } - + else if (abstractDataType instanceof UDTListDataType) { - + UDTListDataType dt = (UDTListDataType) abstractDataType; - + Class javaClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } - + return Optional.of(new UDTListToListConverter(javaClass, repository)); - + } - + return Optional.empty(); } @Override - public Optional> resolveWriteConverter( - AbstractDataType abstractDataType, SessionRepository repository) { - + public Optional> resolveWriteConverter(AbstractDataType abstractDataType, + SessionRepository repository) { + if (abstractDataType instanceof DTDataType) { - + DTDataType dt = (DTDataType) abstractDataType; DataType elementType = dt.getDataType().getTypeArguments().get(0); - + if (elementType instanceof TupleType) { - + Class tupleClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(tupleClass)) { return Optional.empty(); } - + return Optional.of(new ListToTupleListConverter(tupleClass, (TupleType) elementType, repository)); } - + } - + else if (abstractDataType instanceof UDTListDataType) { - + UDTListDataType dt = (UDTListDataType) abstractDataType; - + Class javaClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } UserType userType = repository.findUserType(dt.getUdtName().getName()); if (userType == null) { - throw new CasserMappingException("UserType not found for " + dt.getUdtName() + " with type " + javaClass); + throw new HelenusMappingException( + "UserType not found for " + dt.getUdtName() + " with type " + javaClass); } - + return Optional.of(new ListToUDTListConverter(javaClass, userType, repository)); - + } - + return Optional.empty(); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/LongJavaType.java b/src/main/java/net/helenus/mapping/javatype/LongJavaType.java similarity index 71% rename from src/main/java/com/noorq/casser/mapping/javatype/LongJavaType.java rename to src/main/java/net/helenus/mapping/javatype/LongJavaType.java index 511f272..81b4bec 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/LongJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/LongJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Optional; import com.datastax.driver.core.DataType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class LongJavaType extends AbstractJavaType { @@ -31,26 +33,24 @@ public final class LongJavaType extends AbstractJavaType { public Class getJavaClass() { return Long.class; } - + @Override public Optional> getPrimitiveJavaClass() { return Optional.of(long.class); } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Counter.class)) { - return new DTDataType(columnType, DataType.counter()); + return new DTDataType(columnType, DataType.counter()); } if (null != getter.getDeclaredAnnotation(Types.Bigint.class)) { - return new DTDataType(columnType, DataType.bigint()); + return new DTDataType(columnType, DataType.bigint()); } return new DTDataType(columnType, DataType.bigint()); } - - } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/MapJavaType.java b/src/main/java/net/helenus/mapping/javatype/MapJavaType.java similarity index 55% rename from src/main/java/com/noorq/casser/mapping/javatype/MapJavaType.java rename to src/main/java/net/helenus/mapping/javatype/MapJavaType.java index f549959..4333791 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/MapJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/MapJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -21,34 +21,17 @@ import java.util.Map; import java.util.Optional; import java.util.function.Function; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TupleType; -import com.datastax.driver.core.TupleValue; -import com.datastax.driver.core.UDTValue; -import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.tuple.MapToTupleKeyMapConverter; -import com.noorq.casser.mapping.convert.tuple.MapToTupleMapConverter; -import com.noorq.casser.mapping.convert.tuple.MapToTupleValueMapConverter; -import com.noorq.casser.mapping.convert.tuple.TupleKeyMapToMapConverter; -import com.noorq.casser.mapping.convert.tuple.TupleMapToMapConverter; -import com.noorq.casser.mapping.convert.tuple.TupleValueMapToMapConverter; -import com.noorq.casser.mapping.convert.udt.MapToUDTKeyMapConverter; -import com.noorq.casser.mapping.convert.udt.MapToUDTMapConverter; -import com.noorq.casser.mapping.convert.udt.MapToUDTValueMapConverter; -import com.noorq.casser.mapping.convert.udt.UDTKeyMapToMapConverter; -import com.noorq.casser.mapping.convert.udt.UDTMapToMapConverter; -import com.noorq.casser.mapping.convert.udt.UDTValueMapToMapConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.mapping.type.UDTKeyMapDataType; -import com.noorq.casser.mapping.type.UDTMapDataType; -import com.noorq.casser.mapping.type.UDTValueMapDataType; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Either; +import com.datastax.driver.core.*; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.tuple.*; +import net.helenus.mapping.convert.udt.*; +import net.helenus.mapping.type.*; +import net.helenus.support.Either; +import net.helenus.support.HelenusMappingException; public final class MapJavaType extends AbstractJavaType { @@ -58,359 +41,294 @@ public final class MapJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { Types.Map cmap = getter.getDeclaredAnnotation(Types.Map.class); if (cmap != null) { - return new DTDataType(columnType, - DataType.map( - resolveSimpleType(getter, cmap.key()), - resolveSimpleType(getter, cmap.value()))); + return new DTDataType(columnType, + DataType.map(resolveSimpleType(getter, cmap.key()), resolveSimpleType(getter, cmap.value()))); } Types.UDTKeyMap udtKeyMap = getter.getDeclaredAnnotation(Types.UDTKeyMap.class); if (udtKeyMap != null) { - return new UDTKeyMapDataType(columnType, - resolveUDT(udtKeyMap.key()), - UDTValue.class, + return new UDTKeyMapDataType(columnType, resolveUDT(udtKeyMap.key()), UDTValue.class, resolveSimpleType(getter, udtKeyMap.value())); } Types.UDTValueMap udtValueMap = getter.getDeclaredAnnotation(Types.UDTValueMap.class); if (udtValueMap != null) { - return new UDTValueMapDataType(columnType, - resolveSimpleType(getter, udtValueMap.key()), - resolveUDT(udtValueMap.value()), - UDTValue.class); + return new UDTValueMapDataType(columnType, resolveSimpleType(getter, udtValueMap.key()), + resolveUDT(udtValueMap.value()), UDTValue.class); } - + Types.UDTMap udtMap = getter.getDeclaredAnnotation(Types.UDTMap.class); if (udtMap != null) { - return new UDTMapDataType(columnType, - resolveUDT(udtMap.key()), - UDTValue.class, - resolveUDT(udtMap.value()), + return new UDTMapDataType(columnType, resolveUDT(udtMap.key()), UDTValue.class, resolveUDT(udtMap.value()), UDTValue.class); } Type[] args = getTypeParameters(genericJavaType); ensureTypeArguments(getter, args.length, 2); - - Either key = autodetectParameterType(getter, args[0]); - Either value = autodetectParameterType(getter, args[1]); - + + Either key = autodetectParameterType(getter, args[0], metadata); + Either value = autodetectParameterType(getter, args[1], metadata); + if (key.isLeft()) { - + if (value.isLeft()) { - return DTDataType.map(columnType, - key.getLeft(), args[0], - value.getLeft(), args[1]); + return DTDataType.map(columnType, key.getLeft(), args[0], value.getLeft(), args[1]); + } else { + return new UDTValueMapDataType(columnType, key.getLeft(), value.getRight(), (Class) args[1]); } - else { - return new UDTValueMapDataType(columnType, - key.getLeft(), - value.getRight(), + } else { + + if (value.isLeft()) { + return new UDTKeyMapDataType(columnType, key.getRight(), (Class) args[0], value.getLeft()); + } else { + return new UDTMapDataType(columnType, key.getRight(), (Class) args[0], value.getRight(), (Class) args[1]); } - } - else { - - if (value.isLeft()) { - return new UDTKeyMapDataType(columnType, - key.getRight(), - (Class) args[0], - value.getLeft()); - } - else { - return new UDTMapDataType(columnType, - key.getRight(), - (Class) args[0], - value.getRight(), - (Class) args[1]); - } - + } } - @Override - public Optional> resolveReadConverter( - AbstractDataType abstractDataType, SessionRepository repository) { - + public Optional> resolveReadConverter(AbstractDataType abstractDataType, + SessionRepository repository) { + if (abstractDataType instanceof DTDataType) { return resolveDTReadConverter((DTDataType) abstractDataType, repository); } - + else if (abstractDataType instanceof UDTKeyMapDataType) { - + UDTKeyMapDataType dt = (UDTKeyMapDataType) abstractDataType; - + Class keyClass = (Class) dt.getUdtKeyClass(); - + if (UDTValue.class.isAssignableFrom(keyClass)) { return Optional.empty(); } - + return Optional.of(new UDTKeyMapToMapConverter(keyClass, repository)); - + } - + else if (abstractDataType instanceof UDTValueMapDataType) { - + UDTValueMapDataType dt = (UDTValueMapDataType) abstractDataType; - + Class valueClass = (Class) dt.getUdtValueClass(); - + if (UDTValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); } - + return Optional.of(new UDTValueMapToMapConverter(valueClass, repository)); - + } - + else if (abstractDataType instanceof UDTMapDataType) { - + UDTMapDataType dt = (UDTMapDataType) abstractDataType; - + Class keyClass = (Class) dt.getUdtKeyClass(); Class valueClass = (Class) dt.getUdtValueClass(); - + if (UDTValue.class.isAssignableFrom(keyClass)) { - + if (UDTValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); + } else { + return Optional.of(new UDTValueMapToMapConverter(valueClass, repository)); } - else { - return Optional.of(new UDTValueMapToMapConverter(valueClass, repository)); - } - } - else if (UDTValue.class.isAssignableFrom(valueClass)) { + } else if (UDTValue.class.isAssignableFrom(valueClass)) { return Optional.of(new UDTKeyMapToMapConverter(keyClass, repository)); } - + return Optional.of(new UDTMapToMapConverter(keyClass, valueClass, repository)); - + } - + return Optional.empty(); } - private Optional> resolveDTReadConverter( - DTDataType dt, SessionRepository repository) { - + private Optional> resolveDTReadConverter(DTDataType dt, SessionRepository repository) { + DataType keyDataType = dt.getDataType().getTypeArguments().get(0); DataType valueDataType = dt.getDataType().getTypeArguments().get(1); - + if (keyDataType instanceof TupleType) { - + if (valueDataType instanceof TupleType) { - - Class keyClass = dt.getTypeArguments()[0]; - Class valueClass = dt.getTypeArguments()[1]; - + + Class keyClass = dt.getTypeArguments()[0]; + Class valueClass = dt.getTypeArguments()[1]; + if (TupleValue.class.isAssignableFrom(keyClass)) { - + if (TupleValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); - } - else { + } else { return Optional.of(new TupleValueMapToMapConverter(valueClass, repository)); } - - } - else if (TupleValue.class.isAssignableFrom(valueClass)) { + + } else if (TupleValue.class.isAssignableFrom(valueClass)) { return Optional.of(new TupleKeyMapToMapConverter(keyClass, repository)); } - + return Optional.of(new TupleMapToMapConverter(keyClass, valueClass, repository)); - - } - else { + + } else { Class keyClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(keyClass)) { return Optional.empty(); } - + return Optional.of(new TupleKeyMapToMapConverter(keyClass, repository)); } - } - else if (valueDataType instanceof TupleType) { - + } else if (valueDataType instanceof TupleType) { + Class valueClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); } - + return Optional.of(new TupleValueMapToMapConverter(valueClass, repository)); - + } return Optional.empty(); - + } - + @Override - public Optional> resolveWriteConverter( - AbstractDataType abstractDataType, SessionRepository repository) { - + public Optional> resolveWriteConverter(AbstractDataType abstractDataType, + SessionRepository repository) { + if (abstractDataType instanceof DTDataType) { return resolveDTWriteConverter((DTDataType) abstractDataType, repository); } - + else if (abstractDataType instanceof UDTKeyMapDataType) { - + UDTKeyMapDataType dt = (UDTKeyMapDataType) abstractDataType; - + Class keyClass = (Class) dt.getUdtKeyClass(); - + if (UDTValue.class.isAssignableFrom(keyClass)) { return Optional.empty(); } - return Optional.of(new MapToUDTKeyMapConverter( - keyClass, - getUserType(dt.getUdtKeyName(), keyClass, repository), - repository)); - + return Optional.of(new MapToUDTKeyMapConverter(keyClass, + getUserType(dt.getUdtKeyName(), keyClass, repository), repository)); + } - + else if (abstractDataType instanceof UDTValueMapDataType) { - + UDTValueMapDataType dt = (UDTValueMapDataType) abstractDataType; - + Class valueClass = (Class) dt.getUdtValueClass(); - + if (UDTValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); } - return Optional.of(new MapToUDTValueMapConverter( - valueClass, - getUserType(dt.getUdtValueName(), valueClass, repository), - repository)); - + return Optional.of(new MapToUDTValueMapConverter(valueClass, + getUserType(dt.getUdtValueName(), valueClass, repository), repository)); + } - + else if (abstractDataType instanceof UDTMapDataType) { - + UDTMapDataType dt = (UDTMapDataType) abstractDataType; - + Class keyClass = (Class) dt.getUdtKeyClass(); Class valueClass = (Class) dt.getUdtValueClass(); - + if (UDTValue.class.isAssignableFrom(keyClass)) { - + if (UDTValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); + } else { + + return Optional.of(new MapToUDTValueMapConverter(valueClass, + getUserType(dt.getUdtValueName(), valueClass, repository), repository)); } - else { - - return Optional.of(new MapToUDTValueMapConverter( - valueClass, - getUserType(dt.getUdtValueName(), valueClass, repository), - repository)); - } - } - else if (UDTValue.class.isAssignableFrom(valueClass)) { - - return Optional.of(new MapToUDTKeyMapConverter( - keyClass, - getUserType(dt.getUdtKeyName(), keyClass, repository), - repository)); + } else if (UDTValue.class.isAssignableFrom(valueClass)) { + + return Optional.of(new MapToUDTKeyMapConverter(keyClass, + getUserType(dt.getUdtKeyName(), keyClass, repository), repository)); } - return Optional.of(new MapToUDTMapConverter( - keyClass, - getUserType(dt.getUdtKeyName(), keyClass, repository), - valueClass, - getUserType(dt.getUdtValueName(), valueClass, repository), - repository)); - + return Optional.of(new MapToUDTMapConverter(keyClass, getUserType(dt.getUdtKeyName(), keyClass, repository), + valueClass, getUserType(dt.getUdtValueName(), valueClass, repository), repository)); + } - + return Optional.empty(); } - - private Optional> resolveDTWriteConverter( - DTDataType dt, SessionRepository repository) { + + private Optional> resolveDTWriteConverter(DTDataType dt, SessionRepository repository) { DataType keyDataType = dt.getDataType().getTypeArguments().get(0); DataType valueDataType = dt.getDataType().getTypeArguments().get(1); - + if (keyDataType instanceof TupleType) { - + if (valueDataType instanceof TupleType) { - - Class keyClass = dt.getTypeArguments()[0]; - Class valueClass = dt.getTypeArguments()[1]; - + + Class keyClass = dt.getTypeArguments()[0]; + Class valueClass = dt.getTypeArguments()[1]; + if (TupleValue.class.isAssignableFrom(keyClass)) { - + if (TupleValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); + } else { + return Optional + .of(new MapToTupleValueMapConverter(valueClass, (TupleType) valueDataType, repository)); } - else { - return Optional.of(new MapToTupleValueMapConverter( - valueClass, - (TupleType) valueDataType, - repository)); - } - - } - else if (TupleValue.class.isAssignableFrom(valueClass)) { - return Optional.of(new MapToTupleKeyMapConverter( - keyClass, - (TupleType) keyDataType, - repository)); + } else if (TupleValue.class.isAssignableFrom(valueClass)) { + + return Optional.of(new MapToTupleKeyMapConverter(keyClass, (TupleType) keyDataType, repository)); } - - return Optional.of(new MapToTupleMapConverter( - keyClass, - (TupleType) keyDataType, - valueClass, - (TupleType) valueDataType, - repository)); - - } - else { - + + return Optional.of(new MapToTupleMapConverter(keyClass, (TupleType) keyDataType, valueClass, + (TupleType) valueDataType, repository)); + + } else { + Class keyClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(keyClass)) { return Optional.empty(); } - - return Optional.of(new MapToTupleKeyMapConverter( - keyClass, - (TupleType) keyDataType, - repository)); + + return Optional.of(new MapToTupleKeyMapConverter(keyClass, (TupleType) keyDataType, repository)); } - } - else if (valueDataType instanceof TupleType) { - + } else if (valueDataType instanceof TupleType) { + Class valueClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(valueClass)) { return Optional.empty(); } - - return Optional.of(new MapToTupleValueMapConverter( - valueClass, - (TupleType) valueDataType, - repository)); + + return Optional.of(new MapToTupleValueMapConverter(valueClass, (TupleType) valueDataType, repository)); } return Optional.empty(); } - + private UserType getUserType(IdentityName name, Class javaClass, SessionRepository repository) { UserType userType = repository.findUserType(name.getName()); if (userType == null) { - throw new CasserMappingException("UserType not found for " + name + " with type " + javaClass); + throw new HelenusMappingException("UserType not found for " + name + " with type " + javaClass); } return userType; } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/MappingJavaTypes.java b/src/main/java/net/helenus/mapping/javatype/MappingJavaTypes.java similarity index 79% rename from src/main/java/com/noorq/casser/mapping/javatype/MappingJavaTypes.java rename to src/main/java/net/helenus/mapping/javatype/MappingJavaTypes.java index 95c3991..4bae0dc 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/MappingJavaTypes.java +++ b/src/main/java/net/helenus/mapping/javatype/MappingJavaTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -23,22 +23,24 @@ import java.net.InetAddress; import java.util.Optional; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Metadata; import com.google.common.collect.ImmutableMap; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.support.HelenusMappingException; public final class MappingJavaTypes { private static final EnumJavaType ENUM_JAVA_TYPE = new EnumJavaType(); private static final UDTValueJavaType UDT_VALUE_JAVA_TYPE = new UDTValueJavaType(); private static final TupleValueJavaType TUPLE_VALUE_JAVA_TYPE = new TupleValueJavaType(); - + private static final ImmutableMap, AbstractJavaType> knownTypes; - + static { - + ImmutableMap.Builder, AbstractJavaType> builder = ImmutableMap.builder(); add(builder, new BooleanJavaType()); @@ -48,7 +50,7 @@ public final class MappingJavaTypes { add(builder, new FloatJavaType()); add(builder, new IntegerJavaType()); add(builder, new InetAddressJavaType()); - + add(builder, new ByteBufferJavaType()); add(builder, new ByteArrayJavaType()); add(builder, new DateJavaType()); @@ -61,27 +63,27 @@ public final class MappingJavaTypes { add(builder, new MapJavaType()); add(builder, TUPLE_VALUE_JAVA_TYPE); add(builder, UDT_VALUE_JAVA_TYPE); - + knownTypes = builder.build(); - + } - + private static void add(ImmutableMap.Builder, AbstractJavaType> builder, AbstractJavaType jt) { - + builder.put(jt.getJavaClass(), jt); - + Optional> primitiveJavaClass = jt.getPrimitiveJavaClass(); if (primitiveJavaClass.isPresent()) { builder.put(primitiveJavaClass.get(), jt); } - + } - + private MappingJavaTypes() { } - + public static AbstractJavaType resolveJavaType(Class javaClass) { - + AbstractJavaType ajt = knownTypes.get(javaClass); if (ajt != null) { return ajt; @@ -94,15 +96,14 @@ public final class MappingJavaTypes { if (TUPLE_VALUE_JAVA_TYPE.isApplicable(javaClass)) { return TUPLE_VALUE_JAVA_TYPE; } - + if (UDT_VALUE_JAVA_TYPE.isApplicable(javaClass)) { return UDT_VALUE_JAVA_TYPE; } - - throw new CasserMappingException("unknown java type " + javaClass); + + throw new HelenusMappingException("unknown java type " + javaClass); } - - + public final static class BooleanJavaType extends AbstractJavaType { @Override @@ -116,11 +117,10 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.cboolean()); } - + } public final static class BigDecimalJavaType extends AbstractJavaType { @@ -131,13 +131,12 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.decimal()); } - + } - + public final static class BigIntegerJavaType extends AbstractJavaType { @Override @@ -146,14 +145,12 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.varint()); } - + } - - + public final static class DoubleJavaType extends AbstractJavaType { @Override @@ -167,13 +164,12 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.cdouble()); } - + } - + public final static class FloatJavaType extends AbstractJavaType { @Override @@ -187,13 +183,12 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.cfloat()); } - + } - + public final static class IntegerJavaType extends AbstractJavaType { @Override @@ -207,13 +202,12 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.cint()); } - + } - + public final static class InetAddressJavaType extends AbstractJavaType { @Override @@ -222,10 +216,9 @@ public final class MappingJavaTypes { } @Override - public AbstractDataType resolveDataType(Method getter, - Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { return new DTDataType(columnType, DataType.inet()); } - + } } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/SetJavaType.java b/src/main/java/net/helenus/mapping/javatype/SetJavaType.java similarity index 65% rename from src/main/java/com/noorq/casser/mapping/javatype/SetJavaType.java rename to src/main/java/net/helenus/mapping/javatype/SetJavaType.java index 41a4ec1..0f87dc7 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/SetJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/SetJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -21,24 +21,21 @@ import java.util.Optional; import java.util.Set; import java.util.function.Function; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.TupleType; -import com.datastax.driver.core.TupleValue; -import com.datastax.driver.core.UDTValue; -import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.tuple.SetToTupleSetConverter; -import com.noorq.casser.mapping.convert.tuple.TupleSetToSetConverter; -import com.noorq.casser.mapping.convert.udt.SetToUDTSetConverter; -import com.noorq.casser.mapping.convert.udt.UDTSetToSetConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.mapping.type.UDTSetDataType; -import com.noorq.casser.support.CasserMappingException; -import com.noorq.casser.support.Either; +import com.datastax.driver.core.*; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.tuple.SetToTupleSetConverter; +import net.helenus.mapping.convert.tuple.TupleSetToSetConverter; +import net.helenus.mapping.convert.udt.SetToUDTSetConverter; +import net.helenus.mapping.convert.udt.UDTSetToSetConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.mapping.type.UDTSetDataType; +import net.helenus.support.Either; +import net.helenus.support.HelenusMappingException; public final class SetJavaType extends AbstractJavaType { @@ -48,116 +45,111 @@ public final class SetJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { Types.Set cset = getter.getDeclaredAnnotation(Types.Set.class); if (cset != null) { - return new DTDataType(columnType, - DataType.set(resolveSimpleType(getter, cset.value()))); + return new DTDataType(columnType, DataType.set(resolveSimpleType(getter, cset.value()))); } Types.UDTSet udtSet = getter.getDeclaredAnnotation(Types.UDTSet.class); if (udtSet != null) { - return new UDTSetDataType(columnType, - resolveUDT(udtSet.value()), - UDTValue.class); + return new UDTSetDataType(columnType, resolveUDT(udtSet.value()), UDTValue.class); } Type[] args = getTypeParameters(genericJavaType); ensureTypeArguments(getter, args.length, 1); - - Either parameterType = autodetectParameterType(getter, args[0]); + + Either parameterType = autodetectParameterType(getter, args[0], metadata); if (parameterType.isLeft()) { return DTDataType.set(columnType, parameterType.getLeft(), args[0]); + } else { + return new UDTSetDataType(columnType, parameterType.getRight(), (Class) args[0]); } - else { - return new UDTSetDataType(columnType, - parameterType.getRight(), - (Class) args[0]); - } - + } @Override - public Optional> resolveReadConverter( - AbstractDataType abstractDataType, SessionRepository repository) { - + public Optional> resolveReadConverter(AbstractDataType abstractDataType, + SessionRepository repository) { + if (abstractDataType instanceof DTDataType) { - + DTDataType dt = (DTDataType) abstractDataType; DataType elementType = dt.getDataType().getTypeArguments().get(0); if (elementType instanceof TupleType) { - + Class tupleClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(tupleClass)) { return Optional.empty(); } - + return Optional.of(new TupleSetToSetConverter(tupleClass, repository)); } } - + else if (abstractDataType instanceof UDTSetDataType) { - + UDTSetDataType dt = (UDTSetDataType) abstractDataType; - + Class udtClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(udtClass)) { return Optional.empty(); } - + return Optional.of(new UDTSetToSetConverter(udtClass, repository)); - + } - + return Optional.empty(); } @Override - public Optional> resolveWriteConverter( - AbstractDataType abstractDataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType abstractDataType, + SessionRepository repository) { if (abstractDataType instanceof DTDataType) { - + DTDataType dt = (DTDataType) abstractDataType; DataType elementType = dt.getDataType().getTypeArguments().get(0); - + if (elementType instanceof TupleType) { - + Class tupleClass = dt.getTypeArguments()[0]; - + if (TupleValue.class.isAssignableFrom(tupleClass)) { return Optional.empty(); } - + return Optional.of(new SetToTupleSetConverter(tupleClass, (TupleType) elementType, repository)); } - + } - + else if (abstractDataType instanceof UDTSetDataType) { - + UDTSetDataType dt = (UDTSetDataType) abstractDataType; - + Class udtClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(udtClass)) { return Optional.empty(); } UserType userType = repository.findUserType(dt.getUdtName().getName()); if (userType == null) { - throw new CasserMappingException("UserType not found for " + dt.getUdtName() + " with type " + udtClass); + throw new HelenusMappingException( + "UserType not found for " + dt.getUdtName() + " with type " + udtClass); } - + return Optional.of(new SetToUDTSetConverter(udtClass, userType, repository)); - + } - + return Optional.empty(); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/SimpleJavaTypes.java b/src/main/java/net/helenus/mapping/javatype/SimpleJavaTypes.java similarity index 69% rename from src/main/java/com/noorq/casser/mapping/javatype/SimpleJavaTypes.java rename to src/main/java/net/helenus/mapping/javatype/SimpleJavaTypes.java index b1b11ac..ae60a33 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/SimpleJavaTypes.java +++ b/src/main/java/net/helenus/mapping/javatype/SimpleJavaTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; +import java.time.LocalTime; import java.util.HashMap; import java.util.Map; +import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.DataType; public final class SimpleJavaTypes { @@ -31,30 +33,31 @@ public final class SimpleJavaTypes { for (DataType dataType : DataType.allPrimitiveTypes()) { nameToDataTypeMap.put(dataType.getName(), dataType); - - if (dataType.equals(DataType.counter()) || - dataType.equals(DataType.ascii()) || - dataType.equals(DataType.timeuuid() - )) { + + if (dataType.equals(DataType.counter()) + || dataType.equals(DataType.ascii()) + || dataType.equals(DataType.timeuuid()) + || dataType.equals(DataType.time())) { continue; } - - Class javaClass = dataType.asJavaClass(); - + + Class javaClass = CodecRegistry.DEFAULT_INSTANCE.codecFor(dataType).getJavaType().getRawType(); + DataType dt = javaClassToDataTypeMap.putIfAbsent(javaClass, dataType); if (dt != null) { - throw new IllegalStateException("java type " + javaClass + " is has two datatypes " + dt + " and " + dataType); + throw new IllegalStateException( + "java type " + javaClass + " is has two datatypes " + dt + " and " + dataType); } } javaClassToDataTypeMap.put(String.class, DataType.text()); - + javaClassToDataTypeMap.put(LocalTime.class, DataType.time()); } private SimpleJavaTypes() { } - + public static DataType getDataTypeByName(DataType.Name name) { return nameToDataTypeMap.get(name); } @@ -63,5 +66,4 @@ public final class SimpleJavaTypes { return javaClassToDataTypeMap.get(javaType); } - } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/StringJavaType.java b/src/main/java/net/helenus/mapping/javatype/StringJavaType.java similarity index 68% rename from src/main/java/com/noorq/casser/mapping/javatype/StringJavaType.java rename to src/main/java/net/helenus/mapping/javatype/StringJavaType.java index a2a052a..f0d2a22 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/StringJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/StringJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; import com.datastax.driver.core.DataType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class StringJavaType extends AbstractJavaType { @@ -32,18 +34,18 @@ public final class StringJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Ascii.class)) { - return new DTDataType(columnType, DataType.ascii()); + return new DTDataType(columnType, DataType.ascii()); } if (null != getter.getDeclaredAnnotation(Types.Text.class)) { - return new DTDataType(columnType, DataType.text()); + return new DTDataType(columnType, DataType.text()); } if (null != getter.getDeclaredAnnotation(Types.Varchar.class)) { - return new DTDataType(columnType, DataType.varchar()); + return new DTDataType(columnType, DataType.varchar()); } return new DTDataType(columnType, DataType.text()); diff --git a/src/main/java/com/noorq/casser/mapping/javatype/TupleValueJavaType.java b/src/main/java/net/helenus/mapping/javatype/TupleValueJavaType.java similarity index 54% rename from src/main/java/com/noorq/casser/mapping/javatype/TupleValueJavaType.java rename to src/main/java/net/helenus/mapping/javatype/TupleValueJavaType.java index 99b2892..d65c600 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/TupleValueJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/TupleValueJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -23,21 +23,23 @@ import java.util.function.Function; import java.util.stream.Collectors; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Metadata; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.TypedConverter; -import com.noorq.casser.mapping.convert.tuple.EntityToTupleValueConverter; -import com.noorq.casser.mapping.convert.tuple.TupleValueToEntityConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.core.Helenus; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.TypedConverter; +import net.helenus.mapping.convert.tuple.EntityToTupleValueConverter; +import net.helenus.mapping.convert.tuple.TupleValueToEntityConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; +import net.helenus.support.HelenusMappingException; public final class TupleValueJavaType extends AbstractJavaType { @@ -50,19 +52,19 @@ public final class TupleValueJavaType extends AbstractJavaType { public boolean isApplicable(Class javaClass) { return MappingUtil.isTuple(javaClass); } - + @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { Class javaType = (Class) genericJavaType; if (TupleValue.class.isAssignableFrom(javaType)) { - + Types.Tuple tuple = getter.getDeclaredAnnotation(Types.Tuple.class); if (tuple == null) { - throw new CasserMappingException("tuple must be annotated by @Tuple annotation in " + getter); + throw new HelenusMappingException("tuple must be annotated by @Tuple annotation in " + getter); } - + DataType.Name[] tupleArguments = tuple.value(); int len = tupleArguments.length; DataType[] arguments = new DataType[len]; @@ -70,76 +72,67 @@ public final class TupleValueJavaType extends AbstractJavaType { for (int i = 0; i != len; ++i) { arguments[i] = resolveSimpleType(getter, tupleArguments[i]); } - - TupleType tupleType = TupleType.of(arguments); - return new DTDataType(columnType, tupleType, javaType); - + + TupleType tupleType = metadata.newTupleType(arguments); + return new DTDataType(columnType, tupleType, javaType); + + } else { + return new DTDataType(columnType, toTupleType(javaType, metadata), javaType); } - else { - return new DTDataType(columnType, toTupleType(javaType), javaType); - } - + } - public static TupleType toTupleType(Class javaType) { - CasserEntity tupleEntity = Casser.entity(javaType); - - List tupleTypes = tupleEntity.getOrderedProperties().stream() - .map(p -> p.getDataType()) - .filter(d -> d instanceof DTDataType) - .map(d -> (DTDataType) d) - .map(d -> d.getDataType()) - .collect(Collectors.toList()); - + public static TupleType toTupleType(Class javaType, Metadata metadata) { + HelenusEntity tupleEntity = Helenus.entity(javaType, metadata); + + List tupleTypes = tupleEntity.getOrderedProperties().stream().map(p -> p.getDataType()) + .filter(d -> d instanceof DTDataType).map(d -> (DTDataType) d).map(d -> d.getDataType()) + .collect(Collectors.toList()); + if (tupleTypes.size() < tupleEntity.getOrderedProperties().size()) { - + List wrongColumns = tupleEntity.getOrderedProperties().stream() - .filter(p -> !(p.getDataType() instanceof DTDataType)) - .map(p -> p.getColumnName()) + .filter(p -> !(p.getDataType() instanceof DTDataType)).map(p -> p.getColumnName()) .collect(Collectors.toList()); - - throw new CasserMappingException("non simple types in tuple " + tupleEntity.getMappingInterface() + " in columns: " + wrongColumns); + + throw new HelenusMappingException( + "non simple types in tuple " + tupleEntity.getMappingInterface() + " in columns: " + wrongColumns); } - - return TupleType.of(tupleTypes.toArray(new DataType[tupleTypes.size()])); + + return metadata.newTupleType(tupleTypes.toArray(new DataType[tupleTypes.size()])); } @Override - public Optional> resolveReadConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveReadConverter(AbstractDataType dataType, + SessionRepository repository) { DTDataType dt = (DTDataType) dataType; - + Class javaClass = (Class) dt.getJavaClass(); if (TupleValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } - return Optional.of(TypedConverter.create( - TupleValue.class, - javaClass, + return Optional.of(TypedConverter.create(TupleValue.class, javaClass, new TupleValueToEntityConverter(javaClass, repository))); - + } @Override - public Optional> resolveWriteConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType dataType, + SessionRepository repository) { DTDataType dt = (DTDataType) dataType; - + Class javaClass = (Class) dt.getJavaClass(); - + if (TupleValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } - - return Optional.of(TypedConverter.create( - javaClass, - TupleValue.class, - new EntityToTupleValueConverter(javaClass, - (TupleType) dt.getDataType(), repository))); + + return Optional.of(TypedConverter.create(javaClass, TupleValue.class, + new EntityToTupleValueConverter(javaClass, (TupleType) dt.getDataType(), repository))); } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/UDTValueJavaType.java b/src/main/java/net/helenus/mapping/javatype/UDTValueJavaType.java similarity index 60% rename from src/main/java/com/noorq/casser/mapping/javatype/UDTValueJavaType.java rename to src/main/java/net/helenus/mapping/javatype/UDTValueJavaType.java index f577e82..cbe2b62 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/UDTValueJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/UDTValueJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Optional; import java.util.function.Function; +import com.datastax.driver.core.Metadata; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.mapping.MappingUtil; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.convert.TypedConverter; -import com.noorq.casser.mapping.convert.udt.EntityToUDTValueConverter; -import com.noorq.casser.mapping.convert.udt.UDTValueToEntityConverter; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.UDTDataType; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.mapping.MappingUtil; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.convert.TypedConverter; +import net.helenus.mapping.convert.udt.EntityToUDTValueConverter; +import net.helenus.mapping.convert.udt.UDTValueToEntityConverter; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.UDTDataType; +import net.helenus.support.HelenusMappingException; public final class UDTValueJavaType extends AbstractJavaType { @@ -45,74 +47,69 @@ public final class UDTValueJavaType extends AbstractJavaType { public boolean isApplicable(Class javaClass) { return MappingUtil.isUDT(javaClass); } - + @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { - + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { + Class javaType = (Class) genericJavaType; - + IdentityName udtName = null; - + if (UDTValue.class.isAssignableFrom(javaType)) { - + Types.UDT userTypeName = getter.getDeclaredAnnotation(Types.UDT.class); if (userTypeName == null) { - throw new CasserMappingException("absent UserTypeName annotation for " + getter); + throw new HelenusMappingException("absent UserTypeName annotation for " + getter); } - + udtName = new IdentityName(userTypeName.value(), userTypeName.forceQuote()); + } else { + udtName = MappingUtil.getUserDefinedTypeName(javaType, false); } - else { - udtName = MappingUtil.getUserDefinedTypeName(javaType, false); - } - + if (udtName != null) { return new UDTDataType(columnType, udtName, javaType); } - - throw new CasserMappingException("unknown type " + javaType + " in " + getter); + + throw new HelenusMappingException("unknown type " + javaType + " in " + getter); } @Override - public Optional> resolveReadConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveReadConverter(AbstractDataType dataType, + SessionRepository repository) { UDTDataType dt = (UDTDataType) dataType; - + Class javaClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } - - return Optional.of(TypedConverter.create( - UDTValue.class, - javaClass, - new UDTValueToEntityConverter(javaClass, repository))); + + return Optional.of( + TypedConverter.create(UDTValue.class, javaClass, new UDTValueToEntityConverter(javaClass, repository))); } @Override - public Optional> resolveWriteConverter( - AbstractDataType dataType, SessionRepository repository) { + public Optional> resolveWriteConverter(AbstractDataType dataType, + SessionRepository repository) { UDTDataType dt = (UDTDataType) dataType; - + Class javaClass = (Class) dt.getTypeArguments()[0]; - + if (UDTValue.class.isAssignableFrom(javaClass)) { return Optional.empty(); } UserType userType = repository.findUserType(dt.getUdtName().getName()); if (userType == null) { - throw new CasserMappingException("UserType not found for " + dt.getUdtName() + " with type " + javaClass); + throw new HelenusMappingException("UserType not found for " + dt.getUdtName() + " with type " + javaClass); } - - return Optional.of(TypedConverter.create( - javaClass, - UDTValue.class, + + return Optional.of(TypedConverter.create(javaClass, UDTValue.class, new EntityToUDTValueConverter(javaClass, userType, repository))); - + } } diff --git a/src/main/java/com/noorq/casser/mapping/javatype/UUIDJavaType.java b/src/main/java/net/helenus/mapping/javatype/UUIDJavaType.java similarity index 70% rename from src/main/java/com/noorq/casser/mapping/javatype/UUIDJavaType.java rename to src/main/java/net/helenus/mapping/javatype/UUIDJavaType.java index 5e22272..56bbb6e 100644 --- a/src/main/java/com/noorq/casser/mapping/javatype/UUIDJavaType.java +++ b/src/main/java/net/helenus/mapping/javatype/UUIDJavaType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.javatype; +package net.helenus.mapping.javatype; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.UUID; import com.datastax.driver.core.DataType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.type.AbstractDataType; -import com.noorq.casser.mapping.type.DTDataType; + +import com.datastax.driver.core.Metadata; +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.type.AbstractDataType; +import net.helenus.mapping.type.DTDataType; public final class UUIDJavaType extends AbstractJavaType { @@ -33,17 +35,17 @@ public final class UUIDJavaType extends AbstractJavaType { } @Override - public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType) { + public AbstractDataType resolveDataType(Method getter, Type genericJavaType, ColumnType columnType, Metadata metadata) { if (null != getter.getDeclaredAnnotation(Types.Uuid.class)) { - return new DTDataType(columnType, DataType.uuid()); + return new DTDataType(columnType, DataType.uuid()); } if (null != getter.getDeclaredAnnotation(Types.Timeuuid.class)) { - return new DTDataType(columnType, DataType.timeuuid()); + return new DTDataType(columnType, DataType.timeuuid()); } return new DTDataType(columnType, DataType.uuid()); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/AbstractDataType.java b/src/main/java/net/helenus/mapping/type/AbstractDataType.java similarity index 77% rename from src/main/java/com/noorq/casser/mapping/type/AbstractDataType.java rename to src/main/java/net/helenus/mapping/type/AbstractDataType.java index 0d31e71..fba8178 100644 --- a/src/main/java/com/noorq/casser/mapping/type/AbstractDataType.java +++ b/src/main/java/net/helenus/mapping/type/AbstractDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import com.datastax.driver.core.schemabuilder.Alter; import com.datastax.driver.core.schemabuilder.Create; import com.datastax.driver.core.schemabuilder.CreateType; import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public abstract class AbstractDataType { @@ -29,12 +30,13 @@ public abstract class AbstractDataType { public abstract void addColumn(CreateType create, IdentityName columnName); - public abstract SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnInformation); - + public abstract SchemaStatement alterColumn(Alter alter, IdentityName columnName, + OptionalColumnMetadata columnInformation); + public abstract Class[] getTypeArguments(); - + final ColumnType columnType; - + public AbstractDataType(ColumnType columnType) { this.columnType = columnType; } @@ -48,9 +50,10 @@ public abstract class AbstractDataType { throwWrongColumnType(columnName); } } - + void throwWrongColumnType(IdentityName columnName) { - throw new CasserMappingException("wrong column type " + columnType + " for UserDefinedType in columnName " + columnName); + throw new HelenusMappingException( + "wrong column type " + columnType + " for UserDefinedType in columnName " + columnName); } - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/DTDataType.java b/src/main/java/net/helenus/mapping/type/DTDataType.java similarity index 58% rename from src/main/java/com/noorq/casser/mapping/type/DTDataType.java rename to src/main/java/net/helenus/mapping/type/DTDataType.java index ce221e9..4969ec5 100644 --- a/src/main/java/com/noorq/casser/mapping/type/DTDataType.java +++ b/src/main/java/net/helenus/mapping/type/DTDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,37 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.lang.reflect.Type; -import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.DataType; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.schemabuilder.Alter; import com.datastax.driver.core.schemabuilder.Create; import com.datastax.driver.core.schemabuilder.CreateType; import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class DTDataType extends AbstractDataType { - private static final Class[] EMPTY_CLASSES = new Class[] {}; - + private static final Class[] EMPTY_CLASSES = new Class[]{}; + private final DataType dataType; private final Class javaClass; private final Class[] typeArguments; - + public DTDataType(ColumnType columnType, DataType dataType) { - this(columnType, dataType, dataType.asJavaClass(), EMPTY_CLASSES); + this(columnType, dataType, CodecRegistry.DEFAULT_INSTANCE.codecFor(dataType).getJavaType().getClass(), EMPTY_CLASSES); } - + public DTDataType(ColumnType columnType, DataType dataType, Class javaClass) { this(columnType, dataType, javaClass, EMPTY_CLASSES); } - + public DTDataType(ColumnType columnType, DataType dataType, Class javaClass, Class[] typeArguments) { super(columnType); this.dataType = dataType; @@ -52,60 +53,56 @@ public final class DTDataType extends AbstractDataType { } public static DTDataType list(ColumnType columnType, DataType argumentDataType, Type argumentType) { - + DataType listDataType = DataType.list(argumentDataType); - + if (argumentDataType instanceof TupleType) { - return new DTDataType(columnType, listDataType, listDataType.asJavaClass(), - new Class[] { (Class) argumentType }); - } - else { + return new DTDataType(columnType, listDataType, + CodecRegistry.DEFAULT_INSTANCE.codecFor(listDataType).getClass(), + new Class[]{(Class) argumentType}); + } else { return new DTDataType(columnType, listDataType); } } - + public static DTDataType set(ColumnType columnType, DataType argumentDataType, Type argumentType) { - + DataType setDataType = DataType.set(argumentDataType); - + if (argumentDataType instanceof TupleType) { - return new DTDataType(columnType, setDataType, setDataType.asJavaClass(), - new Class[] { (Class) argumentType }); - } - else { + return new DTDataType(columnType, setDataType, + CodecRegistry.DEFAULT_INSTANCE.codecFor(setDataType).getClass(), + new Class[]{(Class) argumentType}); + } else { return new DTDataType(columnType, setDataType); } } - - public static DTDataType map(ColumnType columnType, - DataType keyDataType, Type keyType, - DataType valueDataType, Type valueType) { - + + public static DTDataType map(ColumnType columnType, DataType keyDataType, Type keyType, DataType valueDataType, + Type valueType) { + DataType mapDataType = DataType.map(keyDataType, valueDataType); - - Class[] typeArguments = EMPTY_CLASSES; - + + Class[] typeArguments = EMPTY_CLASSES; + if (keyDataType instanceof TupleType) { if (valueDataType instanceof TupleType) { - typeArguments = new Class[] { (Class) keyType, (Class) valueType }; - } - else { - typeArguments = new Class[] { (Class) keyType }; + typeArguments = new Class[]{(Class) keyType, (Class) valueType}; + } else { + typeArguments = new Class[]{(Class) keyType}; } + } else if (valueDataType instanceof TupleType) { + typeArguments = new Class[]{(Class) valueType}; } - else if (valueDataType instanceof TupleType) { - typeArguments = new Class[] { (Class) valueType }; - } - - return new DTDataType(columnType, mapDataType, - mapDataType.asJavaClass(), typeArguments); - + + return new DTDataType(columnType, mapDataType, CodecRegistry.DEFAULT_INSTANCE.codecFor(mapDataType).getClass(), + typeArguments); } - + public DataType getDataType() { return dataType; } - + public Class getJavaClass() { return javaClass; } @@ -114,72 +111,71 @@ public final class DTDataType extends AbstractDataType { public Class[] getTypeArguments() { return typeArguments; } - + @Override public void addColumn(Create create, IdentityName columnName) { - - switch(columnType) { - - case PARTITION_KEY: - create.addPartitionKey(columnName.toCql(), dataType); - break; - - case CLUSTERING_COLUMN: - create.addClusteringColumn(columnName.toCql(), dataType); - break; - - case STATIC_COLUMN: - create.addStaticColumn(columnName.toCql(), dataType); - break; - - case COLUMN: - create.addColumn(columnName.toCql(), dataType); - break; - - default: - throwWrongColumnType(columnName); + + switch (columnType) { + + case PARTITION_KEY : + create.addPartitionKey(columnName.toCql(), dataType); + break; + + case CLUSTERING_COLUMN : + create.addClusteringColumn(columnName.toCql(), dataType); + break; + + case STATIC_COLUMN : + create.addStaticColumn(columnName.toCql(), dataType); + break; + + case COLUMN : + create.addColumn(columnName.toCql(), dataType); + break; + + default : + throwWrongColumnType(columnName); } - + } @Override public void addColumn(CreateType create, IdentityName columnName) { - + if (columnType != ColumnType.COLUMN) { throwWrongColumnType(columnName); } - + create.addColumn(columnName.toCql(), dataType); } - + @Override public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { - + if (columnMetadata != null) { - + if (!dataType.equals(columnMetadata.getType())) { ensureSimpleColumn(columnName); - + return alter.alterColumn(columnName.toCql()).type(dataType); } - - } - else { - - switch(columnType) { - - case STATIC_COLUMN: - return alter.addStaticColumn(columnName.toCql()).type(dataType); - - case COLUMN: - return alter.addColumn(columnName.toCql()).type(dataType); - - default: - throw new CasserMappingException("unable to alter " + columnType + " column " + columnName); + + } else { + + switch (columnType) { + + case STATIC_COLUMN : + return alter.addStaticColumn(columnName.toCql()).type(dataType); + + case COLUMN : + return alter.addColumn(columnName.toCql()).type(dataType); + + default : + throw new HelenusMappingException("unable to alter " + columnType + " column " + columnName); } - + } - + return null; } @@ -187,7 +183,5 @@ public final class DTDataType extends AbstractDataType { public String toString() { return dataType.toString(); } - - - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/ListToTupleListConverter.java b/src/main/java/net/helenus/mapping/type/ListToTupleListConverter.java similarity index 81% rename from src/main/java/com/noorq/casser/mapping/type/ListToTupleListConverter.java rename to src/main/java/net/helenus/mapping/type/ListToTupleListConverter.java index fd53014..003f080 100644 --- a/src/main/java/com/noorq/casser/mapping/type/ListToTupleListConverter.java +++ b/src/main/java/net/helenus/mapping/type/ListToTupleListConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import java.util.function.Function; import com.datastax.driver.core.TupleType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.convert.TupleValueWriter; -import com.noorq.casser.support.Transformers; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.convert.TupleValueWriter; +import net.helenus.support.Transformers; public final class ListToTupleListConverter implements Function { final TupleValueWriter writer; - + public ListToTupleListConverter(Class iface, TupleType tupleType, SessionRepository repository) { this.writer = new TupleValueWriter(iface, tupleType, repository); } - + @Override public Object apply(Object t) { return Transformers.transformList((List) t, writer); } - } diff --git a/src/main/java/com/noorq/casser/mapping/type/OptionalColumnMetadata.java b/src/main/java/net/helenus/mapping/type/OptionalColumnMetadata.java similarity index 88% rename from src/main/java/com/noorq/casser/mapping/type/OptionalColumnMetadata.java rename to src/main/java/net/helenus/mapping/type/OptionalColumnMetadata.java index c366191..9b510e7 100644 --- a/src/main/java/com/noorq/casser/mapping/type/OptionalColumnMetadata.java +++ b/src/main/java/net/helenus/mapping/type/OptionalColumnMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import com.datastax.driver.core.DataType; public interface OptionalColumnMetadata { String getName(); - + DataType getType(); - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTDataType.java b/src/main/java/net/helenus/mapping/type/UDTDataType.java similarity index 64% rename from src/main/java/com/noorq/casser/mapping/type/UDTDataType.java rename to src/main/java/net/helenus/mapping/type/UDTDataType.java index 884ca8f..d845139 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; public final class UDTDataType extends AbstractDataType { private final IdentityName udtName; private final Class udtClass; - + public UDTDataType(ColumnType columnType, IdentityName udtName, Class udtClass) { super(columnType); this.udtName = udtName; @@ -39,86 +35,82 @@ public final class UDTDataType extends AbstractDataType { @Override public Class[] getTypeArguments() { - return new Class[] { udtClass }; + return new Class[]{udtClass}; } - + public IdentityName getUdtName() { return udtName; } @Override public void addColumn(Create create, IdentityName columnName) { - - UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); - - switch(columnType) { - - case PARTITION_KEY: - create.addUDTPartitionKey(columnName.toCql(), udtType); - break; - case CLUSTERING_COLUMN: - create.addUDTClusteringColumn(columnName.toCql(), udtType); - break; - - case STATIC_COLUMN: - create.addUDTStaticColumn(columnName.toCql(), udtType); - break; - - case COLUMN: - create.addUDTColumn(columnName.toCql(), udtType); - break; - - default: - throwWrongColumnType(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); + + switch (columnType) { + + case PARTITION_KEY : + create.addUDTPartitionKey(columnName.toCql(), udtType); + break; + + case CLUSTERING_COLUMN : + create.addUDTClusteringColumn(columnName.toCql(), udtType); + break; + + case STATIC_COLUMN : + create.addUDTStaticColumn(columnName.toCql(), udtType); + break; + + case COLUMN : + create.addUDTColumn(columnName.toCql(), udtType); + break; + + default : + throwWrongColumnType(columnName); + } - + } @Override public void addColumn(CreateType create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); create.addUDTColumn(columnName.toCql(), udtType); - + } @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + ensureSimpleColumn(columnName); - + if (columnMetadata != null) { - + DataType metadataType = columnMetadata.getType(); - if (metadataType.getName() == DataType.Name.UDT && - metadataType instanceof UserType) { - + if (metadataType.getName() == DataType.Name.UDT && metadataType instanceof UserType) { + UserType metadataUserType = (UserType) metadataType; - + if (!udtName.getName().equals(metadataUserType.getTypeName())) { - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); return alter.alterColumn(columnName.toCql()).udtType(udtType); } - - } - else { - + + } else { + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); return alter.alterColumn(columnName.toCql()).udtType(udtType); - + } - - } - else { - + + } else { + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); return alter.addColumn(columnName.toCql()).udtType(udtType); - + } return null; diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTKeyMapDataType.java b/src/main/java/net/helenus/mapping/type/UDTKeyMapDataType.java similarity index 73% rename from src/main/java/com/noorq/casser/mapping/type/UDTKeyMapDataType.java rename to src/main/java/net/helenus/mapping/type/UDTKeyMapDataType.java index ff289ac..78554ad 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTKeyMapDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTKeyMapDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,40 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class UDTKeyMapDataType extends AbstractDataType { private final IdentityName keyType; private final Class udtKeyClass; private final DataType valueType; - + public UDTKeyMapDataType(ColumnType columnType, IdentityName keyType, Class udtKeyClass, DataType valueType) { super(columnType); this.keyType = keyType; this.udtKeyClass = udtKeyClass; this.valueType = valueType; } - + @Override public Class[] getTypeArguments() { - return new Class[] { udtKeyClass }; + return new Class[]{udtKeyClass}; } - + public IdentityName getUdtKeyName() { return keyType; } @@ -54,11 +50,11 @@ public final class UDTKeyMapDataType extends AbstractDataType { public Class getUdtKeyClass() { return udtKeyClass; } - + @Override public void addColumn(Create create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType keyUdtType = SchemaBuilder.frozen(keyType.toCql()); create.addUDTMapColumn(columnName.toCql(), keyUdtType, valueType); } @@ -66,52 +62,51 @@ public final class UDTKeyMapDataType extends AbstractDataType { @Override public void addColumn(CreateType create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType keyUdtType = SchemaBuilder.frozen(keyType.toCql()); create.addUDTMapColumn(columnName.toCql(), keyUdtType, valueType); } - + @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + if (columnMetadata == null) { return notSupportedOperation("add", columnName); } - + DataType schemaDataType = columnMetadata.getType(); if (schemaDataType.getName() != DataType.Name.MAP) { return notSupportedOperation("alter", columnName); } - + List args = columnMetadata.getType().getTypeArguments(); if (args.size() != 2 || !args.get(1).equals(valueType)) { return notSupportedOperation("alter", columnName); } - + DataType keyDataType = args.get(0); - if (keyDataType.getName() != DataType.Name.UDT || - !(keyDataType instanceof UserType)) { + if (keyDataType.getName() != DataType.Name.UDT || !(keyDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtKeyType = (UserType) keyDataType; - + if (!keyType.getName().equals(udtKeyType.getTypeName())) { return notSupportedOperation("alter", columnName); } - + // equals return null; } - + private SchemaStatement notSupportedOperation(String op, IdentityName columnName) { - throw new CasserMappingException(op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); + throw new HelenusMappingException( + op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); } - + @Override public String toString() { - return "UDTKeyMap<" + keyType + "," + valueType + ">"; + return "UDTKeyMap<" + keyType + "," + valueType + ">"; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTListDataType.java b/src/main/java/net/helenus/mapping/type/UDTListDataType.java similarity index 73% rename from src/main/java/com/noorq/casser/mapping/type/UDTListDataType.java rename to src/main/java/net/helenus/mapping/type/UDTListDataType.java index ec87b3d..b032ab2 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTListDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTListDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,38 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class UDTListDataType extends AbstractDataType { private final IdentityName udtName; private final Class udtClass; - + public UDTListDataType(ColumnType columnType, IdentityName udtName, Class udtClass) { super(columnType); this.udtName = udtName; this.udtClass = udtClass; } - + @Override public Class[] getTypeArguments() { - return new Class[] { udtClass }; + return new Class[]{udtClass}; } - + public IdentityName getUdtName() { return udtName; } @@ -52,7 +48,7 @@ public final class UDTListDataType extends AbstractDataType { @Override public void addColumn(Create create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); create.addUDTListColumn(columnName.toCql(), udtType); } @@ -60,48 +56,47 @@ public final class UDTListDataType extends AbstractDataType { @Override public void addColumn(CreateType create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); create.addUDTListColumn(columnName.toCql(), udtType); } @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + if (columnMetadata == null) { return notSupportedOperation("add", columnName); } - + DataType schemaDataType = columnMetadata.getType(); if (schemaDataType.getName() != DataType.Name.LIST) { return notSupportedOperation("alter", columnName); } - + List args = columnMetadata.getType().getTypeArguments(); if (args.size() != 1) { return notSupportedOperation("alter", columnName); } - + DataType valueDataType = args.get(0); - if (valueDataType.getName() != DataType.Name.UDT || - !(valueDataType instanceof UserType)) { + if (valueDataType.getName() != DataType.Name.UDT || !(valueDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtValueType = (UserType) valueDataType; - + if (!udtName.getName().equals(udtValueType.getTypeName())) { return notSupportedOperation("alter", columnName); } // equals return null; - + } - + private SchemaStatement notSupportedOperation(String op, IdentityName columnName) { - throw new CasserMappingException(op + " UDTList column is not supported by Cassandra Driver for column '" + columnName + "'"); + throw new HelenusMappingException( + op + " UDTList column is not supported by Cassandra Driver for column '" + columnName + "'"); } @Override diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTMapDataType.java b/src/main/java/net/helenus/mapping/type/UDTMapDataType.java similarity index 73% rename from src/main/java/com/noorq/casser/mapping/type/UDTMapDataType.java rename to src/main/java/net/helenus/mapping/type/UDTMapDataType.java index fd6d164..9f7e8f2 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTMapDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTMapDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class UDTMapDataType extends AbstractDataType { @@ -35,20 +31,21 @@ public final class UDTMapDataType extends AbstractDataType { private final Class udtKeyClass; private final IdentityName valueType; private final Class udtValueClass; - - public UDTMapDataType(ColumnType columnType, IdentityName keyType, Class udtKeyClass, IdentityName valueType, Class udtValueClass) { + + public UDTMapDataType(ColumnType columnType, IdentityName keyType, Class udtKeyClass, IdentityName valueType, + Class udtValueClass) { super(columnType); this.keyType = keyType; this.udtKeyClass = udtKeyClass; this.valueType = valueType; this.udtValueClass = udtValueClass; } - + @Override public Class[] getTypeArguments() { - return new Class[] { udtKeyClass, udtValueClass }; + return new Class[]{udtKeyClass, udtValueClass}; } - + public IdentityName getUdtKeyName() { return keyType; } @@ -68,7 +65,7 @@ public final class UDTMapDataType extends AbstractDataType { @Override public void addColumn(Create create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType keyUdtType = SchemaBuilder.frozen(keyType.toCql()); UDTType valueUdtType = SchemaBuilder.frozen(valueType.toCql()); create.addUDTMapColumn(columnName.toCql(), keyUdtType, valueUdtType); @@ -77,50 +74,47 @@ public final class UDTMapDataType extends AbstractDataType { @Override public void addColumn(CreateType create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType keyUdtType = SchemaBuilder.frozen(keyType.toCql()); UDTType valueUdtType = SchemaBuilder.frozen(valueType.toCql()); create.addUDTMapColumn(columnName.toCql(), keyUdtType, valueUdtType); } - + @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + if (columnMetadata == null) { return notSupportedOperation("add", columnName); } - + DataType schemaDataType = columnMetadata.getType(); if (schemaDataType.getName() != DataType.Name.MAP) { return notSupportedOperation("alter", columnName); } - + List args = columnMetadata.getType().getTypeArguments(); if (args.size() != 2) { return notSupportedOperation("alter", columnName); } - + DataType keyDataType = args.get(0); - if (keyDataType.getName() != DataType.Name.UDT || - !(keyDataType instanceof UserType)) { + if (keyDataType.getName() != DataType.Name.UDT || !(keyDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtKeyType = (UserType) keyDataType; - + if (!keyType.getName().equals(udtKeyType.getTypeName())) { return notSupportedOperation("alter", columnName); } - + DataType valueDataType = args.get(1); - if (valueDataType.getName() != DataType.Name.UDT || - !(valueDataType instanceof UserType)) { + if (valueDataType.getName() != DataType.Name.UDT || !(valueDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtValueType = (UserType) valueDataType; - + if (!valueType.getName().equals(udtValueType.getTypeName())) { return notSupportedOperation("alter", columnName); } @@ -128,13 +122,14 @@ public final class UDTMapDataType extends AbstractDataType { // equals return null; } - + private SchemaStatement notSupportedOperation(String op, IdentityName columnName) { - throw new CasserMappingException(op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); + throw new HelenusMappingException( + op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); } - + @Override public String toString() { - return "UDTMap<" + keyType + "," + valueType + ">"; + return "UDTMap<" + keyType + "," + valueType + ">"; } } diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTSetDataType.java b/src/main/java/net/helenus/mapping/type/UDTSetDataType.java similarity index 72% rename from src/main/java/com/noorq/casser/mapping/type/UDTSetDataType.java rename to src/main/java/net/helenus/mapping/type/UDTSetDataType.java index a984079..d61e0c8 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTSetDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTSetDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,38 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class UDTSetDataType extends AbstractDataType { private final IdentityName udtName; private final Class udtClass; - + public UDTSetDataType(ColumnType columnType, IdentityName udtName, Class udtClass) { super(columnType); this.udtName = udtName; this.udtClass = udtClass; } - + @Override public Class[] getTypeArguments() { - return new Class[] { udtClass }; + return new Class[]{udtClass}; } - + public IdentityName getUdtName() { return udtName; } @@ -52,7 +48,7 @@ public final class UDTSetDataType extends AbstractDataType { @Override public void addColumn(Create create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); create.addUDTSetColumn(columnName.toCql(), udtType); } @@ -60,53 +56,52 @@ public final class UDTSetDataType extends AbstractDataType { @Override public void addColumn(CreateType create, IdentityName columnName) { ensureSimpleColumn(columnName); - + UDTType udtType = SchemaBuilder.frozen(udtName.toCql()); create.addUDTSetColumn(columnName.toCql(), udtType); } - + @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + if (columnMetadata == null) { return notSupportedOperation("add", columnName); } - + DataType schemaDataType = columnMetadata.getType(); if (schemaDataType.getName() != DataType.Name.SET) { return notSupportedOperation("alter", columnName); } - + List args = columnMetadata.getType().getTypeArguments(); if (args.size() != 1) { return notSupportedOperation("alter", columnName); } - + DataType valueDataType = args.get(0); - if (valueDataType.getName() != DataType.Name.UDT || - !(valueDataType instanceof UserType)) { + if (valueDataType.getName() != DataType.Name.UDT || !(valueDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtValueType = (UserType) valueDataType; - + if (!udtName.getName().equals(udtValueType.getTypeName())) { return notSupportedOperation("alter", columnName); } // equals return null; - + } - + private SchemaStatement notSupportedOperation(String op, IdentityName columnName) { - throw new CasserMappingException(op + " UDTSet column is not supported by Cassandra Driver for column '" + columnName + "'"); + throw new HelenusMappingException( + op + " UDTSet column is not supported by Cassandra Driver for column '" + columnName + "'"); } - + @Override public String toString() { return "UDTSet<" + udtName + ">"; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/type/UDTValueMapDataType.java b/src/main/java/net/helenus/mapping/type/UDTValueMapDataType.java similarity index 72% rename from src/main/java/com/noorq/casser/mapping/type/UDTValueMapDataType.java rename to src/main/java/net/helenus/mapping/type/UDTValueMapDataType.java index 2088e0b..e9fd675 100644 --- a/src/main/java/com/noorq/casser/mapping/type/UDTValueMapDataType.java +++ b/src/main/java/net/helenus/mapping/type/UDTValueMapDataType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.type; +package net.helenus.mapping.type; import java.util.List; import com.datastax.driver.core.DataType; import com.datastax.driver.core.UserType; -import com.datastax.driver.core.schemabuilder.Alter; -import com.datastax.driver.core.schemabuilder.Create; -import com.datastax.driver.core.schemabuilder.CreateType; -import com.datastax.driver.core.schemabuilder.SchemaBuilder; -import com.datastax.driver.core.schemabuilder.SchemaStatement; -import com.datastax.driver.core.schemabuilder.UDTType; -import com.noorq.casser.mapping.ColumnType; -import com.noorq.casser.mapping.IdentityName; -import com.noorq.casser.support.CasserMappingException; +import com.datastax.driver.core.schemabuilder.*; + +import net.helenus.mapping.ColumnType; +import net.helenus.mapping.IdentityName; +import net.helenus.support.HelenusMappingException; public final class UDTValueMapDataType extends AbstractDataType { private final DataType keyType; private final IdentityName valueType; private final Class udtValueClass; - - public UDTValueMapDataType(ColumnType columnType, DataType keyType, IdentityName valueType, Class udtValueClass) { + + public UDTValueMapDataType(ColumnType columnType, DataType keyType, IdentityName valueType, + Class udtValueClass) { super(columnType); this.keyType = keyType; this.valueType = valueType; @@ -44,9 +41,9 @@ public final class UDTValueMapDataType extends AbstractDataType { @Override public Class[] getTypeArguments() { - return new Class[] { udtValueClass }; + return new Class[]{udtValueClass}; } - + public IdentityName getUdtValueName() { return valueType; } @@ -54,7 +51,7 @@ public final class UDTValueMapDataType extends AbstractDataType { public Class getUdtValueClass() { return udtValueClass; } - + @Override public void addColumn(Create create, IdentityName columnName) { ensureSimpleColumn(columnName); @@ -72,9 +69,8 @@ public final class UDTValueMapDataType extends AbstractDataType { } @Override - public SchemaStatement alterColumn(Alter alter, IdentityName columnName, - OptionalColumnMetadata columnMetadata) { - + public SchemaStatement alterColumn(Alter alter, IdentityName columnName, OptionalColumnMetadata columnMetadata) { + if (columnMetadata == null) { return notSupportedOperation("add", columnName); } @@ -83,20 +79,19 @@ public final class UDTValueMapDataType extends AbstractDataType { if (schemaDataType.getName() != DataType.Name.MAP) { return notSupportedOperation("alter", columnName); } - + List args = columnMetadata.getType().getTypeArguments(); if (args.size() != 2 || !args.get(0).equals(keyType)) { return notSupportedOperation("alter", columnName); } - + DataType valueDataType = args.get(1); - if (valueDataType.getName() != DataType.Name.UDT || - !(valueDataType instanceof UserType)) { + if (valueDataType.getName() != DataType.Name.UDT || !(valueDataType instanceof UserType)) { return notSupportedOperation("alter", columnName); } - + UserType udtValueType = (UserType) valueDataType; - + if (!valueType.getName().equals(udtValueType.getTypeName())) { return notSupportedOperation("alter", columnName); } @@ -104,14 +99,15 @@ public final class UDTValueMapDataType extends AbstractDataType { // equals return null; } - + private SchemaStatement notSupportedOperation(String op, IdentityName columnName) { - throw new CasserMappingException(op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); + throw new HelenusMappingException( + op + " UDTMap column is not supported by Cassandra Driver for column '" + columnName + "'"); } - + @Override public String toString() { - return "UDTValueMap<" + keyType + "," + valueType + ">"; + return "UDTValueMap<" + keyType + "," + valueType + ">"; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/validator/AlphabetValidator.java b/src/main/java/net/helenus/mapping/validator/AlphabetValidator.java similarity index 75% rename from src/main/java/com/noorq/casser/mapping/validator/AlphabetValidator.java rename to src/main/java/net/helenus/mapping/validator/AlphabetValidator.java index e1a5ca5..9132259 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/AlphabetValidator.java +++ b/src/main/java/net/helenus/mapping/validator/AlphabetValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,44 +13,43 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import java.util.Arrays; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.Alphabet; +import net.helenus.mapping.annotation.Constraints; -public final class AlphabetValidator implements ConstraintValidator { +public final class AlphabetValidator implements ConstraintValidator { char[] alphabet; - + @Override - public void initialize(Alphabet constraintAnnotation) { + public void initialize(Constraints.Alphabet constraintAnnotation) { alphabet = constraintAnnotation.value().toCharArray(); Arrays.sort(alphabet); } @Override - public boolean isValid(CharSequence value, - ConstraintValidatorContext context) { + public boolean isValid(CharSequence value, ConstraintValidatorContext context) { if (value == null) { - return true; + return true; } - + final int len = value.length(); for (int i = 0; i != len; ++i) { - + char ch = value.charAt(i); - + if (Arrays.binarySearch(alphabet, ch) < 0) { return false; } } - + return true; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/EmailValidator.java b/src/main/java/net/helenus/mapping/validator/EmailValidator.java similarity index 63% rename from src/main/java/com/noorq/casser/mapping/validator/EmailValidator.java rename to src/main/java/net/helenus/mapping/validator/EmailValidator.java index 29eb7e3..5a0aec2 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/EmailValidator.java +++ b/src/main/java/net/helenus/mapping/validator/EmailValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import java.net.IDN; import java.util.regex.Pattern; @@ -21,36 +21,31 @@ import java.util.regex.Pattern; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.Email; +import net.helenus.mapping.annotation.Constraints.Email; public final class EmailValidator implements ConstraintValidator { - static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]"; - static final String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*"; - static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]"; + static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]"; + static final String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*"; + static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]"; + + static final String PATTERN = "^" + ATOM + "+(\\." + ATOM + "+)*@" + DOMAIN + "|" + IP_DOMAIN + ")$"; - static final String PATTERN = - "^" + ATOM + "+(\\." + ATOM + "+)*@" - + DOMAIN - + "|" - + IP_DOMAIN - + ")$"; - private static final Pattern pattern = Pattern.compile(PATTERN, Pattern.CASE_INSENSITIVE); - + @Override public void initialize(Email constraintAnnotation) { } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { - + if (value == null) { - return true; + return true; } - - String asciiString = IDN.toASCII( value.toString() ); - + + String asciiString = IDN.toASCII(value.toString()); + return pattern.matcher(asciiString).matches(); } diff --git a/src/main/java/com/noorq/casser/mapping/validator/LengthValidator.java b/src/main/java/net/helenus/mapping/validator/LengthValidator.java similarity index 87% rename from src/main/java/com/noorq/casser/mapping/validator/LengthValidator.java rename to src/main/java/net/helenus/mapping/validator/LengthValidator.java index b483d66..1e30968 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/LengthValidator.java +++ b/src/main/java/net/helenus/mapping/validator/LengthValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.Length; +import net.helenus.mapping.annotation.Constraints.Length; public final class LengthValidator implements ConstraintValidator, SizeConstraint { int length; - + @Override public void initialize(Length constraintAnnotation) { this.length = constraintAnnotation.value(); @@ -31,13 +31,13 @@ public final class LengthValidator implements ConstraintValidator { +public final class LowerCaseValidator implements ConstraintValidator { @Override - public void initialize(LowerCase constraintAnnotation) { + public void initialize(Constraints.LowerCase constraintAnnotation) { } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { - + if (value == null) { - return true; + return true; } - + final int len = value.length(); for (int i = 0; i != len; ++i) { char c = value.charAt(i); @@ -41,14 +41,14 @@ public final class LowerCaseValidator implements ConstraintValidator= 'A' && ch <= 'Z'; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/MaxLengthValidator.java b/src/main/java/net/helenus/mapping/validator/MaxLengthValidator.java similarity index 79% rename from src/main/java/com/noorq/casser/mapping/validator/MaxLengthValidator.java rename to src/main/java/net/helenus/mapping/validator/MaxLengthValidator.java index f0fb598..53a3eac 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/MaxLengthValidator.java +++ b/src/main/java/net/helenus/mapping/validator/MaxLengthValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,31 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.MaxLength; +import net.helenus.mapping.annotation.Constraints; -public final class MaxLengthValidator implements ConstraintValidator, SizeConstraint { +public final class MaxLengthValidator implements ConstraintValidator, SizeConstraint { int maxLength; - + @Override - public void initialize(MaxLength constraintAnnotation) { + public void initialize(Constraints.MaxLength constraintAnnotation) { this.maxLength = constraintAnnotation.value(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { - + int[] size = getSize(value); - + if (size == null || size.length == 0) { return true; } - + return size[0] <= maxLength; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/MinLengthValidator.java b/src/main/java/net/helenus/mapping/validator/MinLengthValidator.java similarity index 79% rename from src/main/java/com/noorq/casser/mapping/validator/MinLengthValidator.java rename to src/main/java/net/helenus/mapping/validator/MinLengthValidator.java index 8d5378b..3293bac 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/MinLengthValidator.java +++ b/src/main/java/net/helenus/mapping/validator/MinLengthValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,31 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.MinLength; +import net.helenus.mapping.annotation.Constraints; -public final class MinLengthValidator implements ConstraintValidator, SizeConstraint { +public final class MinLengthValidator implements ConstraintValidator, SizeConstraint { int minLength; - + @Override - public void initialize(MinLength constraintAnnotation) { + public void initialize(Constraints.MinLength constraintAnnotation) { this.minLength = constraintAnnotation.value(); } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { - + int[] size = getSize(value); - + if (size == null || size.length == 0) { return true; } - + return size[0] >= minLength; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/NotEmptyValidator.java b/src/main/java/net/helenus/mapping/validator/NotEmptyValidator.java similarity index 83% rename from src/main/java/com/noorq/casser/mapping/validator/NotEmptyValidator.java rename to src/main/java/net/helenus/mapping/validator/NotEmptyValidator.java index 3bec200..722cee1 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/NotEmptyValidator.java +++ b/src/main/java/net/helenus/mapping/validator/NotEmptyValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints; -import com.noorq.casser.mapping.annotation.Constraints.NotEmpty; +import net.helenus.mapping.annotation.Constraints; +import net.helenus.mapping.annotation.Constraints.NotEmpty; public final class NotEmptyValidator implements ConstraintValidator, SizeConstraint { @@ -29,17 +29,17 @@ public final class NotEmptyValidator implements ConstraintValidator 0; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/NotNullValidator.java b/src/main/java/net/helenus/mapping/validator/NotNullValidator.java similarity index 82% rename from src/main/java/com/noorq/casser/mapping/validator/NotNullValidator.java rename to src/main/java/net/helenus/mapping/validator/NotNullValidator.java index d52e7f1..ccc049d 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/NotNullValidator.java +++ b/src/main/java/net/helenus/mapping/validator/NotNullValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints; -import com.noorq.casser.mapping.annotation.Constraints.NotNull; +import net.helenus.mapping.annotation.Constraints; +import net.helenus.mapping.annotation.Constraints.NotNull; public final class NotNullValidator implements ConstraintValidator { diff --git a/src/main/java/com/noorq/casser/mapping/validator/NumberValidator.java b/src/main/java/net/helenus/mapping/validator/NumberValidator.java similarity index 70% rename from src/main/java/com/noorq/casser/mapping/validator/NumberValidator.java rename to src/main/java/net/helenus/mapping/validator/NumberValidator.java index b3ea36c..8fb4251 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/NumberValidator.java +++ b/src/main/java/net/helenus/mapping/validator/NumberValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,41 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.Number; +import net.helenus.mapping.annotation.Constraints; -public class NumberValidator implements ConstraintValidator{ +public class NumberValidator implements ConstraintValidator { @Override - public void initialize(Number constraintAnnotation) { + public void initialize(Constraints.Number constraintAnnotation) { } @Override - public boolean isValid(CharSequence value, - ConstraintValidatorContext context) { - + public boolean isValid(CharSequence value, ConstraintValidatorContext context) { + if (value == null) { - return true; + return true; } - + final int len = value.length(); for (int i = 0; i != len; ++i) { - + char ch = value.charAt(i); - + if (!isNumber(ch)) { return false; } } - + return true; } - + private static boolean isNumber(char ch) { return ch >= '0' && ch <= '9'; } diff --git a/src/main/java/com/noorq/casser/mapping/validator/PatternValidator.java b/src/main/java/net/helenus/mapping/validator/PatternValidator.java similarity index 80% rename from src/main/java/com/noorq/casser/mapping/validator/PatternValidator.java rename to src/main/java/net/helenus/mapping/validator/PatternValidator.java index e3c3adc..2008fd0 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/PatternValidator.java +++ b/src/main/java/net/helenus/mapping/validator/PatternValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,32 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import java.util.regex.Pattern; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints; - +import net.helenus.mapping.annotation.Constraints; public final class PatternValidator implements ConstraintValidator { private Pattern pattern; - + @Override public void initialize(Constraints.Pattern constraintAnnotation) { - pattern = Pattern.compile(constraintAnnotation.value(), constraintAnnotation.flags()); + pattern = Pattern.compile(constraintAnnotation.value(), constraintAnnotation.flags()); } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { - + if (value == null) { - return true; + return true; } - + return pattern.matcher(value).matches(); } diff --git a/src/main/java/com/noorq/casser/mapping/validator/SizeConstraint.java b/src/main/java/net/helenus/mapping/validator/SizeConstraint.java similarity index 80% rename from src/main/java/com/noorq/casser/mapping/validator/SizeConstraint.java rename to src/main/java/net/helenus/mapping/validator/SizeConstraint.java index d7c427d..5930f1c 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/SizeConstraint.java +++ b/src/main/java/net/helenus/mapping/validator/SizeConstraint.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import java.lang.reflect.Array; import java.nio.ByteBuffer; @@ -23,38 +23,38 @@ import java.util.Map; public interface SizeConstraint { static final int[] EMPTY = new int[0]; - + default int[] getSize(Object value) { - + if (value == null) { return null; } - + if (value.getClass().isArray()) { - return new int[] { Array.getLength(value) }; + return new int[]{Array.getLength(value)}; } - + if (value instanceof CharSequence) { CharSequence seq = (CharSequence) value; - return new int[] { seq.length() }; + return new int[]{seq.length()}; } if (value instanceof ByteBuffer) { ByteBuffer bb = (ByteBuffer) value; - return new int[] { bb.position() }; + return new int[]{bb.position()}; } - + if (value instanceof Collection) { Collection col = (Collection) value; - return new int[] { col.size() }; + return new int[]{col.size()}; } - + if (value instanceof Map) { Map map = (Map) value; - return new int[] { map.size() }; + return new int[]{map.size()}; } - + return EMPTY; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/validator/UpperCaseValidator.java b/src/main/java/net/helenus/mapping/validator/UpperCaseValidator.java similarity index 76% rename from src/main/java/com/noorq/casser/mapping/validator/UpperCaseValidator.java rename to src/main/java/net/helenus/mapping/validator/UpperCaseValidator.java index e0b393e..b7041bf 100644 --- a/src/main/java/com/noorq/casser/mapping/validator/UpperCaseValidator.java +++ b/src/main/java/net/helenus/mapping/validator/UpperCaseValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,26 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.validator; +package net.helenus.mapping.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import com.noorq.casser.mapping.annotation.Constraints.UpperCase; +import net.helenus.mapping.annotation.Constraints; -public final class UpperCaseValidator implements ConstraintValidator { +public final class UpperCaseValidator implements ConstraintValidator { @Override - public void initialize(UpperCase constraintAnnotation) { + public void initialize(Constraints.UpperCase constraintAnnotation) { } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { - + if (value == null) { - return true; + return true; } - + final int len = value.length(); for (int i = 0; i != len; ++i) { char c = value.charAt(i); @@ -41,16 +41,16 @@ public final class UpperCaseValidator implements ConstraintValidator= 'a' && ch <= 'z'; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/BeanColumnValueProvider.java b/src/main/java/net/helenus/mapping/value/BeanColumnValueProvider.java similarity index 69% rename from src/main/java/com/noorq/casser/mapping/value/BeanColumnValueProvider.java rename to src/main/java/net/helenus/mapping/value/BeanColumnValueProvider.java index 647f58a..1ec8a51 100644 --- a/src/main/java/com/noorq/casser/mapping/value/BeanColumnValueProvider.java +++ b/src/main/java/net/helenus/mapping/value/BeanColumnValueProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,34 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.lang.reflect.Method; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.mapping.HelenusProperty; +import net.helenus.support.HelenusMappingException; public enum BeanColumnValueProvider implements ColumnValueProvider { INSTANCE; - + @Override - public V getColumnValue(Object bean, int columnIndexUnused, - CasserProperty property) { + public V getColumnValue(Object bean, int columnIndexUnused, HelenusProperty property) { Method getter = property.getGetterMethod(); - + Object value = null; try { - value = getter.invoke(bean, new Object[] {}); + value = getter.invoke(bean, new Object[]{}); } catch (ReflectiveOperationException e) { - throw new CasserMappingException("fail to call getter " + getter, e); + throw new HelenusMappingException("fail to call getter " + getter, e); } catch (IllegalArgumentException e) { - throw new CasserMappingException("invalid getter " + getter, e); + throw new HelenusMappingException("invalid getter " + getter, e); } - + return (V) value; - + } } diff --git a/src/main/java/net/helenus/mapping/value/ColumnValuePreparer.java b/src/main/java/net/helenus/mapping/value/ColumnValuePreparer.java new file mode 100644 index 0000000..e7bd647 --- /dev/null +++ b/src/main/java/net/helenus/mapping/value/ColumnValuePreparer.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.value; + +import com.datastax.driver.core.CodecRegistry; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TypeCodec; +import net.helenus.mapping.HelenusProperty; + +public interface ColumnValuePreparer { + + Object prepareColumnValue(Object source, HelenusProperty prop); + + default TypeCodec codecFor(DataType type) { + return CodecRegistry.DEFAULT_INSTANCE.codecFor(type); + } + +} diff --git a/src/main/java/net/helenus/mapping/value/ColumnValueProvider.java b/src/main/java/net/helenus/mapping/value/ColumnValueProvider.java new file mode 100644 index 0000000..000553b --- /dev/null +++ b/src/main/java/net/helenus/mapping/value/ColumnValueProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.mapping.value; + +import com.datastax.driver.core.CodecRegistry; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TypeCodec; +import net.helenus.mapping.HelenusProperty; + +public interface ColumnValueProvider { + + V getColumnValue(Object source, int columnIndex, HelenusProperty property); + + default TypeCodec codecFor(DataType type) { + return CodecRegistry.DEFAULT_INSTANCE.codecFor(type); + } +} diff --git a/src/main/java/com/noorq/casser/mapping/value/RowColumnValueProvider.java b/src/main/java/net/helenus/mapping/value/RowColumnValueProvider.java similarity index 66% rename from src/main/java/com/noorq/casser/mapping/value/RowColumnValueProvider.java rename to src/main/java/net/helenus/mapping/value/RowColumnValueProvider.java index 78edcc9..ee61085 100644 --- a/src/main/java/com/noorq/casser/mapping/value/RowColumnValueProvider.java +++ b/src/main/java/net/helenus/mapping/value/RowColumnValueProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,62 +13,59 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.nio.ByteBuffer; import java.util.List; import java.util.Optional; import java.util.function.Function; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ProtocolVersion; -import com.datastax.driver.core.Row; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; +import com.datastax.driver.core.*; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class RowColumnValueProvider implements ColumnValueProvider { private final SessionRepository repository; - + public RowColumnValueProvider(SessionRepository repository) { this.repository = repository; } - + @Override - public V getColumnValue(Object sourceObj, int columnIndex, CasserProperty property) { + public V getColumnValue(Object sourceObj, int columnIndex, HelenusProperty property) { Row source = (Row) sourceObj; - + Object value = null; if (columnIndex != -1) { value = readValueByIndex(source, columnIndex); - } - else { + } else { value = readValueByName(source, property.getColumnName().getName()); } if (value != null) { Optional> converter = property.getReadConverter(repository); - + if (converter.isPresent()) { value = converter.get().apply(value); } - + } return (V) value; } private Object readValueByIndex(Row source, int columnIndex) { - + if (source.isNull(columnIndex)) { return null; } - + ColumnDefinitions columnDefinitions = source.getColumnDefinitions(); - + DataType columnType = columnDefinitions.getType(columnIndex); if (columnType.isCollection()) { @@ -76,30 +73,31 @@ public final class RowColumnValueProvider implements ColumnValueProvider { List typeArguments = columnType.getTypeArguments(); switch (columnType.getName()) { - case SET: - return source.getSet(columnIndex, typeArguments.get(0).asJavaClass()); - case MAP: - return source.getMap(columnIndex, typeArguments.get(0).asJavaClass(), typeArguments.get(1).asJavaClass()); - case LIST: - return source.getList(columnIndex, typeArguments.get(0).asJavaClass()); + case SET : + return source.getSet(columnIndex, codecFor(typeArguments.get(0)).getJavaType()); + case MAP : + return source.getMap(columnIndex, codecFor(typeArguments.get(0)).getJavaType(), + codecFor(typeArguments.get(1)).getJavaType()); + case LIST : + return source.getList(columnIndex, codecFor(typeArguments.get(0)).getJavaType()); } } ByteBuffer bytes = source.getBytesUnsafe(columnIndex); - Object value = columnType.deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); + Object value = codecFor(columnType).deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); return value; } - + private Object readValueByName(Row source, String columnName) { - + if (source.isNull(columnName)) { return null; } - + ColumnDefinitions columnDefinitions = source.getColumnDefinitions(); - + DataType columnType = columnDefinitions.getType(columnName); if (columnType.isCollection()) { @@ -107,20 +105,21 @@ public final class RowColumnValueProvider implements ColumnValueProvider { List typeArguments = columnType.getTypeArguments(); switch (columnType.getName()) { - case SET: - return source.getSet(columnName, typeArguments.get(0).asJavaClass()); - case MAP: - return source.getMap(columnName, typeArguments.get(0).asJavaClass(), typeArguments.get(1).asJavaClass()); - case LIST: - return source.getList(columnName, typeArguments.get(0).asJavaClass()); + case SET : + return source.getSet(columnName, codecFor(typeArguments.get(0)).getJavaType()); + case MAP : + return source.getMap(columnName, codecFor(typeArguments.get(0)).getJavaType(), + codecFor(typeArguments.get(1)).getJavaType()); + case LIST : + return source.getList(columnName, codecFor(typeArguments.get(0)).getJavaType()); } } ByteBuffer bytes = source.getBytesUnsafe(columnName); - Object value = columnType.deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); + Object value = codecFor(columnType).deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); return value; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/StatementColumnValuePreparer.java b/src/main/java/net/helenus/mapping/value/StatementColumnValuePreparer.java similarity index 77% rename from src/main/java/com/noorq/casser/mapping/value/StatementColumnValuePreparer.java rename to src/main/java/net/helenus/mapping/value/StatementColumnValuePreparer.java index 9f03a41..60ee3b0 100644 --- a/src/main/java/com/noorq/casser/mapping/value/StatementColumnValuePreparer.java +++ b/src/main/java/net/helenus/mapping/value/StatementColumnValuePreparer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.util.Optional; import java.util.function.Function; import com.datastax.driver.core.querybuilder.BindMarker; -import com.noorq.casser.core.CasserValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; +import net.helenus.core.HelenusValidator; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class StatementColumnValuePreparer implements ColumnValuePreparer { @@ -31,16 +31,16 @@ public final class StatementColumnValuePreparer implements ColumnValuePreparer { public StatementColumnValuePreparer(SessionRepository repository) { this.repository = repository; } - + @Override - public Object prepareColumnValue(Object value, CasserProperty prop) { + public Object prepareColumnValue(Object value, HelenusProperty prop) { if (value instanceof BindMarker) { return value; } - - CasserValidator.INSTANCE.validate(prop, value); - + + HelenusValidator.INSTANCE.validate(prop, value); + if (value != null) { Optional> converter = prop.getWriteConverter(repository); @@ -53,5 +53,5 @@ public final class StatementColumnValuePreparer implements ColumnValuePreparer { return value; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/TupleColumnValuePreparer.java b/src/main/java/net/helenus/mapping/value/TupleColumnValuePreparer.java similarity index 71% rename from src/main/java/com/noorq/casser/mapping/value/TupleColumnValuePreparer.java rename to src/main/java/net/helenus/mapping/value/TupleColumnValuePreparer.java index 560dc59..930994a 100644 --- a/src/main/java/com/noorq/casser/mapping/value/TupleColumnValuePreparer.java +++ b/src/main/java/net/helenus/mapping/value/TupleColumnValuePreparer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.util.Optional; import java.util.function.Function; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ProtocolVersion; -import com.datastax.driver.core.TupleType; +import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.BindMarker; -import com.noorq.casser.core.CasserValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; + +import net.helenus.core.HelenusValidator; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class TupleColumnValuePreparer implements ColumnValuePreparer { @@ -35,16 +34,16 @@ public final class TupleColumnValuePreparer implements ColumnValuePreparer { this.tupleType = tupleType; this.repository = repository; } - + @Override - public Object prepareColumnValue(Object value, CasserProperty prop) { - + public Object prepareColumnValue(Object value, HelenusProperty prop) { + if (value instanceof BindMarker) { return value; } - - CasserValidator.INSTANCE.validate(prop, value); - + + HelenusValidator.INSTANCE.validate(prop, value); + if (value != null) { Optional> converter = prop.getWriteConverter(repository); @@ -54,13 +53,13 @@ public final class TupleColumnValuePreparer implements ColumnValuePreparer { } int columnIndex = prop.getOrdinal(); - + DataType dataType = tupleType.getComponentTypes().get(columnIndex); - - return dataType.serialize(value, ProtocolVersion.NEWEST_SUPPORTED); + + return codecFor(dataType).serialize(value, ProtocolVersion.NEWEST_SUPPORTED); } return null; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/TupleColumnValueProvider.java b/src/main/java/net/helenus/mapping/value/TupleColumnValueProvider.java similarity index 83% rename from src/main/java/com/noorq/casser/mapping/value/TupleColumnValueProvider.java rename to src/main/java/net/helenus/mapping/value/TupleColumnValueProvider.java index aae5c3e..4642bf0 100644 --- a/src/main/java/com/noorq/casser/mapping/value/TupleColumnValueProvider.java +++ b/src/main/java/net/helenus/mapping/value/TupleColumnValueProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.nio.ByteBuffer; import java.util.Optional; @@ -23,24 +23,25 @@ import com.datastax.driver.core.DataType; import com.datastax.driver.core.ProtocolVersion; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class TupleColumnValueProvider implements ColumnValueProvider { private final SessionRepository repository; - + public TupleColumnValueProvider(SessionRepository repository) { this.repository = repository; } - + @Override - public V getColumnValue(Object sourceObj, int columnIndexUnused, CasserProperty property) { + public V getColumnValue(Object sourceObj, int columnIndexUnused, HelenusProperty property) { int columnIndex = property.getOrdinal(); - + TupleValue source = (TupleValue) sourceObj; - + ByteBuffer bytes = source.getBytesUnsafe(columnIndex); if (bytes == null) { return null; @@ -49,19 +50,19 @@ public final class TupleColumnValueProvider implements ColumnValueProvider { TupleType tupleType = source.getType(); DataType fieldType = tupleType.getComponentTypes().get(columnIndex); - Object value = fieldType.deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); - + Object value = codecFor(fieldType).deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); + if (value != null) { Optional> converter = property.getReadConverter(repository); - + if (converter.isPresent()) { value = converter.get().apply(value); } - + } - + return (V) value; - + } } diff --git a/src/main/java/com/noorq/casser/mapping/value/UDTColumnValuePreparer.java b/src/main/java/net/helenus/mapping/value/UDTColumnValuePreparer.java similarity index 70% rename from src/main/java/com/noorq/casser/mapping/value/UDTColumnValuePreparer.java rename to src/main/java/net/helenus/mapping/value/UDTColumnValuePreparer.java index 4a2a4df..8a2ee01 100644 --- a/src/main/java/com/noorq/casser/mapping/value/UDTColumnValuePreparer.java +++ b/src/main/java/net/helenus/mapping/value/UDTColumnValuePreparer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.util.Optional; import java.util.function.Function; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ProtocolVersion; -import com.datastax.driver.core.UserType; +import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.BindMarker; -import com.noorq.casser.core.CasserValidator; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; + +import net.helenus.core.HelenusValidator; +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class UDTColumnValuePreparer implements ColumnValuePreparer { @@ -35,16 +34,16 @@ public final class UDTColumnValuePreparer implements ColumnValuePreparer { this.userType = userType; this.repository = repository; } - + @Override - public Object prepareColumnValue(Object value, CasserProperty prop) { + public Object prepareColumnValue(Object value, HelenusProperty prop) { if (value instanceof BindMarker) { return value; } - - CasserValidator.INSTANCE.validate(prop, value); - + + HelenusValidator.INSTANCE.validate(prop, value); + if (value != null) { Optional> converter = prop.getWriteConverter(repository); @@ -54,11 +53,11 @@ public final class UDTColumnValuePreparer implements ColumnValuePreparer { } DataType dataType = userType.getFieldType(prop.getColumnName().getName()); - - return dataType.serialize(value, ProtocolVersion.NEWEST_SUPPORTED); + + return codecFor(dataType).serialize(value, ProtocolVersion.NEWEST_SUPPORTED); } return null; } - + } diff --git a/src/main/java/com/noorq/casser/mapping/value/UDTColumnValueProvider.java b/src/main/java/net/helenus/mapping/value/UDTColumnValueProvider.java similarity index 83% rename from src/main/java/com/noorq/casser/mapping/value/UDTColumnValueProvider.java rename to src/main/java/net/helenus/mapping/value/UDTColumnValueProvider.java index 92b3fb7..36e0455 100644 --- a/src/main/java/com/noorq/casser/mapping/value/UDTColumnValueProvider.java +++ b/src/main/java/net/helenus/mapping/value/UDTColumnValueProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.nio.ByteBuffer; import java.util.Optional; @@ -23,45 +23,46 @@ import com.datastax.driver.core.DataType; import com.datastax.driver.core.ProtocolVersion; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.SessionRepository; -import com.noorq.casser.mapping.CasserProperty; + +import net.helenus.core.SessionRepository; +import net.helenus.mapping.HelenusProperty; public final class UDTColumnValueProvider implements ColumnValueProvider { private final SessionRepository repository; - + public UDTColumnValueProvider(SessionRepository repository) { this.repository = repository; } - + @Override - public V getColumnValue(Object sourceObj, int columnIndexUnused, CasserProperty property) { + public V getColumnValue(Object sourceObj, int columnIndexUnused, HelenusProperty property) { UDTValue source = (UDTValue) sourceObj; - + UserType userType = source.getType(); - + String name = property.getColumnName().getName(); - + ByteBuffer bytes = source.getBytesUnsafe(name); if (bytes == null) { return null; } - + DataType fieldType = userType.getFieldType(name); - Object value = fieldType.deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); - + Object value = codecFor(fieldType).deserialize(bytes, ProtocolVersion.NEWEST_SUPPORTED); + if (value != null) { Optional> converter = property.getReadConverter(repository); - + if (converter.isPresent()) { value = converter.get().apply(value); } - + } - + return (V) value; - + } } diff --git a/src/main/java/com/noorq/casser/mapping/value/ValueProviderMap.java b/src/main/java/net/helenus/mapping/value/ValueProviderMap.java similarity index 85% rename from src/main/java/com/noorq/casser/mapping/value/ValueProviderMap.java rename to src/main/java/net/helenus/mapping/value/ValueProviderMap.java index 2abc89e..daf5677 100644 --- a/src/main/java/com/noorq/casser/mapping/value/ValueProviderMap.java +++ b/src/main/java/net/helenus/mapping/value/ValueProviderMap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,46 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.mapping.value; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.support.CasserMappingException; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusProperty; +import net.helenus.support.HelenusMappingException; public final class ValueProviderMap implements Map { private final Object source; private final ColumnValueProvider valueProvider; - private final CasserEntity entity; - - public ValueProviderMap(Object source, ColumnValueProvider valueProvider, CasserEntity entity) { + private final HelenusEntity entity; + + public ValueProviderMap(Object source, ColumnValueProvider valueProvider, HelenusEntity entity) { this.source = source; this.valueProvider = valueProvider; this.entity = entity; } - + @Override public Object get(Object key) { if (key instanceof String) { String name = (String) key; - CasserProperty prop = entity.getProperty(name); + HelenusProperty prop = entity.getProperty(name); if (prop != null) { return valueProvider.getColumnValue(source, -1, prop); } } return null; } - + @Override public Set keySet() { return entity.getOrderedProperties().stream().map(p -> p.getPropertyName()).collect(Collectors.toSet()); } - + @Override public int size() { return entity.getOrderedProperties().size(); @@ -113,12 +113,12 @@ public final class ValueProviderMap implements Map { } private void throwShouldNeverCall() { - throw new CasserMappingException("should never be called"); + throw new HelenusMappingException("should never be called"); } @Override public String toString() { return source.toString(); } - + } diff --git a/src/main/java/com/noorq/casser/support/CqlUtil.java b/src/main/java/net/helenus/support/CqlUtil.java similarity index 90% rename from src/main/java/com/noorq/casser/support/CqlUtil.java rename to src/main/java/net/helenus/support/CqlUtil.java index aa7f5c8..0d2e50b 100644 --- a/src/main/java/com/noorq/casser/support/CqlUtil.java +++ b/src/main/java/net/helenus/support/CqlUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; public final class CqlUtil { @@ -21,15 +21,15 @@ public final class CqlUtil { } public static String forceQuote(String identity) { - + if (identity == null) { return null; } - + if (identity.startsWith("\"")) { return identity; } return "\"" + identity + "\""; } - + } diff --git a/src/main/java/com/noorq/casser/support/DslPropertyException.java b/src/main/java/net/helenus/support/DslPropertyException.java similarity index 65% rename from src/main/java/com/noorq/casser/support/DslPropertyException.java rename to src/main/java/net/helenus/support/DslPropertyException.java index f8faa7b..8869911 100644 --- a/src/main/java/com/noorq/casser/support/DslPropertyException.java +++ b/src/main/java/net/helenus/support/DslPropertyException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; -import com.noorq.casser.core.reflect.CasserPropertyNode; +import net.helenus.core.reflect.HelenusPropertyNode; -public final class DslPropertyException extends CasserException { +public final class DslPropertyException extends HelenusException { private static final long serialVersionUID = -2745598205929757758L; - private final CasserPropertyNode propertyNode; - - public DslPropertyException(CasserPropertyNode propertyNode) { + private final HelenusPropertyNode propertyNode; + + public DslPropertyException(HelenusPropertyNode propertyNode) { super("DSL PropertyNode Exception"); this.propertyNode = propertyNode; } - public CasserPropertyNode getPropertyNode() { + public HelenusPropertyNode getPropertyNode() { return propertyNode; } diff --git a/src/main/java/com/noorq/casser/support/Either.java b/src/main/java/net/helenus/support/Either.java similarity index 82% rename from src/main/java/com/noorq/casser/support/Either.java rename to src/main/java/net/helenus/support/Either.java index 228c629..e7eb613 100644 --- a/src/main/java/com/noorq/casser/support/Either.java +++ b/src/main/java/net/helenus/support/Either.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.util.function.Function; @@ -21,16 +21,16 @@ public final class Either { private final L left; private final R right; - + private Either(L left, R right) { this.left = left; this.right = right; } - + public boolean isLeft() { return left != null; } - + public L getLeft() { return left; } @@ -54,19 +54,18 @@ public final class Either { public EitherCase getCase() { if (left != null) { return EitherCase.LEFT; - } - else if (right != null) { + } else if (right != null) { return EitherCase.RIGHT; } throw new IllegalStateException("unexpected state"); } - - public T fold(Function leftFunction, Function rightFunction) { - switch(getCase()) { - case LEFT: - return leftFunction.apply(left); - case RIGHT: - return rightFunction.apply(right); + + public T fold(Function leftFunction, Function rightFunction) { + switch (getCase()) { + case LEFT : + return leftFunction.apply(left); + case RIGHT : + return rightFunction.apply(right); } throw new IllegalStateException("unexpected state"); } @@ -78,7 +77,5 @@ public final class Either { } return "[," + right + "]"; } - - - + } diff --git a/src/main/java/com/noorq/casser/support/EitherCase.java b/src/main/java/net/helenus/support/EitherCase.java similarity index 88% rename from src/main/java/com/noorq/casser/support/EitherCase.java rename to src/main/java/net/helenus/support/EitherCase.java index 39c11a7..9ca0db1 100644 --- a/src/main/java/com/noorq/casser/support/EitherCase.java +++ b/src/main/java/net/helenus/support/EitherCase.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; public enum EitherCase { LEFT, RIGHT; -} \ No newline at end of file +} diff --git a/src/main/java/com/noorq/casser/support/Fun.java b/src/main/java/net/helenus/support/Fun.java similarity index 92% rename from src/main/java/com/noorq/casser/support/Fun.java rename to src/main/java/net/helenus/support/Fun.java index 320655a..e5a0408 100644 --- a/src/main/java/com/noorq/casser/support/Fun.java +++ b/src/main/java/net/helenus/support/Fun.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,25 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.util.Arrays; - - public final class Fun { private Fun() { } - + public final static class ArrayTuple { - + public final Object[] _a; - + public ArrayTuple(Object[] a) { this._a = a; } - + public static ArrayTuple of(Object[] a) { return new ArrayTuple(a); } @@ -40,9 +38,9 @@ public final class Fun { public String toString() { return "ArrayTuple " + Arrays.toString(_a); } - + } - + public final static class Tuple1 { public final A _1; @@ -59,9 +57,9 @@ public final class Fun { public String toString() { return "Tuple1 [_1=" + _1 + "]"; } - + } - + public final static class Tuple2 { public final A _1; @@ -75,14 +73,14 @@ public final class Fun { public static Tuple2 of(A _1, B _2) { return new Tuple2(_1, _2); } - + @Override public String toString() { return "Tuple2 [_1=" + _1 + ", _2=" + _2 + "]"; } - + } - + public final static class Tuple3 { public final A _1; @@ -94,26 +92,25 @@ public final class Fun { this._2 = v2; this._3 = v3; } - + public static Tuple3 of(A _1, B _2, C _3) { return new Tuple3(_1, _2, _3); } - + @Override public String toString() { return "Tuple3 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + "]"; } - - } - - + + } + public final static class Tuple4 { public final A _1; public final B _2; public final C _3; public final D _4; - + public Tuple4(A v1, B v2, C v3, D v4) { this._1 = v1; this._2 = v2; @@ -127,13 +124,11 @@ public final class Fun { @Override public String toString() { - return "Tuple4 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 - + "]"; + return "Tuple4 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 + "]"; } } - - + public final static class Tuple5 { public final A _1; @@ -141,7 +136,7 @@ public final class Fun { public final C _3; public final D _4; public final E _5; - + public Tuple5(A v1, B v2, C v3, D v4, E v5) { this._1 = v1; this._2 = v2; @@ -149,19 +144,18 @@ public final class Fun { this._4 = v4; this._5 = v5; } - + public static Tuple5 of(A _1, B _2, C _3, D _4, E _5) { return new Tuple5(_1, _2, _3, _4, _5); } @Override public String toString() { - return "Tuple5 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 - + ", _5=" + _5 + "]"; + return "Tuple5 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 + ", _5=" + _5 + "]"; } - } - + } + public final static class Tuple6 { public final A _1; @@ -170,7 +164,7 @@ public final class Fun { public final D _4; public final E _5; public final F _6; - + public Tuple6(A v1, B v2, C v3, D v4, E v5, F v6) { this._1 = v1; this._2 = v2; @@ -179,19 +173,18 @@ public final class Fun { this._5 = v5; this._6 = v6; } - + public static Tuple6 of(A _1, B _2, C _3, D _4, E _5, F _6) { return new Tuple6(_1, _2, _3, _4, _5, _6); } @Override public String toString() { - return "Tuple6 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 - + ", _5=" + _5 + ", _6=" + _6 + "]"; + return "Tuple6 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 + ", _5=" + _5 + ", _6=" + _6 + "]"; } } - + public final static class Tuple7 { public final A _1; @@ -201,7 +194,7 @@ public final class Fun { public final E _5; public final F _6; public final G _7; - + public Tuple7(A v1, B v2, C v3, D v4, E v5, F v6, G v7) { this._1 = v1; this._2 = v2; @@ -211,15 +204,15 @@ public final class Fun { this._6 = v6; this._7 = v7; } - + public static Tuple7 of(A _1, B _2, C _3, D _4, E _5, F _6, G _7) { return new Tuple7(_1, _2, _3, _4, _5, _6, _7); } @Override public String toString() { - return "Tuple7 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 - + ", _5=" + _5 + ", _6=" + _6 + ", _7=" + _7 + "]"; + return "Tuple7 [_1=" + _1 + ", _2=" + _2 + ", _3=" + _3 + ", _4=" + _4 + ", _5=" + _5 + ", _6=" + _6 + + ", _7=" + _7 + "]"; } } diff --git a/src/main/java/com/noorq/casser/support/CasserException.java b/src/main/java/net/helenus/support/HelenusException.java similarity index 70% rename from src/main/java/com/noorq/casser/support/CasserException.java rename to src/main/java/net/helenus/support/HelenusException.java index 08974f9..a677b03 100644 --- a/src/main/java/com/noorq/casser/support/CasserException.java +++ b/src/main/java/net/helenus/support/HelenusException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; -public class CasserException extends RuntimeException { +public class HelenusException extends RuntimeException { private static final long serialVersionUID = 7711799134283942588L; - public CasserException(String msg) { + public HelenusException(String msg) { super(msg); } - public CasserException(Throwable t) { + public HelenusException(Throwable t) { super(t); } - public CasserException(String msg, Throwable t) { + public HelenusException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/src/main/java/com/noorq/casser/support/CasserMappingException.java b/src/main/java/net/helenus/support/HelenusMappingException.java similarity index 70% rename from src/main/java/com/noorq/casser/support/CasserMappingException.java rename to src/main/java/net/helenus/support/HelenusMappingException.java index 9ddafa2..dbef9d0 100644 --- a/src/main/java/com/noorq/casser/support/CasserMappingException.java +++ b/src/main/java/net/helenus/support/HelenusMappingException.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; -public class CasserMappingException extends CasserException { +public class HelenusMappingException extends HelenusException { private static final long serialVersionUID = -4730562130753392363L; - public CasserMappingException(String msg) { + public HelenusMappingException(String msg) { super(msg); } - public CasserMappingException(Throwable t) { + public HelenusMappingException(Throwable t) { super(t); } - public CasserMappingException(String msg, Throwable t) { + public HelenusMappingException(String msg, Throwable t) { super(msg, t); } - + } diff --git a/src/main/java/com/noorq/casser/support/Immutables.java b/src/main/java/net/helenus/support/Immutables.java similarity index 87% rename from src/main/java/com/noorq/casser/support/Immutables.java rename to src/main/java/net/helenus/support/Immutables.java index b82e171..94d6e13 100644 --- a/src/main/java/com/noorq/casser/support/Immutables.java +++ b/src/main/java/net/helenus/support/Immutables.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,39 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; +import java.util.*; public final class Immutables { private Immutables() { } - + public static Set setOf(T value) { return new SingleEntrySet(value); } - + public static List listOf(T value) { return new SingleEntryList(value); } - + public static Map mapOf(K key, V value) { return new SingleEntryMap(key, value); } - + static class SingleEntryIterator implements Iterator { - + T entry; boolean processed = false; - + SingleEntryIterator(T entry) { this.entry = entry; } @@ -62,9 +55,9 @@ public final class Immutables { } } - + static class SingleEntryListIterator extends SingleEntryIterator implements ListIterator { - + SingleEntryListIterator(T entry) { super(entry); } @@ -106,15 +99,15 @@ public final class Immutables { } } - + static class SingleEntryCollection implements Collection { final T entry; - - SingleEntryCollection( T entry) { + + SingleEntryCollection(T entry) { this.entry = entry; } - + @Override public int size() { return 1; @@ -140,7 +133,7 @@ public final class Immutables { @Override public Object[] toArray() { - return new Object[] { entry }; + return new Object[]{entry}; } @Override @@ -193,18 +186,18 @@ public final class Immutables { public void clear() { throw new UnsupportedOperationException(); } - + } - - static final class SingleEntrySet extends SingleEntryCollection implements Set { - + + static final class SingleEntrySet extends SingleEntryCollection implements Set { + SingleEntrySet(T entry) { super(entry); } } - static final class SingleEntryList extends SingleEntryCollection implements List { + static final class SingleEntryList extends SingleEntryCollection implements List { SingleEntryList(T entry) { super(entry); @@ -266,32 +259,28 @@ public final class Immutables { if (fromIndex == 0) { if (toIndex == 0) { return Collections.emptyList(); - } - else if (toIndex == 1) { + } else if (toIndex == 1) { return this; - } - else { + } else { throw new IndexOutOfBoundsException(); } - } - else if (fromIndex == 1 && toIndex == 1) { + } else if (fromIndex == 1 && toIndex == 1) { return Collections.emptyList(); - } - else { + } else { throw new IndexOutOfBoundsException(); } } - - } - - static final class SingleEntryMap implements Map { - final K key; - final V value; - - SingleEntryMap(K key, V value) { - this.key = key; - this.value = value; + } + + static final class SingleEntryMap implements Map { + + final K key; + final V value; + + SingleEntryMap(K key, V value) { + this.key = key; + this.value = value; } @Override diff --git a/src/main/java/com/noorq/casser/support/Mutable.java b/src/main/java/net/helenus/support/Mutable.java similarity index 90% rename from src/main/java/com/noorq/casser/support/Mutable.java rename to src/main/java/net/helenus/support/Mutable.java index 7a0e81b..9a44d99 100644 --- a/src/main/java/com/noorq/casser/support/Mutable.java +++ b/src/main/java/net/helenus/support/Mutable.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; public final class Mutable { private volatile T value; - + public Mutable(T initialValue) { this.value = initialValue; } - + public T get() { return value; } - + public void set(T value) { this.value = value; } diff --git a/src/main/java/com/noorq/casser/support/PackageUtil.java b/src/main/java/net/helenus/support/PackageUtil.java similarity index 72% rename from src/main/java/com/noorq/casser/support/PackageUtil.java rename to src/main/java/net/helenus/support/PackageUtil.java index ed1e8e3..2a0917c 100644 --- a/src/main/java/com/noorq/casser/support/PackageUtil.java +++ b/src/main/java/net/helenus/support/PackageUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.io.File; import java.io.IOException; @@ -29,67 +29,55 @@ import java.util.jar.JarFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class PackageUtil { private static final Logger log = LoggerFactory.getLogger(PackageUtil.class); public static final String JAR_URL_SEPARATOR = "!/"; - private static void doFetchInPath(Set> classes, File directory, - String packageName, ClassLoader classLoader) - throws ClassNotFoundException { + private static void doFetchInPath(Set> classes, File directory, String packageName, + ClassLoader classLoader) throws ClassNotFoundException { File[] dirContents = directory.listFiles(); if (dirContents == null) { - throw new ClassNotFoundException("invalid directory " - + directory.getAbsolutePath()); + throw new ClassNotFoundException("invalid directory " + directory.getAbsolutePath()); } for (File file : dirContents) { String fileName = file.getName(); if (file.isDirectory()) { - doFetchInPath(classes, file, packageName + "." + fileName, - classLoader); + doFetchInPath(classes, file, packageName + "." + fileName, classLoader); } else if (fileName.endsWith(".class")) { - classes.add(classLoader.loadClass(packageName + '.' - + fileName.substring(0, fileName.length() - 6))); + classes.add(classLoader.loadClass(packageName + '.' + fileName.substring(0, fileName.length() - 6))); } } } - public static Set> getClasses(String packagePath) - throws ClassNotFoundException { + public static Set> getClasses(String packagePath) throws ClassNotFoundException { Set> classes = new HashSet>(); - ClassLoader classLoader = Thread.currentThread() - .getContextClassLoader(); + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { - throw new ClassNotFoundException( - "class loader not found for current thread"); + throw new ClassNotFoundException("class loader not found for current thread"); } Enumeration resources = null; try { resources = classLoader.getResources(packagePath.replace('.', '/')); } catch (IOException e) { - throw new ClassNotFoundException("invalid package " + packagePath, - e); + throw new ClassNotFoundException("invalid package " + packagePath, e); } while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url == null) { - throw new ClassNotFoundException(packagePath - + " - package not found"); + throw new ClassNotFoundException(packagePath + " - package not found"); } String dirPath = fastReplace(url.getFile(), "%20", " "); int jarSeparator = dirPath.indexOf(JAR_URL_SEPARATOR); if (jarSeparator == -1) { File directory = new File(dirPath); if (!directory.exists()) { - throw new ClassNotFoundException(packagePath - + " - invalid package"); + throw new ClassNotFoundException(packagePath + " - invalid package"); } doFetchInPath(classes, directory, packagePath, classLoader); } else { - String rootEntry = dirPath.substring(jarSeparator - + JAR_URL_SEPARATOR.length()); + String rootEntry = dirPath.substring(jarSeparator + JAR_URL_SEPARATOR.length()); if (!"".equals(rootEntry) && !rootEntry.endsWith("/")) { rootEntry = rootEntry + "/"; } @@ -105,16 +93,13 @@ public class PackageUtil { jarName = fastReplace(jarName, " ", "%20"); jarFile = new JarFile(jarName); } - for (Enumeration entries = jarFile.entries(); entries - .hasMoreElements();) { + for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String fileName = entry.getName(); - if (fileName.startsWith(rootEntry) - && fileName.endsWith(".class")) { + if (fileName.startsWith(rootEntry) && fileName.endsWith(".class")) { fileName = fileName.replace('/', '.'); try { - classes.add(classLoader.loadClass(fileName - .substring(0, fileName.length() - 6))); + classes.add(classLoader.loadClass(fileName.substring(0, fileName.length() - 6))); } catch (ClassNotFoundException e) { log.error("class load fail", e); } @@ -128,8 +113,7 @@ public class PackageUtil { return classes; } - public static String fastReplace(String inString, String oldPattern, - String newPattern) { + public static String fastReplace(String inString, String oldPattern, String newPattern) { if (inString == null) { return null; } diff --git a/src/main/java/com/noorq/casser/support/Requires.java b/src/main/java/net/helenus/support/Requires.java similarity index 92% rename from src/main/java/com/noorq/casser/support/Requires.java rename to src/main/java/net/helenus/support/Requires.java index 6699c67..e399946 100644 --- a/src/main/java/com/noorq/casser/support/Requires.java +++ b/src/main/java/net/helenus/support/Requires.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.lang.reflect.Array; import java.util.Objects; - public final class Requires { private Requires() { @@ -31,5 +30,5 @@ public final class Requires { Objects.requireNonNull(Array.get(arr, i), "element " + i + " is empty in array"); } } - + } diff --git a/src/main/java/net/helenus/support/Scala.java b/src/main/java/net/helenus/support/Scala.java new file mode 100644 index 0000000..7486b08 --- /dev/null +++ b/src/main/java/net/helenus/support/Scala.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.support; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; + +import scala.concurrent.Future; +import scala.concurrent.impl.Promise.DefaultPromise; + +public final class Scala { + + public static Future asFuture(ListenableFuture future) { + final scala.concurrent.Promise promise = new DefaultPromise(); + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(T result) { + promise.success(result); + } + @Override + public void onFailure(Throwable t) { + promise.failure(t); + } + }); + return promise.future(); + } + + public static Future> asFuture(ListenableFuture future, A a) { + final scala.concurrent.Promise> promise = new DefaultPromise>(); + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(T result) { + promise.success(new Fun.Tuple2(result, a)); + } + @Override + public void onFailure(Throwable t) { + promise.failure(t); + } + }); + return promise.future(); + } + + public static Future> asFuture(ListenableFuture future, A a, B b) { + final scala.concurrent.Promise> promise = new DefaultPromise>(); + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(T result) { + promise.success(new Fun.Tuple3(result, a, b)); + } + @Override + public void onFailure(Throwable t) { + promise.failure(t); + } + }); + return promise.future(); + } + + public static Future> asFuture(ListenableFuture future, A a, B b, C c) { + final scala.concurrent.Promise> promise = new DefaultPromise>(); + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(T result) { + promise.success(new Fun.Tuple4(result, a, b, c)); + } + @Override + public void onFailure(Throwable t) { + promise.failure(t); + } + }); + return promise.future(); + } + + public static Future> asFuture(ListenableFuture future, A a, B b, C c, + D d) { + final scala.concurrent.Promise> promise = new DefaultPromise>(); + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(T result) { + promise.success(new Fun.Tuple5(result, a, b, c, d)); + } + @Override + public void onFailure(Throwable t) { + promise.failure(t); + } + }); + return promise.future(); + } + +} diff --git a/src/main/java/com/noorq/casser/support/Timeuuid.java b/src/main/java/net/helenus/support/Timeuuid.java similarity index 96% rename from src/main/java/com/noorq/casser/support/Timeuuid.java rename to src/main/java/net/helenus/support/Timeuuid.java index b28e6a9..d417f10 100644 --- a/src/main/java/com/noorq/casser/support/Timeuuid.java +++ b/src/main/java/net/helenus/support/Timeuuid.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.security.SecureRandom; import java.util.Date; @@ -48,7 +48,7 @@ public final class Timeuuid { public static UUID minOf(long timestampMillis) { return new UuidBuilder().addVersion(1).addTimestampMillis(timestampMillis).setMinClockSeqAndNode().build(); } - + public static UUID minOf(Date date) { return minOf(date.getTime()); } @@ -56,7 +56,7 @@ public final class Timeuuid { public static UUID maxOf(long timestampMillis) { return new UuidBuilder().addVersion(1).addTimestampMillis(timestampMillis).setMaxClockSeqAndNode().build(); } - + public static UUID maxOf(Date date) { return maxOf(date.getTime()); } diff --git a/src/main/java/com/noorq/casser/support/Transformers.java b/src/main/java/net/helenus/support/Transformers.java similarity index 86% rename from src/main/java/com/noorq/casser/support/Transformers.java rename to src/main/java/net/helenus/support/Transformers.java index 8436396..faa4a97 100644 --- a/src/main/java/com/noorq/casser/support/Transformers.java +++ b/src/main/java/net/helenus/support/Transformers.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; -import java.util.AbstractList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; +import java.util.*; import java.util.function.Function; import com.google.common.collect.Maps; @@ -37,11 +33,11 @@ public final class Transformers { } return set; } - + public static List transformList(List inputList, Function func) { return new TransformedImmutableList(inputList, func); } - + public static Map transformMapKey(Map inputMap, Function func) { Map map = Maps.newHashMap(); for (Map.Entry e : inputMap.entrySet()) { @@ -53,21 +49,21 @@ public final class Transformers { public static Map transformMapValue(Map inputMap, Function func) { return Maps.transformValues(inputMap, func::apply); } - - public static Map transformMap(Map inputMap, Function funcKey, Function funcValue) { + + public static Map transformMap(Map inputMap, Function funcKey, + Function funcValue) { Map map = Maps.newHashMap(); for (Map.Entry e : inputMap.entrySet()) { - map.put(funcKey.apply(e.getKey()), - funcValue.apply(e.getValue())); + map.put(funcKey.apply(e.getKey()), funcValue.apply(e.getValue())); } return map; } - + static final class TransformedImmutableList extends AbstractList implements List { - + final List inputList; final Function func; - + TransformedImmutableList(List inputList, Function func) { this.inputList = Objects.requireNonNull(inputList, "inputList is null"); this.func = Objects.requireNonNull(func, "func is null"); @@ -83,7 +79,6 @@ public final class Transformers { return inputList.size(); } - } - + } diff --git a/src/main/java/com/noorq/casser/support/UuidBuilder.java b/src/main/java/net/helenus/support/UuidBuilder.java similarity index 91% rename from src/main/java/com/noorq/casser/support/UuidBuilder.java rename to src/main/java/net/helenus/support/UuidBuilder.java index b850a24..a56452c 100644 --- a/src/main/java/com/noorq/casser/support/UuidBuilder.java +++ b/src/main/java/net/helenus/support/UuidBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.support; +package net.helenus.support; import java.util.UUID; - public final class UuidBuilder { public static final long NUM_100NS_IN_MILLISECOND = 10000L; public static final long NUM_100NS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; - private static final long MIN_CLOCK_SEQ_AND_NODE = 0x8080808080808080L; - private static final long MAX_CLOCK_SEQ_AND_NODE = 0x7f7f7f7f7f7f7f7fL; - + private static final long MIN_CLOCK_SEQ_AND_NODE = 0x8080808080808080L; + private static final long MAX_CLOCK_SEQ_AND_NODE = 0x7f7f7f7f7f7f7f7fL; + private long leastSigBits = 0x8000000000000000L; private long mostSigBits = 0L; diff --git a/src/test/java/com/noorq/casser/test/integration/core/CasserValidatorTest.java b/src/test/java/com/noorq/casser/test/integration/core/CasserValidatorTest.java deleted file mode 100644 index 34b14ef..0000000 --- a/src/test/java/com/noorq/casser/test/integration/core/CasserValidatorTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.noorq.casser.test.integration.core; - -import org.junit.Before; -import org.junit.Test; - -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserValidator; -import com.noorq.casser.mapping.CasserEntity; -import com.noorq.casser.mapping.CasserProperty; -import com.noorq.casser.mapping.annotation.Constraints; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.support.CasserException; -import com.noorq.casser.support.CasserMappingException; - -public class CasserValidatorTest { - - @Table - interface ModelForValidation { - - @Constraints.Email - @PartitionKey - String id(); - - } - - CasserEntity entity; - - CasserProperty prop; - - @Before - public void begin() { - - entity = Casser.entity(ModelForValidation.class); - - prop = entity.getProperty("id"); - - } - - @Test(expected=CasserMappingException.class) - public void testWrongType() { - CasserValidator.INSTANCE.validate(prop, Integer.valueOf(123)); - } - - @Test(expected=CasserException.class) - public void testWrongValue() { - CasserValidator.INSTANCE.validate(prop, "123"); - } - - - public void testOk() { - CasserValidator.INSTANCE.validate(prop, "a@b.c"); - } -} diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/AddressInformation.java b/src/test/java/com/noorq/casser/test/integration/core/usertype/AddressInformation.java deleted file mode 100644 index 81dadec..0000000 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/AddressInformation.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.noorq.casser.test.integration.core.usertype; - -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.UDT; - -@UDT -public interface AddressInformation { - - @Column - Address address(); - -} diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/Customer.java b/src/test/java/com/noorq/casser/test/integration/core/usertype/Customer.java deleted file mode 100644 index 35a7166..0000000 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/Customer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.noorq.casser.test.integration.core.usertype; - -import java.util.UUID; - -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; - -@Table -public interface Customer { - - @PartitionKey - UUID id(); - - @Column - AddressInformation addressInformation(); - -} diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/Rocket.java b/src/test/java/com/noorq/casser/test/unit/core/dsl/Rocket.java deleted file mode 100644 index d0caaf7..0000000 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/Rocket.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.noorq.casser.test.unit.core.dsl; - -import com.noorq.casser.mapping.annotation.UDT; - -@UDT -public interface Rocket { - - int length(); - - double price(); - -} diff --git a/src/test/java/com/noorq/casser/test/integration/build/AbstractEmbeddedCassandraTest.java b/src/test/java/net/helenus/test/integration/build/AbstractEmbeddedCassandraTest.java similarity index 66% rename from src/test/java/com/noorq/casser/test/integration/build/AbstractEmbeddedCassandraTest.java rename to src/test/java/net/helenus/test/integration/build/AbstractEmbeddedCassandraTest.java index 2713b29..d19efca 100644 --- a/src/test/java/com/noorq/casser/test/integration/build/AbstractEmbeddedCassandraTest.java +++ b/src/test/java/net/helenus/test/integration/build/AbstractEmbeddedCassandraTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,8 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.build; +package net.helenus.test.integration.build; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -23,10 +25,11 @@ import com.datastax.driver.core.Cluster; import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.Session; +import java.io.IOException; + /** * AbstractEmbeddedCassandraTest - * - * @author Alex Shvid + * * */ @@ -39,7 +42,7 @@ public abstract class AbstractEmbeddedCassandraTest { private static Session session; private static boolean keep; - + public static boolean isConnected() { return session != null; } @@ -51,36 +54,38 @@ public abstract class AbstractEmbeddedCassandraTest { public static Session getSession() { return session; } - + public static String getKeyspace() { return keyspace; } - + public static void setKeep(boolean enable) { keep = enable; } - + @BeforeClass - public static void before() throws Exception { - EmbeddedCassandraServerHelper.startEmbeddedCassandra(BuildProperties.getCassandraConfig()); - + public static void before() throws TTransportException, IOException, InterruptedException, ConfigurationException { + //EmbeddedCassandraServerHelper.startEmbeddedCassandra(BuildProperties.getCassandraConfig()); + cluster = Cluster.builder() - .addContactPoint(BuildProperties.getCassandraHost()) - .withPort(BuildProperties.getCassandraNativePort()) + .addContactPoint("localhost") + //.addContactPoint(BuildProperties.getCassandraHost()) + .withPort(9042) + //.withPort(BuildProperties.getCassandraNativePort()) .build(); KeyspaceMetadata kmd = cluster.getMetadata().getKeyspace(keyspace); - if (kmd == null) { + if (kmd == null) { session = cluster.connect(); - + String cql = "CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};"; System.out.println(cql + "\n"); session.execute(cql); - - cql = "USE " + keyspace + ";"; - System.out.println(cql + "\n"); - session.execute(cql); + + cql = "USE " + keyspace + ";"; + System.out.println(cql + "\n"); + session.execute(cql); } else { session = cluster.connect(keyspace); } @@ -90,10 +95,13 @@ public abstract class AbstractEmbeddedCassandraTest { @AfterClass public static void after() { if (!keep && isConnected()) { + String cql = "DROP " + keyspace + ";"; + System.out.println(cql + "\n"); +// session.execute(cql); + session.close(); session = null; - EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); - //EmbeddedCassandraServerHelper.stopEmbeddedCassandra(); +// EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); } } } diff --git a/src/test/java/com/noorq/casser/test/integration/build/BuildProperties.java b/src/test/java/net/helenus/test/integration/build/BuildProperties.java similarity index 93% rename from src/test/java/com/noorq/casser/test/integration/build/BuildProperties.java rename to src/test/java/net/helenus/test/integration/build/BuildProperties.java index 69504e5..ce849fb 100644 --- a/src/test/java/com/noorq/casser/test/integration/build/BuildProperties.java +++ b/src/test/java/net/helenus/test/integration/build/BuildProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.build; +package net.helenus.test.integration.build; import java.io.InputStream; import java.util.Properties; @@ -32,21 +32,21 @@ public final class BuildProperties { private final Properties props = new Properties(); private BuildProperties() { - - if (isRunInMaven()) { + + if (false) { //isRunInMaven()) { this.cassandraConfig = "build-cassandra.yaml"; - loadFromClasspath("build.properties"); + loadFromClasspath("build.properties"); } else { this.cassandraConfig = "eclipse-cassandra.yaml"; loadFromClasspath("eclipse.properties"); } } - + private boolean isRunInMaven() { return System.getProperty("maven.integration.test") != null; } - + private void loadFromClasspath(String resourceName) { InputStream in = getClass().getResourceAsStream("/" + resourceName); if (in == null) { @@ -60,19 +60,19 @@ public final class BuildProperties { IOUtils.closeQuietly(in); } } - + public static String getCassandraConfig() { return Singleton.INSTANCE.cassandraConfig; } - + public static String getCassandraHost() { return "localhost"; } - + public static String getRandomKeyspace() { return "test" + UUID.randomUUID().toString().replace("-", ""); } - + public static int getCassandraNativePort() { return Singleton.INSTANCE.getInt("build.cassandra.native_transport_port"); } diff --git a/src/test/java/com/noorq/casser/test/integration/core/ContextInitTest.java b/src/test/java/net/helenus/test/integration/core/ContextInitTest.java similarity index 70% rename from src/test/java/com/noorq/casser/test/integration/core/ContextInitTest.java rename to src/test/java/net/helenus/test/integration/core/ContextInitTest.java index a8f6151..92a4ea8 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/ContextInitTest.java +++ b/src/test/java/net/helenus/test/integration/core/ContextInitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core; +package net.helenus.test.integration.core; +import net.helenus.core.HelenusSession; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class ContextInitTest extends AbstractEmbeddedCassandraTest { @Test public void test() { - CasserSession session = Casser.init(getSession()).get(); + HelenusSession session = Helenus.init(getSession()).get(); System.out.println("Works! " + session); - + } - + } diff --git a/src/test/java/net/helenus/test/integration/core/HelenusValidatorTest.java b/src/test/java/net/helenus/test/integration/core/HelenusValidatorTest.java new file mode 100644 index 0000000..0596666 --- /dev/null +++ b/src/test/java/net/helenus/test/integration/core/HelenusValidatorTest.java @@ -0,0 +1,57 @@ +package net.helenus.test.integration.core; + +import net.helenus.core.HelenusSession; +import net.helenus.core.HelenusValidator; +import net.helenus.mapping.HelenusEntity; +import net.helenus.mapping.HelenusProperty; +import net.helenus.mapping.annotation.Constraints; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.support.HelenusMappingException; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; +import org.junit.Before; +import org.junit.Test; + +import net.helenus.core.Helenus; +import net.helenus.support.HelenusException; + +public class HelenusValidatorTest extends AbstractEmbeddedCassandraTest { + + @Table + interface ModelForValidation { + + @Constraints.Email + @PartitionKey + String id(); + + } + + HelenusEntity entity; + + HelenusProperty prop; + + @Before + public void begin() { + Helenus.init(getSession()).singleton(); + + entity = Helenus.entity(ModelForValidation.class); + + prop = entity.getProperty("id"); + + } + + @Test(expected=HelenusMappingException.class) + public void testWrongType() { + HelenusValidator.INSTANCE.validate(prop, Integer.valueOf(123)); + } + + @Test(expected=HelenusException.class) + public void testWrongValue() { + HelenusValidator.INSTANCE.validate(prop, "123"); + } + + + public void testOk() { + HelenusValidator.INSTANCE.validate(prop, "a@b.c"); + } +} diff --git a/src/test/java/com/noorq/casser/test/integration/core/collection/CollectionTest.java b/src/test/java/net/helenus/test/integration/core/collection/CollectionTest.java similarity index 91% rename from src/test/java/com/noorq/casser/test/integration/core/collection/CollectionTest.java rename to src/test/java/net/helenus/test/integration/core/collection/CollectionTest.java index 380d1b5..a017c28 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/collection/CollectionTest.java +++ b/src/test/java/net/helenus/test/integration/core/collection/CollectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.collection; +package net.helenus.test.integration.core.collection; -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; -import static com.noorq.casser.core.Query.getIdx; +import static net.helenus.core.Query.eq; +import static net.helenus.core.Query.get; +import static net.helenus.core.Query.getIdx; import java.util.ArrayList; import java.util.HashMap; @@ -27,344 +27,345 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import net.helenus.core.HelenusSession; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class CollectionTest extends AbstractEmbeddedCassandraTest { - static Customer customer = Casser.dsl(Customer.class); - - static CasserSession session; + static Customer customer; + + static HelenusSession session; @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(customer).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Customer.class).autoCreateDrop().get(); + customer = Helenus.dsl(Customer.class, session.getMetadata()); } - + @Test public void testPrint() { System.out.println(customer); } - + @Test public void testSetCRUID() { - + UUID id = UUID.randomUUID(); - + Set aliases = new HashSet(); aliases.add("Alex"); aliases.add("Albert"); - + // CREATE - + session.insert() .value(customer::id, id) .value(customer::aliases, aliases) .sync(); - + // READ - + // read full object - + Customer actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(aliases, actual.aliases()); Assert.assertNull(actual.names()); Assert.assertNull(actual.properties()); - + // read full set - + Set actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(aliases, actualSet); - + // UPDATE - + Set expected = new HashSet(); expected.add("unknown"); - + session.update().set(customer::aliases, expected).where(customer::id, eq(id)).sync(); - + actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(expected, actual.aliases()); - + // INSERT - + // add operation - + expected.add("add"); session.update().add(customer::aliases, "add").where(customer::id, eq(id)).sync(); - + actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualSet); - + // addAll operation expected.addAll(aliases); session.update().addAll(customer::aliases, aliases).where(customer::id, eq(id)).sync(); - + actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualSet); - + // DELETE - + // remove single value - + expected.remove("add"); session.update().remove(customer::aliases, "add").where(customer::id, eq(id)).sync(); - + actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualSet); - + // remove values - + expected.removeAll(aliases); session.update().removeAll(customer::aliases, aliases).where(customer::id, eq(id)).sync(); - + actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualSet); - + // remove full list - + session.update().set(customer::aliases, null).where(customer::id, eq(id)).sync(); - + actualSet = session.select(customer::aliases).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualSet); - + // remove object - + session.delete().where(customer::id, eq(id)).sync(); Long cnt = session.count().where(customer::id, eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - - + + @Test public void testListCRUID() { - + UUID id = UUID.randomUUID(); - + List names = new ArrayList(); names.add("Alex"); names.add("Albert"); - + // CREATE - + session.insert() .value(customer::id, id) .value(customer::names, names) .sync(); - + // READ - + // read full object - + Customer actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(names, actual.names()); Assert.assertNull(actual.aliases()); Assert.assertNull(actual.properties()); - + // read full list - + List actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(names, actualList); - + // read single value by index - + String cql = session.select(getIdx(customer::names, 1)) .where(customer::id, eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + List expected = new ArrayList(); expected.add("unknown"); - + session.update().set(customer::names, expected).where(customer::id, eq(id)).sync(); - + actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(expected, actual.names()); - + // INSERT - + // prepend operation - + expected.add(0, "prepend"); session.update().prepend(customer::names, "prepend").where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // append operation - + expected.add("append"); session.update().append(customer::names, "append").where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // prependAll operation expected.addAll(0, names); session.update().prependAll(customer::names, names).where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // appendAll operation expected.addAll(names); session.update().appendAll(customer::names, names).where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // set by Index - + expected.set(5, "inserted"); session.update().setIdx(customer::names, 5, "inserted").where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // DELETE - + // remove single value - + expected.remove("inserted"); session.update().discard(customer::names, "inserted").where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // remove values - + expected.removeAll(names); session.update().discardAll(customer::names, names).where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualList); - + // remove full list - + session.update().set(customer::names, null).where(customer::id, eq(id)).sync(); - + actualList = session.select(customer::names).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualList); - + // remove object - + session.delete().where(customer::id, eq(id)).sync(); Long cnt = session.count().where(customer::id, eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + @Test public void testMapCRUID() { - + UUID id = UUID.randomUUID(); - + Map props = new HashMap(); props.put("key1", "value1"); props.put("key2", "value2"); - + // CREATE - + session.insert() .value(customer::id, id) .value(customer::properties, props) .sync(); - + // READ - + // read full object - + Customer actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(props, actual.properties()); Assert.assertNull(actual.aliases()); Assert.assertNull(actual.names()); - + // read full map - + Map actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(props, actualMap); - + // read single key-value in map - + String cql = session.select(get(customer::properties, "key1")) .where(customer::id, eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put("k1", "v1"); expected.put("k2", "v2"); - + session.update().set(customer::properties, expected).where(customer::id, eq(id)).sync(); - + actual = session.select(Customer.class).where(customer::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); Assert.assertEquals(expected, actual.properties()); - + // INSERT - + // put operation - + expected.put("k3", "v3"); session.update().put(customer::properties, "k3", "v3").where(customer::id, eq(id)).sync(); - + actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualMap); - + // putAll operation expected.putAll(props); session.update().putAll(customer::properties, props).where(customer::id, eq(id)).sync(); - + actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualMap); - + // put existing - + expected.put("k3", "v33"); session.update().put(customer::properties, "k3", "v33").where(customer::id, eq(id)).sync(); - + actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove("k3"); session.update().put(customer::properties, "k3", null).where(customer::id, eq(id)).sync(); - + actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertEquals(expected, actualMap); - + // remove full map - + session.update().set(customer::properties, null).where(customer::id, eq(id)).sync(); - + actualMap = session.select(customer::properties).where(customer::id, eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - + session.delete().where(customer::id, eq(id)).sync(); Long cnt = session.count().where(customer::id, eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - - + + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/collection/Customer.java b/src/test/java/net/helenus/test/integration/core/collection/Customer.java similarity index 78% rename from src/test/java/com/noorq/casser/test/integration/core/collection/Customer.java rename to src/test/java/net/helenus/test/integration/core/collection/Customer.java index 9846019..4905b32 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/collection/Customer.java +++ b/src/test/java/net/helenus/test/integration/core/collection/Customer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.collection; +package net.helenus.test.integration.core.collection; import java.util.List; import java.util.Map; @@ -21,22 +21,22 @@ import java.util.Set; import java.util.UUID; import com.datastax.driver.core.DataType.Name; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Customer { @PartitionKey UUID id(); - + @Types.Set(Name.TEXT) Set aliases(); - + @Types.List(Name.TEXT) List names(); - + @Types.Map(key=Name.TEXT, value=Name.TEXT) Map properties(); diff --git a/src/test/java/com/noorq/casser/test/integration/core/compound/CompondKeyTest.java b/src/test/java/net/helenus/test/integration/core/compound/CompondKeyTest.java similarity index 73% rename from src/test/java/com/noorq/casser/test/integration/core/compound/CompondKeyTest.java rename to src/test/java/net/helenus/test/integration/core/compound/CompondKeyTest.java index 54f2dc9..bc448dc 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/compound/CompondKeyTest.java +++ b/src/test/java/net/helenus/test/integration/core/compound/CompondKeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.compound; +package net.helenus.test.integration.core.compound; import java.util.Date; import java.util.UUID; +import net.helenus.core.Helenus; +import net.helenus.core.HelenusSession; +import net.helenus.core.Operator; +import net.helenus.core.Query; +import net.helenus.support.Mutable; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.core.Operator; - -import static com.noorq.casser.core.Query.*; - -import com.noorq.casser.support.Mutable; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; - public class CompondKeyTest extends AbstractEmbeddedCassandraTest { - Timeline timeline = Casser.dsl(Timeline.class); + Timeline timeline; - CasserSession session; + HelenusSession session; public static class TimelineImpl implements Timeline { @@ -64,8 +61,8 @@ public class CompondKeyTest extends AbstractEmbeddedCassandraTest { @Before public void beforeTest() { - - session = Casser.init(getSession()).showCql().add(Timeline.class).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Timeline.class).autoCreateDrop().get(); + timeline = Helenus.dsl(Timeline.class, session.getMetadata()); } @Test @@ -93,7 +90,7 @@ public class CompondKeyTest extends AbstractEmbeddedCassandraTest { session.select(timeline::userId, timeline::timestamp, timeline::text) .where(timeline::userId, Operator.EQ, userId) - .orderBy(desc(timeline::timestamp)).limit(5).sync() + .orderBy(Query.desc(timeline::timestamp)).limit(5).sync() .forEach(t -> { //System.out.println(t); diff --git a/src/test/java/com/noorq/casser/test/integration/core/compound/Timeline.java b/src/test/java/net/helenus/test/integration/core/compound/Timeline.java similarity index 68% rename from src/test/java/com/noorq/casser/test/integration/core/compound/Timeline.java rename to src/test/java/net/helenus/test/integration/core/compound/Timeline.java index ae4eee5..e1980ce 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/compound/Timeline.java +++ b/src/test/java/net/helenus/test/integration/core/compound/Timeline.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.compound; +package net.helenus.test.integration.core.compound; import java.util.Date; import java.util.UUID; -import com.noorq.casser.mapping.annotation.ClusteringColumn; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.ClusteringColumn; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Timeline { @PartitionKey(ordinal=0) UUID userId(); - + @ClusteringColumn(ordinal=1) @Types.Timeuuid Date timestamp(); - + @Column(ordinal=2) String text(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/counter/CounterTest.java b/src/test/java/net/helenus/test/integration/core/counter/CounterTest.java similarity index 74% rename from src/test/java/com/noorq/casser/test/integration/core/counter/CounterTest.java rename to src/test/java/net/helenus/test/integration/core/counter/CounterTest.java index 19d31ab..5d3f34e 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/counter/CounterTest.java +++ b/src/test/java/net/helenus/test/integration/core/counter/CounterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,52 +13,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.counter; +package net.helenus.test.integration.core.counter; -import static com.noorq.casser.core.Query.eq; +import static net.helenus.core.Query.eq; +import net.helenus.core.HelenusSession; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class CounterTest extends AbstractEmbeddedCassandraTest { - static Page page = Casser.dsl(Page.class); - - static CasserSession session; + static Page page; + + static HelenusSession session; @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(page).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Page.class).autoCreateDrop().get(); + page = Helenus.dsl(Page.class, session.getMetadata()); } - + @Test public void testPrint() { System.out.println(page); } - + @Test public void testCounter() { - + boolean exists = session.select(page::hits).where(page::alias, eq("index")).sync().findFirst().isPresent(); Assert.assertFalse(exists); - + session.update().increment(page::hits, 10L).where(page::alias, eq("index")).sync(); - + long hits = session.select(page::hits).where(page::alias, eq("index")).sync().findFirst().get()._1; Assert.assertEquals(10, hits); - + session.update().decrement(page::hits).where(page::alias, eq("index")).sync(); - + hits = session.select(page::hits).where(page::alias, eq("index")).sync().findFirst().get()._1; Assert.assertEquals(9, hits); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/counter/Page.java b/src/test/java/net/helenus/test/integration/core/counter/Page.java similarity index 72% rename from src/test/java/com/noorq/casser/test/integration/core/counter/Page.java rename to src/test/java/net/helenus/test/integration/core/counter/Page.java index 6139683..6d9f3b8 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/counter/Page.java +++ b/src/test/java/net/helenus/test/integration/core/counter/Page.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.counter; +package net.helenus.test.integration.core.counter; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Page { @PartitionKey String alias(); - + @Types.Counter long hits(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/hierarchy/Animal.java b/src/test/java/net/helenus/test/integration/core/hierarchy/Animal.java similarity index 63% rename from src/test/java/com/noorq/casser/test/integration/core/hierarchy/Animal.java rename to src/test/java/net/helenus/test/integration/core/hierarchy/Animal.java index 9861609..3cfec1b 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/hierarchy/Animal.java +++ b/src/test/java/net/helenus/test/integration/core/hierarchy/Animal.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.hierarchy; +package net.helenus.test.integration.core.hierarchy; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; +import jnr.ffi.annotations.In; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.InheritedTable; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Transient; +@InheritedTable public interface Animal { @PartitionKey(ordinal=0) int id(); - + @Column(ordinal=1) boolean eatable(); - + + @Transient default Animal me() { + return this; + } } diff --git a/src/test/java/com/noorq/casser/test/integration/core/hierarchy/Cat.java b/src/test/java/net/helenus/test/integration/core/hierarchy/Cat.java similarity index 71% rename from src/test/java/com/noorq/casser/test/integration/core/hierarchy/Cat.java rename to src/test/java/net/helenus/test/integration/core/hierarchy/Cat.java index 3e2c5fb..0c3ac60 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/hierarchy/Cat.java +++ b/src/test/java/net/helenus/test/integration/core/hierarchy/Cat.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.hierarchy; +package net.helenus.test.integration.core.hierarchy; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Index; +import net.helenus.mapping.annotation.Table; @Table("cats") public interface Cat extends Animal { @Column(ordinal=0) + @Index(caseSensitive = false) String nickname(); - + } diff --git a/src/test/java/net/helenus/test/integration/core/hierarchy/HierarchyTest.java b/src/test/java/net/helenus/test/integration/core/hierarchy/HierarchyTest.java new file mode 100644 index 0000000..4dc4705 --- /dev/null +++ b/src/test/java/net/helenus/test/integration/core/hierarchy/HierarchyTest.java @@ -0,0 +1,63 @@ +package net.helenus.test.integration.core.hierarchy; + +import static net.helenus.core.Query.eq; + +import java.util.Optional; +import java.util.Random; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import net.helenus.core.Helenus; +import net.helenus.core.HelenusSession; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; + +public class HierarchyTest extends AbstractEmbeddedCassandraTest { + + static Cat cat; + + static Pig pig; + + static HelenusSession session; + + static Random rnd = new Random(); + + @BeforeClass + public static void beforeTest() { + session = Helenus.init(getSession()).showCql() + .add(Cat.class) + .add(Pig.class) + .autoCreateDrop().get(); + cat = Helenus.dsl(Cat.class); + pig = Helenus.dsl(Pig.class); + } + + @Test + public void testPrint() { + System.out.println(cat); + } + + @Test + public void testCounter() { + + session.insert().value(cat::id, rnd.nextInt()).value(cat::nickname, "garfield").value(cat::eatable, false).sync(); + session.insert().value(pig::id, rnd.nextInt()).value(pig::nickname, "porky").value(pig::eatable, true).sync(); + + Optional animal = session.select(Cat.class).where(cat::nickname, eq("garfield")).sync().findFirst(); + Assert.assertTrue(animal.isPresent()); + Assert.assertFalse(animal.get().eatable()); + } + + @Test + public void testDefaultMethod() { + session.insert().value(cat::id, rnd.nextInt()).value(cat::nickname, "garfield").value(cat::eatable, false).sync(); + Optional animal = session.select(Cat.class).where(cat::nickname, eq("garfield")).sync().findFirst(); + Assert.assertTrue(animal.isPresent()); + + Cat cat = animal.get(); + Animal itsme = cat.me(); + Assert.assertEquals(cat, itsme); + } + +} diff --git a/src/main/java/com/noorq/casser/mapping/value/ColumnValueProvider.java b/src/test/java/net/helenus/test/integration/core/hierarchy/Pig.java similarity index 66% rename from src/main/java/com/noorq/casser/mapping/value/ColumnValueProvider.java rename to src/test/java/net/helenus/test/integration/core/hierarchy/Pig.java index e2346b0..28d5660 100644 --- a/src/main/java/com/noorq/casser/mapping/value/ColumnValueProvider.java +++ b/src/test/java/net/helenus/test/integration/core/hierarchy/Pig.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.mapping.value; +package net.helenus.test.integration.core.hierarchy; -import com.noorq.casser.mapping.CasserProperty; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Table; +@Table("pigs") +public interface Pig extends Animal { -public interface ColumnValueProvider { + @Column(ordinal=0) + String nickname(); - V getColumnValue(Object source, int columnIndex, CasserProperty property); - } diff --git a/src/test/java/com/noorq/casser/test/integration/core/index/Book.java b/src/test/java/net/helenus/test/integration/core/index/Book.java similarity index 70% rename from src/test/java/com/noorq/casser/test/integration/core/index/Book.java rename to src/test/java/net/helenus/test/integration/core/index/Book.java index b2799b5..9ada1d5 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/index/Book.java +++ b/src/test/java/net/helenus/test/integration/core/index/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.index; +package net.helenus.test.integration.core.index; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Index; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Index; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table("books") public interface Book { @PartitionKey(ordinal=0) long id(); - + @Column(ordinal=1) @Index String isbn(); - + @Column(ordinal=2) String author(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/index/SecondaryIndexTest.java b/src/test/java/net/helenus/test/integration/core/index/SecondaryIndexTest.java similarity index 63% rename from src/test/java/com/noorq/casser/test/integration/core/index/SecondaryIndexTest.java rename to src/test/java/net/helenus/test/integration/core/index/SecondaryIndexTest.java index 9e94bc7..a383d01 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/index/SecondaryIndexTest.java +++ b/src/test/java/net/helenus/test/integration/core/index/SecondaryIndexTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,43 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.index; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.index; +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class SecondaryIndexTest extends AbstractEmbeddedCassandraTest { - Book book = Casser.dsl(Book.class); - - CasserSession session; - + Book book; + + HelenusSession session; + @Before public void beforeTest() { - - session = Casser.init(getSession()).showCql().add(Book.class).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Book.class).autoCreateDrop().get(); + book = Helenus.dsl(Book.class, session.getMetadata()); } - + @Test public void test() throws Exception { - + session.insert() .value(book::id, 123L) .value(book::isbn, "ABC") .value(book::author, "Alex") .sync(); - - long actualId = session.select(book::id).where(book::isbn, eq("ABC")).sync().findFirst().get()._1; - + + long actualId = session.select(book::id).where(book::isbn, Query.eq("ABC")).sync().findFirst().get()._1; + Assert.assertEquals(123L, actualId); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/prepared/Car.java b/src/test/java/net/helenus/test/integration/core/prepared/Car.java similarity index 78% rename from src/test/java/com/noorq/casser/test/integration/core/prepared/Car.java rename to src/test/java/net/helenus/test/integration/core/prepared/Car.java index e2e070b..58e8685 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/prepared/Car.java +++ b/src/test/java/net/helenus/test/integration/core/prepared/Car.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.prepared; +package net.helenus.test.integration.core.prepared; import java.math.BigDecimal; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table("cars") public interface Car { @PartitionKey(ordinal=0) String make(); - + @PartitionKey(ordinal=1) String model(); int year(); - + BigDecimal price(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/prepared/PreparedStatementTest.java b/src/test/java/net/helenus/test/integration/core/prepared/PreparedStatementTest.java similarity index 65% rename from src/test/java/com/noorq/casser/test/integration/core/prepared/PreparedStatementTest.java rename to src/test/java/net/helenus/test/integration/core/prepared/PreparedStatementTest.java index 8235abf..8ba5484 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/prepared/PreparedStatementTest.java +++ b/src/test/java/net/helenus/test/integration/core/prepared/PreparedStatementTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,99 +13,98 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.prepared; +package net.helenus.test.integration.core.prepared; -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.marker; +import static net.helenus.core.Query.marker; import java.math.BigDecimal; +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; +import net.helenus.core.operation.PreparedOperation; +import net.helenus.core.operation.PreparedStreamOperation; +import net.helenus.support.Fun; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.datastax.driver.core.ResultSet; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.core.operation.PreparedOperation; -import com.noorq.casser.core.operation.PreparedStreamOperation; -import com.noorq.casser.support.Fun; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class PreparedStatementTest extends AbstractEmbeddedCassandraTest { static Car car; - - static CasserSession session; - + + static HelenusSession session; + static PreparedOperation insertOp; static PreparedOperation updateOp; static PreparedStreamOperation selectOp; - + static PreparedStreamOperation> selectPriceOp; - + static PreparedOperation deleteOp; - + static PreparedOperation countOp; - + @BeforeClass public static void beforeTest() { - car = Casser.dsl(Car.class); - - session = Casser.init(getSession()).showCql().add(Car.class).autoCreateDrop().get(); - + session = Helenus.init(getSession()).showCql().add(Car.class).autoCreateDrop().get(); + car = Helenus.dsl(Car.class, session.getMetadata()); + insertOp = session.insert() - .value(car::make, marker()) - .value(car::model, marker()) + .value(car::make, Query.marker()) + .value(car::model, Query.marker()) .value(car::year, 2004) .prepare(); - + updateOp = session.update() - .set(car::price, marker()) - .where(car::make, eq(marker())) - .and(car::model, eq(marker())) + .set(car::price, Query.marker()) + .where(car::make, Query.eq(Query.marker())) + .and(car::model, Query.eq(Query.marker())) .prepare(); selectOp = session.select(Car.class) - .where(car::make, eq(marker())) - .and(car::model, eq(marker())) + .where(car::make, Query.eq(Query.marker())) + .and(car::model, Query.eq(Query.marker())) .prepare(); - + selectPriceOp = session.select(car::price) - .where(car::make, eq(marker())) - .and(car::model, eq(marker())) + .where(car::make, Query.eq(Query.marker())) + .and(car::model, Query.eq(Query.marker())) .prepare(); - + deleteOp = session.delete() - .where(car::make, eq(marker())) - .and(car::model, eq(marker())) + .where(car::make, Query.eq(Query.marker())) + .and(car::model, Query.eq(Query.marker())) .prepare(); - + countOp = session.count() - .where(car::make, eq(marker())) - .and(car::model, eq(marker())) + .where(car::make, Query.eq(Query.marker())) + .and(car::model, Query.eq(Query.marker())) .prepare(); - + } - + @Test public void testPrint() { System.out.println(car); } - + @Test public void testCRUID() throws Exception { - + // INSERT - + insertOp.bind("Nissan", "350Z").sync(); - + // SELECT - + Car actual = selectOp.bind("Nissan", "350Z").sync().findFirst().get(); Assert.assertEquals("Nissan", actual.make()); Assert.assertEquals("350Z", actual.model()); @@ -113,23 +112,23 @@ public class PreparedStatementTest extends AbstractEmbeddedCassandraTest { Assert.assertNull(actual.price()); // UPDATE - + updateOp.bind(BigDecimal.valueOf(10000.0), "Nissan", "350Z").sync(); BigDecimal price = selectPriceOp.bind("Nissan", "350Z").sync().findFirst().get()._1; - + Assert.assertEquals(BigDecimal.valueOf(10000.0), price); - + // DELETE - + Long cnt = countOp.bind("Nissan", "350Z").sync(); Assert.assertEquals(Long.valueOf(1), cnt); - + deleteOp.bind("Nissan", "350Z").sync(); - + cnt = countOp.bind("Nissan", "350Z").sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/Message.java b/src/test/java/net/helenus/test/integration/core/simple/Message.java similarity index 66% rename from src/test/java/com/noorq/casser/test/integration/core/simple/Message.java rename to src/test/java/net/helenus/test/integration/core/simple/Message.java index 8767766..94c237c 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/Message.java +++ b/src/test/java/net/helenus/test/integration/core/simple/Message.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; +package net.helenus.test.integration.core.simple; import java.util.Date; -import com.noorq.casser.mapping.annotation.ClusteringColumn; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.StaticColumn; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.ClusteringColumn; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.StaticColumn; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Message { @@ -33,10 +33,10 @@ public interface Message { @ClusteringColumn @Types.Timeuuid Date timestamp(); - + @StaticColumn(forceQuote=true) String from(); - + @Column(forceQuote=true) String to(); diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/SimpleUserTest.java b/src/test/java/net/helenus/test/integration/core/simple/SimpleUserTest.java similarity index 86% rename from src/test/java/com/noorq/casser/test/integration/core/simple/SimpleUserTest.java rename to src/test/java/net/helenus/test/integration/core/simple/SimpleUserTest.java index 13692df..f34a3fb 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/SimpleUserTest.java +++ b/src/test/java/net/helenus/test/integration/core/simple/SimpleUserTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,49 +13,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; +package net.helenus.test.integration.core.simple; -import static com.noorq.casser.core.Query.eq; +import static net.helenus.core.Query.eq; +import net.helenus.core.HelenusSession; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.core.Operator; -import com.noorq.casser.support.Fun; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.core.Operator; +import net.helenus.support.Fun; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class SimpleUserTest extends AbstractEmbeddedCassandraTest { - static User user = Casser.dsl(User.class); - - static CasserSession session; - + static User user; + + static HelenusSession session; + @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(User.class).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(User.class).autoCreateDrop().get(); + user = Helenus.dsl(User.class, session.getMetadata()); } - + public static class UserImpl implements User { - + Long id; String name; Integer age; UserType type; - + @Override public Long id() { return id; } - + @Override public String name() { return name; } - + @Override public Integer age() { return age; @@ -65,36 +66,36 @@ public class SimpleUserTest extends AbstractEmbeddedCassandraTest { public UserType type() { return type; } - + } - + @Test public void testCruid() throws Exception { - + UserImpl newUser = new UserImpl(); newUser.id = 100L; newUser.name = "alex"; newUser.age = 34; newUser.type = UserType.USER; - + // CREATE - + session.upsert(newUser).sync(); - + // READ - + // select row and map to entity - + User actual = session.selectAll(User.class).mapTo(User.class).where(user::id, eq(100L)).sync().findFirst().get(); assertUsers(newUser, actual); - + // select as object - + actual = session.select(User.class).where(user::id, eq(100L)).sync().findFirst().get(); assertUsers(newUser, actual); - + // select by columns - + actual = session.select() .column(user::id) .column(user::name) @@ -104,42 +105,42 @@ public class SimpleUserTest extends AbstractEmbeddedCassandraTest { .where(user::id, eq(100L)) .sync().findFirst().get(); assertUsers(newUser, actual); - + // select by columns - + actual = session.select(User.class) .mapTo(User.class) .where(user::id, eq(100L)) .sync().findFirst().get(); assertUsers(newUser, actual); - + // select as object and mapTo - + actual = session.select(user::id, user::name, user::age, user::type) .mapTo(User.class) .where(user::id, eq(100L)) .sync().findFirst().get(); assertUsers(newUser, actual); - + // select single column - + String name = session.select(user::name) .where(user::id, eq(100L)) .sync().findFirst().get()._1; - + Assert.assertEquals(newUser.name(), name); - + // select single column in array tuple - + name = (String) session.select() .column(user::name) .where(user::id, eq(100L)) .sync().findFirst().get()._a[0]; - + Assert.assertEquals(newUser.name(), name); - + // UPDATE - + session.update(user::name, "albert") .set(user::age, 35) .where(user::id, Operator.EQ, 100L).sync(); @@ -153,38 +154,38 @@ public class SimpleUserTest extends AbstractEmbeddedCassandraTest { .sync() .findFirst() .get(); - + Assert.assertEquals("_albert", name); - + User u = session.select(User.class).where(user::id, eq(100L)).sync().findFirst().get(); - + Assert.assertEquals(Long.valueOf(100L), u.id()); Assert.assertEquals("albert", u.name()); Assert.assertEquals(Integer.valueOf(35), u.age()); - + // INSERT - + session.update() .set(user::name, null) .set(user::age, null) .set(user::type, null) .where(user::id, eq(100L)).sync(); - - + + Fun.Tuple3 tuple = session.select(user::name, user::age, user::type) .where(user::id, eq(100L)).sync().findFirst().get(); - + Assert.assertNull(tuple._1); Assert.assertNull(tuple._2); Assert.assertNull(tuple._3); - + // DELETE - + session.delete(user).where(user::id, eq(100L)).sync(); - + cnt = session.select().count().where(user::id, eq(100L)).sync(); Assert.assertEquals(0L, cnt); - + } private void assertUsers(User expected, User actual) { diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/StaticColumnTest.java b/src/test/java/net/helenus/test/integration/core/simple/StaticColumnTest.java similarity index 61% rename from src/test/java/com/noorq/casser/test/integration/core/simple/StaticColumnTest.java rename to src/test/java/net/helenus/test/integration/core/simple/StaticColumnTest.java index 6d88db3..1648c97 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/StaticColumnTest.java +++ b/src/test/java/net/helenus/test/integration/core/simple/StaticColumnTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,43 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.simple; import java.util.Date; import java.util.List; import java.util.stream.Collectors; +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class StaticColumnTest extends AbstractEmbeddedCassandraTest { - static Message message = Casser.dsl(Message.class); - + static HelenusSession session; + static Message message; + @BeforeClass public static void beforeTest() { - Casser.init(getSession()).showCql().addPackage(Message.class.getPackage().getName()).autoCreateDrop().singleton(); + session = Helenus.init(getSession()).showCql().addPackage(Message.class.getPackage().getName()).autoCreateDrop().get(); + message = Helenus.dsl(Message.class, session.getMetadata()); } - + @Test public void testPrint() { System.out.println(message); } - + private static class MessageImpl implements Message { - + int id; Date timestamp; String from; String to; String msg; - + @Override public int id() { return id; @@ -74,79 +76,81 @@ public class StaticColumnTest extends AbstractEmbeddedCassandraTest { public String message() { return msg; } - + } - - + + @Test public void testCRUID() { - + MessageImpl msg = new MessageImpl(); msg.id = 123; msg.timestamp = new Date(); msg.from = "Alex"; msg.to = "Bob"; msg.msg = "hi"; - + // CREATE - - Casser.session().insert(msg).sync(); - + + session.insert(msg).sync(); + msg.id = 123; msg.to = "Craig"; - Casser.session().insert(msg).sync(); - - + session.insert(msg).sync(); + + // READ - - List actual = Casser.session().select(Message.class) - .where(message::id, eq(123)).sync() + + List actual = session.select(Message.class) + .where(message::id, Query.eq(123)).sync() .collect(Collectors.toList()); - + Assert.assertEquals(2, actual.size()); - - Message toCraig = actual.stream().filter(m -> m.to().equals("Craig")).findFirst().get(); + + Message toCraig = actual.stream().filter(m -> m.to().equals("Craig")).findFirst().get(); assertMessages(msg, toCraig); - + // UPDATE - - Casser.session().update().set(message::from, "Albert") - .where(message::id, eq(123)) - .onlyIf(message::from, eq("Alex")) - .sync(); - - long cnt = Casser.session().select(message::from) - .where(message::id, eq(123)).sync() + + session.update().set(message::from, "Albert") + .where(message::id, Query.eq(123)) + .onlyIf(message::from, Query.eq("Alex")) + .sync(); + + long cnt = session.select(message::from) + .where(message::id, Query.eq(123)).sync() .filter(t -> t._1.equals("Albert")) .count(); - + Assert.assertEquals(2, cnt); // INSERT - - Casser.session().update().set(message::from, null) - .where(message::id, eq(123)) + + session.update().set(message::from, null) + .where(message::id, Query.eq(123)) .sync(); - - Casser.session().select(message::from) - .where(message::id, eq(123)) + + session.select(message::from) + .where(message::id, Query.eq(123)) .sync() .map(t -> t._1) .forEach(Assert::assertNull); - Casser.session().update().set(message::from, "Alex") - .where(message::id, eq(123)) - .onlyIf(message::from, eq(null)).sync(); - + session.update().set(message::from, "Alex") + .where(message::id, Query.eq(123)) + .onlyIf(message::from, Query.eq(null)).sync(); + // DELETE - - Casser.session().delete().where(message::id, eq(123)).sync(); - - cnt = Casser.session().count().where(message::id, eq(123)).sync(); + + session.delete() + .where(message::id, Query.eq(123)).sync(); + + cnt = session.count() + .where(message::id, Query.eq(123)).sync(); Assert.assertEquals(0, cnt); } - + private void assertMessages(Message expected, Message actual) { Assert.assertEquals(expected.id(), actual.id()); Assert.assertEquals(expected.from(), actual.from()); @@ -154,5 +158,5 @@ public class StaticColumnTest extends AbstractEmbeddedCassandraTest { Assert.assertEquals(expected.to(), actual.to()); Assert.assertEquals(expected.message(), actual.message()); } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/User.java b/src/test/java/net/helenus/test/integration/core/simple/User.java similarity index 73% rename from src/test/java/com/noorq/casser/test/integration/core/simple/User.java rename to src/test/java/net/helenus/test/integration/core/simple/User.java index d23333e..80ced28 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/User.java +++ b/src/test/java/net/helenus/test/integration/core/simple/User.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; +package net.helenus.test.integration.core.simple; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table("simple_users") public interface User { @PartitionKey Long id(); - + @Username @Column("override_name") String name(); - + Integer age(); - + UserType type(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/UserType.java b/src/test/java/net/helenus/test/integration/core/simple/UserType.java similarity index 86% rename from src/test/java/com/noorq/casser/test/integration/core/simple/UserType.java rename to src/test/java/net/helenus/test/integration/core/simple/UserType.java index c74d875..0a425ce 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/UserType.java +++ b/src/test/java/net/helenus/test/integration/core/simple/UserType.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; +package net.helenus.test.integration.core.simple; public enum UserType { USER, ADMIN; diff --git a/src/test/java/com/noorq/casser/test/integration/core/simple/Username.java b/src/test/java/net/helenus/test/integration/core/simple/Username.java similarity index 85% rename from src/test/java/com/noorq/casser/test/integration/core/simple/Username.java rename to src/test/java/net/helenus/test/integration/core/simple/Username.java index 1533791..61afdf0 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/simple/Username.java +++ b/src/test/java/net/helenus/test/integration/core/simple/Username.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.simple; +package net.helenus.test.integration.core.simple; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -21,8 +21,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.noorq.casser.mapping.annotation.Constraints; - +import net.helenus.mapping.annotation.Constraints; @Documented @Retention(RetentionPolicy.RUNTIME) diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/Album.java b/src/test/java/net/helenus/test/integration/core/tuple/Album.java similarity index 73% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/Album.java rename to src/test/java/net/helenus/test/integration/core/tuple/Album.java index 7b3eead..64f2df5 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/Album.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/Album.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,25 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; +package net.helenus.test.integration.core.tuple; import com.datastax.driver.core.DataType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Album { @PartitionKey(ordinal=1) int id(); - + AlbumInformation info(); - + @Types.Tuple({DataType.Name.TEXT, DataType.Name.TEXT}) @Column(ordinal=1) TupleValue infoNoMapping(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/AlbumInformation.java b/src/test/java/net/helenus/test/integration/core/tuple/AlbumInformation.java similarity index 77% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/AlbumInformation.java rename to src/test/java/net/helenus/test/integration/core/tuple/AlbumInformation.java index 4a79285..10cff73 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/AlbumInformation.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/AlbumInformation.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; +package net.helenus.test.integration.core.tuple; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Tuple; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Tuple; @Tuple public interface AlbumInformation { @Column(ordinal=0) String about(); - + @Column(ordinal=1) String place(); - + } diff --git a/src/test/java/net/helenus/test/integration/core/tuple/DslTest.java b/src/test/java/net/helenus/test/integration/core/tuple/DslTest.java new file mode 100644 index 0000000..c597289 --- /dev/null +++ b/src/test/java/net/helenus/test/integration/core/tuple/DslTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2015 The Helenus Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.helenus.test.integration.core.tuple; + +import org.junit.Assert; +import org.junit.Test; + +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; + +public class DslTest extends AbstractEmbeddedCassandraTest { + + @Test + public void testDslBeforeSessionInit() { + Assert.assertNotNull(Helenus.dsl(Album.class)); + } + + @Test + public void testSessionInitAddingDslProxy() { + Assert.assertNotNull(Helenus.init(getSession()).showCql().add(Helenus.dsl(Album.class))); + } + +} diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/InnerTupleTest.java b/src/test/java/net/helenus/test/integration/core/tuple/InnerTupleTest.java similarity index 69% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/InnerTupleTest.java rename to src/test/java/net/helenus/test/integration/core/tuple/InnerTupleTest.java index df58c62..631f140 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/InnerTupleTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/InnerTupleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,49 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; +package net.helenus.test.integration.core.tuple; -import static com.noorq.casser.core.Query.eq; - +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; public class InnerTupleTest extends AbstractEmbeddedCassandraTest { - static PhotoAlbum photoAlbum = Casser.dsl(PhotoAlbum.class); + static PhotoAlbum photoAlbum; + + static HelenusSession session; - static CasserSession session; - @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(photoAlbum).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(PhotoAlbum.class).autoCreateDrop().get(); + photoAlbum = Helenus.dsl(PhotoAlbum.class, session.getMetadata()); } - + @Test public void testPrint() { System.out.println(photoAlbum); } - - + + @Test public void testCruid() { - + Photo photo = new Photo() { @Override public byte[] blob() { return "jpeg".getBytes(); } - + }; - + PhotoFolder folder = new PhotoFolder() { @Override @@ -67,30 +67,30 @@ public class InnerTupleTest extends AbstractEmbeddedCassandraTest { public Photo photo() { return photo; } - + }; - + // CREATE (C) - + session.insert() .value(photoAlbum::id, 123) .value(photoAlbum::folder, folder) .sync(); - + // READ (R) - - PhotoFolder actual = session.select(photoAlbum::folder).where(photoAlbum::id, eq(123)).sync().findFirst().get()._1; - + + PhotoFolder actual = session.select(photoAlbum::folder).where(photoAlbum::id, Query.eq(123)).sync().findFirst().get()._1; + Assert.assertEquals(folder.name(), actual.name()); - + // UPDATE (U) - + // unfortunately this is not working right now in Cassandra, can not update a single column in tuple :( //session.update() - // .set(photoAlbum.folder().photo()::blob, "Casser".getBytes()) + // .set(photoAlbum.folder().photo()::blob, "Helenus".getBytes()) // .where(photoAlbum::id, eq(123)) // .sync(); - + PhotoFolder expected = new PhotoFolder() { @Override @@ -102,37 +102,37 @@ public class InnerTupleTest extends AbstractEmbeddedCassandraTest { public Photo photo() { return photo; } - + }; - + session.update() .set(photoAlbum::folder, expected) - .where(photoAlbum::id, eq(123)) - .sync(); - - actual = session.select(photoAlbum::folder).where(photoAlbum::id, eq(123)).sync().findFirst().get()._1; - + .where(photoAlbum::id, Query.eq(123)) + .sync(); + + actual = session.select(photoAlbum::folder).where(photoAlbum::id, Query.eq(123)).sync().findFirst().get()._1; + Assert.assertEquals(expected.name(), actual.name()); - - // INSERT (I) + + // INSERT (I) // let's insert null ;) - + session.update() .set(photoAlbum::folder, null) - .where(photoAlbum::id, eq(123)) - .sync(); - - actual = session.select(photoAlbum::folder).where(photoAlbum::id, eq(123)).sync().findFirst().get()._1; - Assert.assertNull(actual); - - // DELETE (D) - session.delete().where(photoAlbum::id, eq(123)).sync(); + .where(photoAlbum::id, Query.eq(123)) + .sync(); - long cnt = session.select(photoAlbum::folder).where(photoAlbum::id, eq(123)).sync().count(); + actual = session.select(photoAlbum::folder).where(photoAlbum::id, Query.eq(123)).sync().findFirst().get()._1; + Assert.assertNull(actual); + + // DELETE (D) + session.delete().where(photoAlbum::id, Query.eq(123)).sync(); + + long cnt = session.select(photoAlbum::folder).where(photoAlbum::id, Query.eq(123)).sync().count(); Assert.assertEquals(0, cnt); - - + + } - - + + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/Photo.java b/src/test/java/net/helenus/test/integration/core/tuple/Photo.java similarity index 80% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/Photo.java rename to src/test/java/net/helenus/test/integration/core/tuple/Photo.java index af88fcf..8606325 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/Photo.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/Photo.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; - -import com.noorq.casser.mapping.annotation.Tuple; +package net.helenus.test.integration.core.tuple; +import net.helenus.mapping.annotation.Tuple; @Tuple public interface Photo { byte[] blob(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoAlbum.java b/src/test/java/net/helenus/test/integration/core/tuple/PhotoAlbum.java similarity index 76% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoAlbum.java rename to src/test/java/net/helenus/test/integration/core/tuple/PhotoAlbum.java index be06d0b..8404eee 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoAlbum.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/PhotoAlbum.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; +package net.helenus.test.integration.core.tuple; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table public interface PhotoAlbum { @PartitionKey int id(); - + PhotoFolder folder(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoFolder.java b/src/test/java/net/helenus/test/integration/core/tuple/PhotoFolder.java similarity index 77% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoFolder.java rename to src/test/java/net/helenus/test/integration/core/tuple/PhotoFolder.java index 1a4d87a..7fdbd8f 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/PhotoFolder.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/PhotoFolder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,19 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; - -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Tuple; +package net.helenus.test.integration.core.tuple; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Tuple; @Tuple public interface PhotoFolder { @Column(ordinal=0) String name(); - + @Column(ordinal=1) Photo photo(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuple/TupleTest.java b/src/test/java/net/helenus/test/integration/core/tuple/TupleTest.java similarity index 82% rename from src/test/java/com/noorq/casser/test/integration/core/tuple/TupleTest.java rename to src/test/java/net/helenus/test/integration/core/tuple/TupleTest.java index 3c5fdac..1f7c84c 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuple/TupleTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuple/TupleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuple; +package net.helenus.test.integration.core.tuple; -import static com.noorq.casser.core.Query.eq; +import static net.helenus.core.Query.eq; +import net.helenus.core.HelenusSession; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -26,29 +27,30 @@ import org.junit.Test; import com.datastax.driver.core.DataType; import com.datastax.driver.core.TupleType; import com.datastax.driver.core.TupleValue; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public class TupleTest extends AbstractEmbeddedCassandraTest { - static Album album = Casser.dsl(Album.class); + static Album album; + + static HelenusSession session; - static CasserSession session; - @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(album).autoCreateDrop().get(); + Helenus.clearDslCache(); + session = Helenus.init(getSession()).showCql().add(Album.class).autoCreateDrop().get(); + album = Helenus.dsl(Album.class, session.getMetadata()); } - + @Test public void testPrint() { System.out.println(album); } - + @Test public void testCruid() { - + AlbumInformation info = new AlbumInformation() { @Override @@ -60,133 +62,133 @@ public class TupleTest extends AbstractEmbeddedCassandraTest { public String place() { return "San Jose"; } - + }; - - + + // CREATE (C) - + session.insert() .value(album::id, 123) .value(album::info, info) .sync(); - + // READ (R) - + AlbumInformation actual = session.select(album::info).where(album::id, eq(123)).sync().findFirst().get()._1; - + Assert.assertEquals(info.about(), actual.about()); Assert.assertEquals(info.place(), actual.place()); - + // UPDATE (U) - + // unfortunately this is not working right now in Cassandra, can not update a single column in tuple :( //session.update() - // .set(album.info()::about, "Casser") + // .set(album.info()::about, "Helenus") // .where(album::id, eq(123)) - // .sync(); - + // .sync(); + AlbumInformation expected = new AlbumInformation() { @Override public String about() { - return "Casser"; + return "Helenus"; } @Override public String place() { return "Santa Cruz"; } - + }; - + session.update() .set(album::info, expected) .where(album::id, eq(123)) - .sync(); - + .sync(); + actual = session.select(album::info).where(album::id, eq(123)).sync().findFirst().get()._1; - + Assert.assertEquals(expected.about(), actual.about()); Assert.assertEquals(expected.place(), actual.place()); - - // INSERT (I) + + // INSERT (I) // let's insert null ;) - + session.update() .set(album::info, null) .where(album::id, eq(123)) - .sync(); - + .sync(); + actual = session.select(album::info).where(album::id, eq(123)).sync().findFirst().get()._1; Assert.assertNull(actual); - + // DELETE (D) session.delete().where(album::id, eq(123)).sync(); long cnt = session.select(album::info).where(album::id, eq(123)).sync().count(); Assert.assertEquals(0, cnt); - - + + } - + @Test public void testNoMapping() { - - TupleType tupleType = TupleType.of(DataType.text(), DataType.text()); + + TupleType tupleType = session.getMetadata().newTupleType(DataType.text(), DataType.text()); TupleValue info = tupleType.newValue(); - + info.setString(0, "Cassandra"); info.setString(1, "San Jose"); - + // CREATE (C) - + session.insert() .value(album::id, 555) .value(album::infoNoMapping, info) .sync(); - + // READ (R) - + TupleValue actual = session.select(album::infoNoMapping).where(album::id, eq(555)).sync().findFirst().get()._1; - + Assert.assertEquals(info.getString(0), actual.getString(0)); Assert.assertEquals(info.getString(1), actual.getString(1)); - + // UPDATE (U) - + TupleValue expected = tupleType.newValue(); - - expected.setString(0, "Casser"); + + expected.setString(0, "Helenus"); expected.setString(1, "Los Altos"); - + session.update() .set(album::infoNoMapping, expected) .where(album::id, eq(555)) - .sync(); - + .sync(); + actual = session.select(album::infoNoMapping).where(album::id, eq(555)).sync().findFirst().get()._1; - + Assert.assertEquals(expected.getString(0), actual.getString(0)); Assert.assertEquals(expected.getString(1), actual.getString(1)); - - // INSERT (I) + + // INSERT (I) // let's insert null ;) - + session.update() .set(album::infoNoMapping, null) .where(album::id, eq(555)) - .sync(); - + .sync(); + actual = session.select(album::infoNoMapping).where(album::id, eq(555)).sync().findFirst().get()._1; Assert.assertNull(actual); - + // DELETE (D) session.delete().where(album::id, eq(555)).sync(); long cnt = session.select(album::infoNoMapping).where(album::id, eq(555)).sync().count(); Assert.assertEquals(0, cnt); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Author.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/Author.java similarity index 76% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Author.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/Author.java index eab9b78..bcf4135 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Author.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/Author.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; +package net.helenus.test.integration.core.tuplecollection; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Tuple; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Tuple; @Tuple public interface Author { @Column(ordinal=0) String name(); - + @Column(ordinal=1) String city(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Book.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/Book.java similarity index 79% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/Book.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/Book.java index 642deb3..88841a3 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Book.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.tuplecollection; import java.util.List; import java.util.Map; import java.util.Set; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table public interface Book { @PartitionKey int id(); - + List authors(); Set reviewers(); - + Map contents(); - + Map notes(); - + Map writers(); } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Section.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/Section.java similarity index 76% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Section.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/Section.java index 3ca1195..4159658 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Section.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/Section.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; +package net.helenus.test.integration.core.tuplecollection; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Tuple; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Tuple; @Tuple public interface Section { @Column(ordinal=0) String title(); - + @Column(ordinal=1) int page(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleCollectionTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleCollectionTest.java similarity index 85% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleCollectionTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleCollectionTest.java index 4fff6ec..09c2046 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleCollectionTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleCollectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,41 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; +package net.helenus.test.integration.core.tuplecollection; +import net.helenus.core.HelenusSession; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; public abstract class TupleCollectionTest extends AbstractEmbeddedCassandraTest { - static Book book = Casser.dsl(Book.class); - - static CasserSession session; + static Book book; + + static HelenusSession session; @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(book).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Book.class).autoCreateDrop().get(); + book = Helenus.dsl(Book.class, session.getMetadata()); } - + @Test public void test() { - System.out.println(book); + System.out.println(book); } - + public static final class AuthorImpl implements Author { String name; String city; - + AuthorImpl(String name, String city) { this.name = name; this.city = city; } - + @Override public String name() { return name; @@ -93,19 +94,19 @@ public abstract class TupleCollectionTest extends AbstractEmbeddedCassandraTest public String toString() { return "AuthorImpl [name=" + name + ", city=" + city + "]"; } - + } public static final class SectionImpl implements Section { String title; int page; - + SectionImpl(String title, int page) { this.title = title; this.page = page; } - + @Override public String title() { return title; @@ -148,10 +149,10 @@ public abstract class TupleCollectionTest extends AbstractEmbeddedCassandraTest public String toString() { return "SectionImpl [title=" + title + ", page=" + page + "]"; } - + } - - + + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleKeyMapTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleKeyMapTest.java similarity index 64% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleKeyMapTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleKeyMapTest.java index 95a1ccd..2a93f6d 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleKeyMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleKeyMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,124 +13,122 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +package net.helenus.test.integration.core.tuplecollection; import java.util.HashMap; import java.util.Map; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class TupleKeyMapTest extends TupleCollectionTest { - + @Test public void testKeyMapCRUID() { - + int id = 888; - + Map notes = new HashMap(); notes.put(new SectionImpl("first", 1), "value1"); notes.put(new SectionImpl("second", 2), "value2"); - + // CREATE - + session.insert() - .value(book::id, id) - .value(book::notes, notes) - .sync(); - + .value(book::id, id) + .value(book::notes, notes) + .sync(); + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(notes, actual.notes()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.writers()); Assert.assertNull(actual.contents()); - + // read full map - - Map actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + + Map actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(notes, actualMap); - + // read single key-value in map - - String cql = session.select(get(book::notes, new SectionImpl("first", 1))) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.get(book::notes, new SectionImpl("first", 1))) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put(new SectionImpl("f", 1), "v1"); expected.put(new SectionImpl("s", 1), "v2"); - - session.update().set(book::notes, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + session.update().set(book::notes, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.notes()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); - + expected.put(third, "v3"); - session.update().put(book::notes, third, "v3").where(book::id, eq(id)).sync(); - - actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::notes, third, "v3").where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(notes); - session.update().putAll(book::notes, notes).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().putAll(book::notes, notes).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + expected.put(third, "v33"); - session.update().put(book::notes, third, "v33").where(book::id, eq(id)).sync(); - - actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::notes, third, "v33").where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(third); - session.update().put(book::notes, third, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::notes, third, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - - session.update().set(book::notes, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::notes, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::notes).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Section e : expected.keySet()) { @@ -139,9 +137,9 @@ public class TupleKeyMapTest extends TupleCollectionTest { Assert.assertEquals(e.page(), a.page()); Assert.assertEquals(expected.get(e), actual.get(a)); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleListTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleListTest.java similarity index 65% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleListTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleListTest.java index b8a78af..b5c2964 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleListTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleListTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,156 +13,154 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.getIdx; +package net.helenus.test.integration.core.tuplecollection; import java.util.ArrayList; import java.util.List; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class TupleListTest extends TupleCollectionTest { - + @Test public void testListCRUID() { - + int id = 777; - + List authors = new ArrayList(); authors.add(new AuthorImpl("Alex", "San Jose")); authors.add(new AuthorImpl("Bob", "San Francisco")); - + // CREATE - + session.insert() .value(book::id, id) .value(book::authors, authors) .sync(); - + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualLists(authors, actual.authors()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.contents()); - + // read full list - - List actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + + List actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(authors, actualList); - + // read single value by index - - String cql = session.select(getIdx(book::authors, 1)) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.getIdx(book::authors, 1)) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + List expected = new ArrayList(); expected.add(new AuthorImpl("Unknown", "City 17")); - - session.update().set(book::authors, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + session.update().set(book::authors, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualLists(expected, actual.authors()); - + // INSERT - + // prepend operation - + expected.add(0, new AuthorImpl("Prepend", "PrependCity")); - session.update().prepend(book::authors, new AuthorImpl("Prepend", "PrependCity")).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().prepend(book::authors, new AuthorImpl("Prepend", "PrependCity")).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // append operation - + expected.add(new AuthorImpl("Append", "AppendCity")); - session.update().append(book::authors, new AuthorImpl("Append", "AppendCity")).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().append(book::authors, new AuthorImpl("Append", "AppendCity")).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // prependAll operation expected.addAll(0, authors); - session.update().prependAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().prependAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // appendAll operation expected.addAll(authors); - session.update().appendAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().appendAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // set by Index - + Author inserted = new AuthorImpl("Insert", "InsertCity"); expected.set(5, inserted); - session.update().setIdx(book::authors, 5, inserted).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().setIdx(book::authors, 5, inserted).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // DELETE - + // remove single value - + expected.remove(inserted); - session.update().discard(book::authors, inserted).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().discard(book::authors, inserted).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // remove values - + expected.removeAll(authors); - session.update().discardAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().discardAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // remove full list - - session.update().set(book::authors, null).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::authors, null).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualList); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualLists(List expected, List actual) { Assert.assertEquals(expected.size(), actual.size()); - + int size = expected.size(); - + for (int i = 0; i != size; ++i) { Author e = expected.get(i); Author a = actual.get(i); Assert.assertEquals(e.name(), a.name()); Assert.assertEquals(e.city(), a.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleMapTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleMapTest.java similarity index 59% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleMapTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleMapTest.java index 8083142..9f52fa5 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,143 +13,140 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +package net.helenus.test.integration.core.tuplecollection; import java.util.HashMap; import java.util.Map; +import net.helenus.core.Query; +import net.helenus.test.integration.core.udtcollection.UDTCollectionTest; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.test.integration.core.udtcollection.UDTCollectionTest.AuthorImpl; - public class TupleMapTest extends TupleCollectionTest { - + @Test public void testMapCRUID() { - + int id = 333; - + Map writers = new HashMap(); - writers.put(new SectionImpl("first", 1), new AuthorImpl("Alex", "San Jose")); - writers.put(new SectionImpl("second", 2), new AuthorImpl("Bob", "San Francisco")); - + writers.put(new SectionImpl("first", 1), new TupleCollectionTest.AuthorImpl("Alex", "San Jose")); + writers.put(new SectionImpl("second", 2), new TupleCollectionTest.AuthorImpl("Bob", "San Francisco")); + // CREATE - + session.insert() - .value(book::id, id) - .value(book::writers, writers) - .sync(); - + .value(book::id, id) + .value(book::writers, writers) + .sync(); + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(writers, actual.writers()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.notes()); Assert.assertNull(actual.contents()); - + // read full map - - Map actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + + Map actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(writers, actualMap); - + // read single key-value in map - - String cql = session.select(get(book::writers, new SectionImpl("first", 1))) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.get(book::writers, new SectionImpl("first", 1))) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); - expected.put(new SectionImpl("f", 1), new AuthorImpl("A", "SJ")); - expected.put(new SectionImpl("s", 1), new AuthorImpl("B", "SF")); - - session.update().set(book::writers, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + expected.put(new SectionImpl("f", 1), new TupleCollectionTest.AuthorImpl("A", "SJ")); + expected.put(new SectionImpl("s", 1), new TupleCollectionTest.AuthorImpl("B", "SF")); + + session.update().set(book::writers, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.writers()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); - Author unk = new AuthorImpl("Unk", "City 17"); - + Author unk = new TupleCollectionTest.AuthorImpl("Unk", "City 17"); + expected.put(third, unk); - session.update().put(book::writers, third, unk).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, unk).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(writers); - session.update().putAll(book::writers, writers).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().putAll(book::writers, writers).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + expected.put(third, unk); - session.update().put(book::writers, third, unk).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, unk).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(third); - session.update().put(book::writers, third, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - - session.update().set(book::writers, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::writers, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Section e : expected.keySet()) { Section a = actual.keySet().stream().filter(p -> p.title().equals(e.title())).findFirst().get(); Assert.assertEquals(e.title(), a.title()); Assert.assertEquals(e.page(), a.page()); - + Author ea = expected.get(e); Author aa = actual.get(a); - + Assert.assertEquals(ea.name(), aa.name()); Assert.assertEquals(ea.city(), aa.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleSetTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleSetTest.java similarity index 68% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleSetTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleSetTest.java index b06e180..109a9e3 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleSetTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleSetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,113 +13,112 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.tuplecollection; import java.util.HashSet; import java.util.Set; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class TupleSetTest extends TupleCollectionTest { - + @Test public void testSetCRUID() { - + int id = 555; - + // CREATE - + Set reviewers = new HashSet(); reviewers.add(new AuthorImpl("Alex", "San Jose")); reviewers.add(new AuthorImpl("Bob", "San Francisco")); - + session.insert() .value(book::id, id) .value(book::reviewers, reviewers) .sync(); - + // READ - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualSets(reviewers, actual.reviewers()); - + // UPDATE - + Set expected = new HashSet(); expected.add(new AuthorImpl("Craig", "Los Altos")); - - session.update().set(book::reviewers, expected).where(book::id, eq(id)).sync(); - - Set actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::reviewers, expected).where(book::id, Query.eq(id)).sync(); + + Set actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // add operation - + expected.add(new AuthorImpl("Add", "AddCity")); session.update().add(book::reviewers, new AuthorImpl("Add", "AddCity")) - .where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + .where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // addAll operation expected.addAll(reviewers); - session.update().addAll(book::reviewers, reviewers).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().addAll(book::reviewers, reviewers).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // DELETE - + // remove single value - + Author a = expected.stream().filter(p -> p.name().equals("Add")).findFirst().get(); expected.remove(a); - - session.update().remove(book::reviewers, a).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().remove(book::reviewers, a).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // remove values - + expected.remove(expected.stream().filter(p -> p.name().equals("Alex")).findFirst().get()); expected.remove(expected.stream().filter(p -> p.name().equals("Bob")).findFirst().get()); - session.update().removeAll(book::reviewers, reviewers).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().removeAll(book::reviewers, reviewers).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // remove full list - - session.update().set(book::reviewers, null).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::reviewers, null).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualSet); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - - + + } - + private void assertEqualSets(Set expected, Set actual) { Assert.assertEquals(expected.size(), actual.size()); - + for (Author e : expected) { Author a = actual.stream().filter(p -> p.name().equals(e.name())).findFirst().get(); Assert.assertEquals(e.city(), a.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleValueMapTest.java b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleValueMapTest.java similarity index 68% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleValueMapTest.java rename to src/test/java/net/helenus/test/integration/core/tuplecollection/TupleValueMapTest.java index 4e543b9..e8b36cf 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/TupleValueMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/tuplecollection/TupleValueMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,125 +13,123 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +package net.helenus.test.integration.core.tuplecollection; import java.util.HashMap; import java.util.Map; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class TupleValueMapTest extends TupleCollectionTest { - + @Test public void testValueMapCRUID() { - + int id = 999; - + Map contents = new HashMap(); contents.put(1, new SectionImpl("first", 1)); contents.put(2, new SectionImpl("second", 2)); - + // CREATE - + session.insert() .value(book::id, id) .value(book::contents, contents) .sync(); - + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(contents, actual.contents()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.writers()); Assert.assertNull(actual.notes()); - + // read full map - - Map actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + + Map actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(contents, actualMap); - + // read single key-value in map - - String cql = session.select(get(book::contents, 1)) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.get(book::contents, 1)) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put(4, new SectionImpl("4", 4)); expected.put(5, new SectionImpl("5", 5)); - - session.update().set(book::contents, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + session.update().set(book::contents, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.contents()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); - + expected.put(3, third); - session.update().put(book::contents, 3, third).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::contents, 3, third).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(contents); - session.update().putAll(book::contents, contents).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().putAll(book::contents, contents).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + third = new SectionImpl("t-replace", 3); expected.put(3, third); - session.update().put(book::contents, 3, third).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::contents, 3, third).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(3); - session.update().put(book::contents, 3, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::contents, 3, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - - session.update().set(book::contents, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::contents, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::contents).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Integer i : expected.keySet()) { @@ -140,9 +138,9 @@ public class TupleValueMapTest extends TupleCollectionTest { Assert.assertEquals(e.title(), a.title()); Assert.assertEquals(e.page(), a.page()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Author.java b/src/test/java/net/helenus/test/integration/core/udtcollection/Author.java similarity index 80% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/Author.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/Author.java index 7c6f738..d1a4893 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Author.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/Author.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.udtcollection; -import com.noorq.casser.mapping.annotation.UDT; +import net.helenus.mapping.annotation.UDT; @UDT public interface Author { String name(); - + String city(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Book.java b/src/test/java/net/helenus/test/integration/core/udtcollection/Book.java similarity index 79% rename from src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Book.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/Book.java index a78b582..894f7e3 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/tuplecollection/Book.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.tuplecollection; +package net.helenus.test.integration.core.udtcollection; import java.util.List; import java.util.Map; import java.util.Set; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; @Table public interface Book { @PartitionKey int id(); - + List authors(); Set reviewers(); - + Map contents(); - + Map notes(); - + Map writers(); } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Section.java b/src/test/java/net/helenus/test/integration/core/udtcollection/Section.java similarity index 80% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/Section.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/Section.java index 1a415a8..1638603 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/Section.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/Section.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.udtcollection; -import com.noorq.casser.mapping.annotation.UDT; +import net.helenus.mapping.annotation.UDT; @UDT public interface Section { String title(); - + int page(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTCollectionTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTCollectionTest.java similarity index 84% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTCollectionTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTCollectionTest.java index 2dec057..b304b1f 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTCollectionTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTCollectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,41 +13,43 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.udtcollection; +import net.helenus.core.HelenusSession; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; +import net.helenus.core.Helenus; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; public abstract class UDTCollectionTest extends AbstractEmbeddedCassandraTest { - static Book book = Casser.dsl(Book.class); - - static CasserSession session; + static Book book; + + static HelenusSession session; @BeforeClass - public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(book).autoCreateDrop().get(); + public static void beforeTest(){ + Helenus.clearDslCache(); + session = Helenus.init(getSession()).showCql().add(Book.class).autoCreateDrop().get(); + book = Helenus.dsl(Book.class); } - + @Test public void test() { - System.out.println(book); + System.out.println(book); } - + public static final class AuthorImpl implements Author { String name; String city; - + AuthorImpl(String name, String city) { this.name = name; this.city = city; } - + @Override public String name() { return name; @@ -93,19 +95,19 @@ public abstract class UDTCollectionTest extends AbstractEmbeddedCassandraTest { public String toString() { return "AuthorImpl [name=" + name + ", city=" + city + "]"; } - + } public static final class SectionImpl implements Section { String title; int page; - + SectionImpl(String title, int page) { this.title = title; this.page = page; } - + @Override public String title() { return title; @@ -148,10 +150,10 @@ public abstract class UDTCollectionTest extends AbstractEmbeddedCassandraTest { public String toString() { return "SectionImpl [title=" + title + ", page=" + page + "]"; } - + } - - + + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTKeyMapTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTKeyMapTest.java similarity index 91% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTKeyMapTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTKeyMapTest.java index 3961e81..ddcfca2 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTKeyMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTKeyMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.udtcollection; -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +import static net.helenus.core.Query.eq; +import static net.helenus.core.Query.get; import java.util.HashMap; import java.util.Map; @@ -25,112 +25,112 @@ import org.junit.Assert; import org.junit.Test; public class UDTKeyMapTest extends UDTCollectionTest { - + @Test public void testKeyMapCRUID() { - + int id = 888; - + Map notes = new HashMap(); notes.put(new SectionImpl("first", 1), "value1"); notes.put(new SectionImpl("second", 2), "value2"); - + // CREATE - + session.insert() - .value(book::id, id) - .value(book::notes, notes) - .sync(); - + .value(book::id, id) + .value(book::notes, notes) + .sync(); + // READ - + // read full object - + Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(notes, actual.notes()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.writers()); Assert.assertNull(actual.contents()); - + // read full map - + Map actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(notes, actualMap); - + // read single key-value in map - + String cql = session.select(get(book::notes, new SectionImpl("first", 1))) .where(book::id, eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put(new SectionImpl("f", 1), "v1"); expected.put(new SectionImpl("s", 1), "v2"); - + session.update().set(book::notes, expected).where(book::id, eq(id)).sync(); - + actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.notes()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); - + expected.put(third, "v3"); session.update().put(book::notes, third, "v3").where(book::id, eq(id)).sync(); - + actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(notes); session.update().putAll(book::notes, notes).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + expected.put(third, "v33"); session.update().put(book::notes, third, "v33").where(book::id, eq(id)).sync(); - + actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(third); session.update().put(book::notes, third, null).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - + session.update().set(book::notes, null).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::notes).where(book::id, eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - + session.delete().where(book::id, eq(id)).sync(); Long cnt = session.count().where(book::id, eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Section e : expected.keySet()) { @@ -139,9 +139,9 @@ public class UDTKeyMapTest extends UDTCollectionTest { Assert.assertEquals(e.page(), a.page()); Assert.assertEquals(expected.get(e), actual.get(a)); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTListTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTListTest.java similarity index 65% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTListTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTListTest.java index 31a5bab..5769631 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTListTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTListTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,156 +13,154 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.getIdx; +package net.helenus.test.integration.core.udtcollection; import java.util.ArrayList; import java.util.List; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class UDTListTest extends UDTCollectionTest { - + @Test public void testListCRUID() { - + int id = 777; - + List authors = new ArrayList(); authors.add(new AuthorImpl("Alex", "San Jose")); authors.add(new AuthorImpl("Bob", "San Francisco")); - + // CREATE - + session.insert() .value(book::id, id) .value(book::authors, authors) .sync(); - + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualLists(authors, actual.authors()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.contents()); - + // read full list - - List actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + + List actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(authors, actualList); - + // read single value by index - - String cql = session.select(getIdx(book::authors, 1)) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.getIdx(book::authors, 1)) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + List expected = new ArrayList(); expected.add(new AuthorImpl("Unknown", "City 17")); - - session.update().set(book::authors, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + session.update().set(book::authors, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualLists(expected, actual.authors()); - + // INSERT - + // prepend operation - + expected.add(0, new AuthorImpl("Prepend", "PrependCity")); - session.update().prepend(book::authors, new AuthorImpl("Prepend", "PrependCity")).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().prepend(book::authors, new AuthorImpl("Prepend", "PrependCity")).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // append operation - + expected.add(new AuthorImpl("Append", "AppendCity")); - session.update().append(book::authors, new AuthorImpl("Append", "AppendCity")).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().append(book::authors, new AuthorImpl("Append", "AppendCity")).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // prependAll operation expected.addAll(0, authors); - session.update().prependAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().prependAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // appendAll operation expected.addAll(authors); - session.update().appendAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().appendAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // set by Index - + Author inserted = new AuthorImpl("Insert", "InsertCity"); expected.set(5, inserted); - session.update().setIdx(book::authors, 5, inserted).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().setIdx(book::authors, 5, inserted).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // DELETE - + // remove single value - + expected.remove(inserted); - session.update().discard(book::authors, inserted).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().discard(book::authors, inserted).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // remove values - + expected.removeAll(authors); - session.update().discardAll(book::authors, authors).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().discardAll(book::authors, authors).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualLists(expected, actualList); - + // remove full list - - session.update().set(book::authors, null).where(book::id, eq(id)).sync(); - - actualList = session.select(book::authors).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::authors, null).where(book::id, Query.eq(id)).sync(); + + actualList = session.select(book::authors).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualList); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualLists(List expected, List actual) { Assert.assertEquals(expected.size(), actual.size()); - + int size = expected.size(); - + for (int i = 0; i != size; ++i) { Author e = expected.get(i); Author a = actual.get(i); Assert.assertEquals(e.name(), a.name()); Assert.assertEquals(e.city(), a.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTMapTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTMapTest.java similarity index 68% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTMapTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTMapTest.java index 7576243..9b88da7 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,143 +13,139 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; - -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +package net.helenus.test.integration.core.udtcollection; import java.util.HashMap; import java.util.Map; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.test.integration.core.udtcollection.UDTCollectionTest.AuthorImpl; - public class UDTMapTest extends UDTCollectionTest { - + @Test public void testMapCRUID() { - + int id = 333; - + Map writers = new HashMap(); writers.put(new SectionImpl("first", 1), new AuthorImpl("Alex", "San Jose")); writers.put(new SectionImpl("second", 2), new AuthorImpl("Bob", "San Francisco")); - + // CREATE - + session.insert() .value(book::id, id) .value(book::writers, writers) .sync(); - + // READ - + // read full object - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(writers, actual.writers()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.notes()); Assert.assertNull(actual.contents()); - + // read full map - - Map actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + + Map actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(writers, actualMap); - + // read single key-value in map - - String cql = session.select(get(book::writers, new SectionImpl("first", 1))) - .where(book::id, eq(id)).cql(); + + String cql = session.select(Query.get(book::writers, new SectionImpl("first", 1))) + .where(book::id, Query.eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put(new SectionImpl("f", 1), new AuthorImpl("A", "SJ")); expected.put(new SectionImpl("s", 1), new AuthorImpl("B", "SF")); - - session.update().set(book::writers, expected).where(book::id, eq(id)).sync(); - - actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + session.update().set(book::writers, expected).where(book::id, Query.eq(id)).sync(); + + actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.writers()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); Author unk = new AuthorImpl("Unk", "City 17"); - + expected.put(third, unk); - session.update().put(book::writers, third, unk).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, unk).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(writers); - session.update().putAll(book::writers, writers).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().putAll(book::writers, writers).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + expected.put(third, unk); - session.update().put(book::writers, third, unk).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, unk).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(third); - session.update().put(book::writers, third, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().put(book::writers, third, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - - session.update().set(book::writers, null).where(book::id, eq(id)).sync(); - - actualMap = session.select(book::writers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::writers, null).where(book::id, Query.eq(id)).sync(); + + actualMap = session.select(book::writers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Section e : expected.keySet()) { Section a = actual.keySet().stream().filter(p -> p.title().equals(e.title())).findFirst().get(); Assert.assertEquals(e.title(), a.title()); Assert.assertEquals(e.page(), a.page()); - + Author ea = expected.get(e); Author aa = actual.get(a); - + Assert.assertEquals(ea.name(), aa.name()); Assert.assertEquals(ea.city(), aa.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTSetTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTSetTest.java similarity index 65% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTSetTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTSetTest.java index 3f57529..1ea52d0 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTSetTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTSetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,113 +13,112 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.udtcollection; import java.util.HashSet; import java.util.Set; +import net.helenus.core.Query; import org.junit.Assert; import org.junit.Test; public class UDTSetTest extends UDTCollectionTest { - + @Test public void testSetCRUID() { - + int id = 555; - + // CREATE - + Set reviewers = new HashSet(); reviewers.add(new AuthorImpl("Alex", "San Jose")); reviewers.add(new AuthorImpl("Bob", "San Francisco")); - + session.insert() - .value(book::id, id) - .value(book::reviewers, reviewers) - .sync(); - + .value(book::id, id) + .value(book::reviewers, reviewers) + .sync(); + // READ - - Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); + + Book actual = session.select(Book.class).where(book::id, Query.eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualSets(reviewers, actual.reviewers()); - + // UPDATE - + Set expected = new HashSet(); expected.add(new AuthorImpl("Craig", "Los Altos")); - - session.update().set(book::reviewers, expected).where(book::id, eq(id)).sync(); - - Set actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::reviewers, expected).where(book::id, Query.eq(id)).sync(); + + Set actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // add operation - + expected.add(new AuthorImpl("Add", "AddCity")); session.update().add(book::reviewers, new AuthorImpl("Add", "AddCity")) - .where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + .where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // addAll operation expected.addAll(reviewers); - session.update().addAll(book::reviewers, reviewers).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().addAll(book::reviewers, reviewers).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // DELETE - + // remove single value - + Author a = expected.stream().filter(p -> p.name().equals("Add")).findFirst().get(); expected.remove(a); - - session.update().remove(book::reviewers, a).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().remove(book::reviewers, a).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // remove values - + expected.remove(expected.stream().filter(p -> p.name().equals("Alex")).findFirst().get()); expected.remove(expected.stream().filter(p -> p.name().equals("Bob")).findFirst().get()); - session.update().removeAll(book::reviewers, reviewers).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + session.update().removeAll(book::reviewers, reviewers).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; assertEqualSets(expected, actualSet); - + // remove full list - - session.update().set(book::reviewers, null).where(book::id, eq(id)).sync(); - - actualSet = session.select(book::reviewers).where(book::id, eq(id)).sync().findFirst().get()._1; + + session.update().set(book::reviewers, null).where(book::id, Query.eq(id)).sync(); + + actualSet = session.select(book::reviewers).where(book::id, Query.eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualSet); - + // remove object - - session.delete().where(book::id, eq(id)).sync(); - Long cnt = session.count().where(book::id, eq(id)).sync(); + + session.delete().where(book::id, Query.eq(id)).sync(); + Long cnt = session.count().where(book::id, Query.eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - - + + } - + private void assertEqualSets(Set expected, Set actual) { Assert.assertEquals(expected.size(), actual.size()); - + for (Author e : expected) { Author a = actual.stream().filter(p -> p.name().equals(e.name())).findFirst().get(); Assert.assertEquals(e.city(), a.city()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTValueMapTest.java b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTValueMapTest.java similarity index 92% rename from src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTValueMapTest.java rename to src/test/java/net/helenus/test/integration/core/udtcollection/UDTValueMapTest.java index 3936415..1e0ce65 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/udtcollection/UDTValueMapTest.java +++ b/src/test/java/net/helenus/test/integration/core/udtcollection/UDTValueMapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.udtcollection; +package net.helenus.test.integration.core.udtcollection; -import static com.noorq.casser.core.Query.eq; -import static com.noorq.casser.core.Query.get; +import static net.helenus.core.Query.eq; +import static net.helenus.core.Query.get; import java.util.HashMap; import java.util.Map; @@ -25,113 +25,113 @@ import org.junit.Assert; import org.junit.Test; public class UDTValueMapTest extends UDTCollectionTest { - + @Test public void testValueMapCRUID() { - + int id = 999; - + Map contents = new HashMap(); contents.put(1, new SectionImpl("first", 1)); contents.put(2, new SectionImpl("second", 2)); - + // CREATE - + session.insert() .value(book::id, id) .value(book::contents, contents) .sync(); - + // READ - + // read full object - + Book actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(contents, actual.contents()); Assert.assertNull(actual.reviewers()); Assert.assertNull(actual.writers()); Assert.assertNull(actual.notes()); - + // read full map - + Map actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(contents, actualMap); - + // read single key-value in map - + String cql = session.select(get(book::contents, 1)) .where(book::id, eq(id)).cql(); System.out.println("Still not supporting cql = " + cql); - + // UPDATE - + Map expected = new HashMap(); expected.put(4, new SectionImpl("4", 4)); expected.put(5, new SectionImpl("5", 5)); - + session.update().set(book::contents, expected).where(book::id, eq(id)).sync(); - + actual = session.select(Book.class).where(book::id, eq(id)).sync().findFirst().get(); Assert.assertEquals(id, actual.id()); assertEqualMaps(expected, actual.contents()); - + // INSERT - + // put operation - + Section third = new SectionImpl("t", 3); - + expected.put(3, third); session.update().put(book::contents, 3, third).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // putAll operation expected.putAll(contents); session.update().putAll(book::contents, contents).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // put existing - + third = new SectionImpl("t-replace", 3); expected.put(3, third); session.update().put(book::contents, 3, third).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // DELETE - + // remove single key - + expected.remove(3); session.update().put(book::contents, 3, null).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; assertEqualMaps(expected, actualMap); - + // remove full map - + session.update().set(book::contents, null).where(book::id, eq(id)).sync(); - + actualMap = session.select(book::contents).where(book::id, eq(id)).sync().findFirst().get()._1; Assert.assertNull(actualMap); - + // remove object - + session.delete().where(book::id, eq(id)).sync(); Long cnt = session.count().where(book::id, eq(id)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + private void assertEqualMaps(Map expected, Map actual) { - + Assert.assertEquals(expected.size(), actual.size()); for (Integer i : expected.keySet()) { @@ -140,9 +140,9 @@ public class UDTValueMapTest extends UDTCollectionTest { Assert.assertEquals(e.title(), a.title()); Assert.assertEquals(e.page(), a.page()); } - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/Account.java b/src/test/java/net/helenus/test/integration/core/usertype/Account.java similarity index 71% rename from src/test/java/com/noorq/casser/test/integration/core/usertype/Account.java rename to src/test/java/net/helenus/test/integration/core/usertype/Account.java index 1ec2d01..e8ea377 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/Account.java +++ b/src/test/java/net/helenus/test/integration/core/usertype/Account.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,25 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.usertype; +package net.helenus.test.integration.core.usertype; import com.datastax.driver.core.UDTValue; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface Account { @PartitionKey(ordinal=0) long id(); - + @Column Address address(); - + @Types.UDT("address") @Column UDTValue addressNoMapping(); - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/Address.java b/src/test/java/net/helenus/test/integration/core/usertype/Address.java similarity index 77% rename from src/test/java/com/noorq/casser/test/integration/core/usertype/Address.java rename to src/test/java/net/helenus/test/integration/core/usertype/Address.java index 12f1939..6138ee2 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/Address.java +++ b/src/test/java/net/helenus/test/integration/core/usertype/Address.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.usertype; +package net.helenus.test.integration.core.usertype; import java.util.Set; import com.datastax.driver.core.DataType; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Types; -import com.noorq.casser.mapping.annotation.UDT; +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.Types; +import net.helenus.mapping.annotation.UDT; @UDT("address") public interface Address { @@ -36,7 +36,7 @@ public interface Address { @Column String country(); - + @Column @Types.Set(DataType.Name.TEXT) Set phones(); diff --git a/src/test/java/net/helenus/test/integration/core/usertype/AddressInformation.java b/src/test/java/net/helenus/test/integration/core/usertype/AddressInformation.java new file mode 100644 index 0000000..f541f75 --- /dev/null +++ b/src/test/java/net/helenus/test/integration/core/usertype/AddressInformation.java @@ -0,0 +1,12 @@ +package net.helenus.test.integration.core.usertype; + +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.UDT; + +@UDT +public interface AddressInformation { + + @Column + Address address(); + +} diff --git a/src/test/java/net/helenus/test/integration/core/usertype/Customer.java b/src/test/java/net/helenus/test/integration/core/usertype/Customer.java new file mode 100644 index 0000000..8a0461a --- /dev/null +++ b/src/test/java/net/helenus/test/integration/core/usertype/Customer.java @@ -0,0 +1,18 @@ +package net.helenus.test.integration.core.usertype; + +import java.util.UUID; + +import net.helenus.mapping.annotation.Column; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; + +@Table +public interface Customer { + + @PartitionKey + UUID id(); + + @Column + AddressInformation addressInformation(); + +} diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/InnerUserDefinedTypeTest.java b/src/test/java/net/helenus/test/integration/core/usertype/InnerUserDefinedTypeTest.java similarity index 58% rename from src/test/java/com/noorq/casser/test/integration/core/usertype/InnerUserDefinedTypeTest.java rename to src/test/java/net/helenus/test/integration/core/usertype/InnerUserDefinedTypeTest.java index 1d3c854..56e6973 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/InnerUserDefinedTypeTest.java +++ b/src/test/java/net/helenus/test/integration/core/usertype/InnerUserDefinedTypeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,46 +13,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.usertype; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.usertype; import java.util.Set; import java.util.UUID; +import net.helenus.core.Helenus; +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; +import net.helenus.core.SchemaUtil; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.Sets; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; public class InnerUserDefinedTypeTest extends AbstractEmbeddedCassandraTest { - static Customer customer = Casser.dsl(Customer.class); - static AddressInformation accountInformation = Casser.dsl(AddressInformation.class); - - static CasserSession session; - - + static Customer customer; + static AddressInformation addressInformation; + + static HelenusSession session; + + @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(Customer.class).autoCreateDrop().get(); + Helenus.clearDslCache(); + session = Helenus.init(getSession()).showCql().add(Customer.class).autoCreateDrop().get(); + customer = Helenus.dsl(Customer.class); + addressInformation = Helenus.dsl(AddressInformation.class); } - - @Test + + @AfterClass + public static void afterTest() { + session.getSession().execute("DROP TABLE IF EXISTS customer;"); + session.getSession().execute("DROP TYPE IF EXISTS address_information;"); +// SchemaUtil.dropUserType(session.getSessionRepository().findUserType("address_information")), true); + } + + @Test public void testPrint() { - System.out.println(accountInformation); + System.out.println(addressInformation); System.out.println(customer); } - + @Test public void testCrud() { - + UUID id = UUID.randomUUID(); - + Address a = new Address() { @Override @@ -79,49 +90,49 @@ public class InnerUserDefinedTypeTest extends AbstractEmbeddedCassandraTest { public Set phones() { return Sets.newHashSet("14080000000"); } - + }; - - + + AddressInformation ai = new AddressInformation() { @Override public Address address() { return a; } - + }; - + session.insert() .value(customer::id, id) .value(customer::addressInformation, ai) .sync(); - + String cql = session.update() .set(customer.addressInformation().address()::street, "3 st") - .where(customer::id, eq(id)).cql(); + .where(customer::id, Query.eq(id)).cql(); - System.out.println("At the time when this test was written Cassandra did not support querties like this: " + cql); + //TODO: System.out.println("At the time when this test was written Cassandra did not support queries like this: " + cql); session.update() .set(customer::addressInformation, ai) - .where(customer::id, eq(id)) + .where(customer::id, Query.eq(id)) .sync(); String street = session.select(customer.addressInformation().address()::street) - .where(customer::id, eq(id)) + .where(customer::id, Query.eq(id)) .sync() .findFirst() .get()._1; - + Assert.assertEquals("1 st", street); - - session.delete().where(customer::id, eq(id)).sync(); - - Long cnt = session.count().where(customer::id, eq(id)).sync(); - + + session.delete().where(customer::id, Query.eq(id)).sync(); + + Long cnt = session.count().where(customer::id, Query.eq(id)).sync(); + Assert.assertEquals(Long.valueOf(0), cnt); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/integration/core/usertype/UserDefinedTypeTest.java b/src/test/java/net/helenus/test/integration/core/usertype/UserDefinedTypeTest.java similarity index 76% rename from src/test/java/com/noorq/casser/test/integration/core/usertype/UserDefinedTypeTest.java rename to src/test/java/net/helenus/test/integration/core/usertype/UserDefinedTypeTest.java index 9e576a7..bf1af4c 100644 --- a/src/test/java/com/noorq/casser/test/integration/core/usertype/UserDefinedTypeTest.java +++ b/src/test/java/net/helenus/test/integration/core/usertype/UserDefinedTypeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,35 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.integration.core.usertype; - -import static com.noorq.casser.core.Query.eq; +package net.helenus.test.integration.core.usertype; import java.util.Set; +import net.helenus.core.Helenus; +import net.helenus.core.HelenusSession; +import net.helenus.core.Query; +import net.helenus.test.integration.build.AbstractEmbeddedCassandraTest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.CasserSession; -import com.noorq.casser.test.integration.build.AbstractEmbeddedCassandraTest; public class UserDefinedTypeTest extends AbstractEmbeddedCassandraTest { - static Address address = Casser.dsl(Address.class); - static Account account = Casser.dsl(Account.class); - - static CasserSession session; - + static Address address; + static Account account; + + static HelenusSession session; + public static class AccountImpl implements Account { long id; Address address; UDTValue addressNoMapping; - + @Override public long id() { return id; @@ -56,9 +55,9 @@ public class UserDefinedTypeTest extends AbstractEmbeddedCassandraTest { public UDTValue addressNoMapping() { return addressNoMapping; } - + } - + public static class AddressImpl implements Address { String street; @@ -66,7 +65,7 @@ public class UserDefinedTypeTest extends AbstractEmbeddedCassandraTest { int zip; String country; Set phones; - + @Override public String street() { return street; @@ -91,126 +90,128 @@ public class UserDefinedTypeTest extends AbstractEmbeddedCassandraTest { public Set phones() { return phones; } - + } - - + + @BeforeClass public static void beforeTest() { - session = Casser.init(getSession()).showCql().add(Account.class).autoCreateDrop().get(); + session = Helenus.init(getSession()).showCql().add(Account.class).autoCreateDrop().get(); + address = Helenus.dsl(Address.class); + account = Helenus.dsl(Account.class); } - + @Test public void testPrint() { System.out.println(address); System.out.println(account); } - + @Test public void testMappingCRUID() { - + AddressImpl addr = new AddressImpl(); addr.street = "1 st"; addr.city = "San Jose"; - + AccountImpl acc = new AccountImpl(); acc.id = 123L; acc.address = addr; // CREATE - + session.upsert(acc).sync(); - + // READ - - String streetName = session.select(account.address()::street).where(account::id, eq(123L)).sync().findFirst().get()._1; - + + String streetName = session.select(account.address()::street).where(account::id, Query.eq(123L)).sync().findFirst().get()._1; + Assert.assertEquals("1 st", streetName); - + // UPDATE - + AddressImpl expected = new AddressImpl(); expected.street = "2 st"; expected.city = "San Francisco"; - - session.update().set(account::address, expected).where(account::id, eq(123L)).sync(); - Address actual = session.select(account::address).where(account::id, eq(123L)).sync().findFirst().get()._1; + session.update().set(account::address, expected).where(account::id, Query.eq(123L)).sync(); + + Address actual = session.select(account::address).where(account::id, Query.eq(123L)).sync().findFirst().get()._1; Assert.assertEquals(expected.street(), actual.street()); Assert.assertEquals(expected.city(), actual.city()); Assert.assertNull(actual.country()); Assert.assertEquals(0, actual.zip()); - + // INSERT - - session.update().set(account::address, null).where(account::id, eq(123L)).sync(); - - Address adrNull = session.select(account::address).where(account::id, eq(123L)).sync().findFirst().get()._1; + + session.update().set(account::address, null).where(account::id, Query.eq(123L)).sync(); + + Address adrNull = session.select(account::address).where(account::id, Query.eq(123L)).sync().findFirst().get()._1; Assert.assertNull(adrNull); - + // DELETE - - session.delete().where(account::id, eq(123L)).sync(); - - Long cnt = session.count().where(account::id, eq(123L)).sync(); + + session.delete().where(account::id, Query.eq(123L)).sync(); + + Long cnt = session.count().where(account::id, Query.eq(123L)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); - + } - + @Test public void testNoMapping() { - + String ks = getSession().getLoggedKeyspace(); UserType addressType = getSession().getCluster().getMetadata().getKeyspace(ks).getUserType("address"); - + UDTValue addressNoMapping = addressType.newValue(); addressNoMapping.setString("line_1", "1st street"); addressNoMapping.setString("city", "San Jose"); - + AccountImpl acc = new AccountImpl(); acc.id = 777L; acc.addressNoMapping = addressNoMapping; // CREATE - + session.upsert(acc).sync(); - + // READ - - UDTValue found = session.select(account::addressNoMapping).where(account::id, eq(777L)).sync().findFirst().get()._1; - + + UDTValue found = session.select(account::addressNoMapping).where(account::id, Query.eq(777L)).sync().findFirst().get()._1; + Assert.assertEquals(addressNoMapping.getType(), found.getType()); Assert.assertEquals(addressNoMapping.getString("line_1"), found.getString("line_1")); Assert.assertEquals(addressNoMapping.getString("city"), found.getString("city")); - + // UPDATE addressNoMapping = addressType.newValue(); addressNoMapping.setString("line_1", "Market street"); addressNoMapping.setString("city", "San Francisco"); - - session.update().set(account::addressNoMapping, addressNoMapping).where(account::id, eq(777L)).sync(); - found = session.select(account::addressNoMapping).where(account::id, eq(777L)).sync().findFirst().get()._1; - + session.update().set(account::addressNoMapping, addressNoMapping).where(account::id, Query.eq(777L)).sync(); + + found = session.select(account::addressNoMapping).where(account::id, Query.eq(777L)).sync().findFirst().get()._1; + Assert.assertEquals(addressNoMapping.getType(), found.getType()); Assert.assertEquals(addressNoMapping.getString("line_1"), found.getString("line_1")); Assert.assertEquals(addressNoMapping.getString("city"), found.getString("city")); - - // INSERT - - session.update().set(account::addressNoMapping, null).where(account::id, eq(777L)).sync(); - found = session.select(account::addressNoMapping).where(account::id, eq(777L)).sync().findFirst().get()._1; + // INSERT + + session.update().set(account::addressNoMapping, null).where(account::id, Query.eq(777L)).sync(); + + found = session.select(account::addressNoMapping).where(account::id, Query.eq(777L)).sync().findFirst().get()._1; Assert.assertNull(found); - + // DELETE - - session.delete().where(account::id, eq(777L)).sync(); - - Long cnt = session.count().where(account::id, eq(777L)).sync(); + + session.delete().where(account::id, Query.eq(777L)).sync(); + + Long cnt = session.count().where(account::id, Query.eq(777L)).sync(); Assert.assertEquals(Long.valueOf(0), cnt); } diff --git a/src/test/java/com/noorq/casser/test/performance/core/dsl/CachedElevatorImpl.java b/src/test/java/net/helenus/test/performance/core/dsl/CachedElevatorImpl.java similarity index 89% rename from src/test/java/com/noorq/casser/test/performance/core/dsl/CachedElevatorImpl.java rename to src/test/java/net/helenus/test/performance/core/dsl/CachedElevatorImpl.java index 93950cf..26a91ec 100644 --- a/src/test/java/com/noorq/casser/test/performance/core/dsl/CachedElevatorImpl.java +++ b/src/test/java/net/helenus/test/performance/core/dsl/CachedElevatorImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,36 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.performance.core.dsl; +package net.helenus.test.performance.core.dsl; import java.util.Map; -import com.noorq.casser.core.reflect.MapExportable; +import net.helenus.core.reflect.MapExportable; public final class CachedElevatorImpl implements Elevator, MapExportable { private final Map backingMap; - + private int mask = 0; - + private int height; private Double price; private String name; - + public CachedElevatorImpl(Map backingMap) { this.backingMap = backingMap; } - + @Override public int height() { - + if ((mask & 1) == 0) { Object obj = backingMap.get("height"); if (obj != null) { height = ((Integer) obj).intValue(); } - + mask &= 1; } return height; @@ -50,14 +50,14 @@ public final class CachedElevatorImpl implements Elevator, MapExportable { @Override public Double price() { - + if ((mask & 2) == 0) { - + Object obj = backingMap.get("price"); if (obj != null) { price = (Double) obj; } - + mask &= 2; } return price; @@ -65,14 +65,14 @@ public final class CachedElevatorImpl implements Elevator, MapExportable { @Override public String name() { - + if ((mask & 4) == 0) { - + Object obj = backingMap.get("name"); if (obj != null) { name = (String) obj; } - + mask &= 4; } return name; @@ -87,5 +87,5 @@ public final class CachedElevatorImpl implements Elevator, MapExportable { public String toString() { return backingMap.toString(); } - + } diff --git a/src/test/java/com/noorq/casser/test/performance/core/dsl/Elevator.java b/src/test/java/net/helenus/test/performance/core/dsl/Elevator.java similarity index 86% rename from src/test/java/com/noorq/casser/test/performance/core/dsl/Elevator.java rename to src/test/java/net/helenus/test/performance/core/dsl/Elevator.java index 2c38486..41cd489 100644 --- a/src/test/java/com/noorq/casser/test/performance/core/dsl/Elevator.java +++ b/src/test/java/net/helenus/test/performance/core/dsl/Elevator.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.performance.core.dsl; +package net.helenus.test.performance.core.dsl; public interface Elevator { int height(); - + Double price(); - + String name(); - + } diff --git a/src/test/java/com/noorq/casser/test/performance/core/dsl/ElevatorImpl.java b/src/test/java/net/helenus/test/performance/core/dsl/ElevatorImpl.java similarity index 90% rename from src/test/java/com/noorq/casser/test/performance/core/dsl/ElevatorImpl.java rename to src/test/java/net/helenus/test/performance/core/dsl/ElevatorImpl.java index 145a795..14464ef 100644 --- a/src/test/java/com/noorq/casser/test/performance/core/dsl/ElevatorImpl.java +++ b/src/test/java/net/helenus/test/performance/core/dsl/ElevatorImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.performance.core.dsl; +package net.helenus.test.performance.core.dsl; import java.util.Map; -import com.noorq.casser.core.reflect.MapExportable; +import net.helenus.core.reflect.MapExportable; public final class ElevatorImpl implements Elevator, MapExportable { private final Map backingMap; - + public ElevatorImpl(Map backingMap) { this.backingMap = backingMap; } - + @Override public int height() { Object obj = backingMap.get("height"); @@ -63,5 +63,5 @@ public final class ElevatorImpl implements Elevator, MapExportable { public String toString() { return backingMap.toString(); } - + } diff --git a/src/test/java/com/noorq/casser/test/performance/core/dsl/MappingTest.java b/src/test/java/net/helenus/test/performance/core/dsl/MappingTest.java similarity index 89% rename from src/test/java/com/noorq/casser/test/performance/core/dsl/MappingTest.java rename to src/test/java/net/helenus/test/performance/core/dsl/MappingTest.java index 70ed526..efa69ad 100644 --- a/src/test/java/com/noorq/casser/test/performance/core/dsl/MappingTest.java +++ b/src/test/java/net/helenus/test/performance/core/dsl/MappingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,58 +13,58 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.performance.core.dsl; +package net.helenus.test.performance.core.dsl; import java.util.HashMap; import java.util.Map; import org.junit.Test; -import com.noorq.casser.core.Casser; +import net.helenus.core.Helenus; public class MappingTest { static Map fixture; - + static { fixture = new HashMap(); fixture.put("height", Integer.valueOf(55)); fixture.put("price", Double.valueOf(44.99)); fixture.put("name", "first"); } - + @Test public void testReflectionConstructor() { - - long t0 = System.currentTimeMillis(); - - for (int i = 0; i != 100000; ++i) { - Casser.map(Elevator.class, fixture); - } - - long t1 = System.currentTimeMillis() - t0; - - System.out.println("ReflectionConstructor = " + t1); - } - - @Test - public void testReflectionAccess() { - + long t0 = System.currentTimeMillis(); - Elevator elevator = Casser.map(Elevator.class, fixture); + for (int i = 0; i != 100000; ++i) { + Helenus.map(Elevator.class, fixture); + } + + long t1 = System.currentTimeMillis() - t0; + + System.out.println("ReflectionConstructor = " + t1); + } + + @Test + public void testReflectionAccess() { + + long t0 = System.currentTimeMillis(); + + Elevator elevator = Helenus.map(Elevator.class, fixture); for (int i = 0; i != 100000; ++i) { elevator.height(); elevator.price(); elevator.name(); } - + long t1 = System.currentTimeMillis() - t0; - + System.out.println("ReflectionAccess = " + t1); } - + @Test public void testJavaAccess() { @@ -82,8 +82,8 @@ public class MappingTest { System.out.println("JavaAccess = " + t1); - } - + } + @Test public void testJavaCachedAccess() { @@ -101,8 +101,8 @@ public class MappingTest { System.out.println("JavaCachedAccess = " + t1); - } - + } + @Test public void testJavaConstructor() { @@ -116,6 +116,6 @@ public class MappingTest { System.out.println("JavaConstructor = " + t1); - } - + } + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/Account.java b/src/test/java/net/helenus/test/unit/core/dsl/Account.java similarity index 67% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/Account.java rename to src/test/java/net/helenus/test/unit/core/dsl/Account.java index d3a840d..9e585c0 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/Account.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/Account.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,27 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; import java.util.Date; -import com.noorq.casser.mapping.annotation.ClusteringColumn; -import com.noorq.casser.mapping.annotation.Column; -import com.noorq.casser.mapping.annotation.Index; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; +import net.helenus.mapping.annotation.*; @Table public interface Account { @PartitionKey Long id(); - + @ClusteringColumn Date time(); - + @Index @Column("is_active") boolean active(); - + + + @Transient + default Draft draft() { return new Draft(); } + class Draft {} + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/AccountWithCollections.java b/src/test/java/net/helenus/test/unit/core/dsl/AccountWithCollections.java similarity index 78% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/AccountWithCollections.java rename to src/test/java/net/helenus/test/unit/core/dsl/AccountWithCollections.java index 7697e8e..42c1b21 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/AccountWithCollections.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/AccountWithCollections.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,30 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; import java.util.List; import java.util.Map; import java.util.Set; import com.datastax.driver.core.DataType.Name; -import com.noorq.casser.mapping.annotation.PartitionKey; -import com.noorq.casser.mapping.annotation.Table; -import com.noorq.casser.mapping.annotation.Types; +import net.helenus.mapping.annotation.PartitionKey; +import net.helenus.mapping.annotation.Table; +import net.helenus.mapping.annotation.Types; @Table public interface AccountWithCollections { @PartitionKey long id(); - + @Types.Set(Name.TEXT) Set aliases(); - + @Types.List(Name.TEXT) List name(); - + @Types.Map(key=Name.TEXT, value=Name.TEXT) Map properties(); - + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/CollectionsDlsTest.java b/src/test/java/net/helenus/test/unit/core/dsl/CollectionsDlsTest.java similarity index 73% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/CollectionsDlsTest.java rename to src/test/java/net/helenus/test/unit/core/dsl/CollectionsDlsTest.java index b79324b..6672ab1 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/CollectionsDlsTest.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/CollectionsDlsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,75 +13,75 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; +import net.helenus.core.reflect.HelenusPropertyNode; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.core.Getter; -import com.noorq.casser.core.Query; -import com.noorq.casser.core.reflect.CasserPropertyNode; -import com.noorq.casser.support.DslPropertyException; +import net.helenus.core.Helenus; +import net.helenus.core.Getter; +import net.helenus.core.Query; +import net.helenus.support.DslPropertyException; public class CollectionsDlsTest { static AccountWithCollections account; - + @BeforeClass public static void beforeTests() { - account = Casser.dsl(AccountWithCollections.class); + account = Helenus.dsl(AccountWithCollections.class); } - + @Test public void testPrint() { System.out.println(account); } - + @Test public void testMapGet() { - + String columnName = null; - + Getter getter = Query.get(account::properties, "key1"); - + try { getter.get(); } catch(DslPropertyException e) { - - CasserPropertyNode node = e.getPropertyNode(); + + HelenusPropertyNode node = e.getPropertyNode(); columnName = node.getColumnName(); - + } - + Assert.assertEquals("\"properties\"[\"key1\"]", columnName); - + } - + @Test public void testListGet() { - + String columnName = null; - + Getter getter = Query.getIdx(account::name, 2); - + try { getter.get(); } catch(DslPropertyException e) { - - CasserPropertyNode node = e.getPropertyNode(); + + HelenusPropertyNode node = e.getPropertyNode(); columnName = node.getColumnName(); - + } - + Assert.assertEquals("\"name\"[\"2\"]", columnName); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/DslTest.java b/src/test/java/net/helenus/test/unit/core/dsl/DslTest.java similarity index 77% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/DslTest.java rename to src/test/java/net/helenus/test/unit/core/dsl/DslTest.java index 19781fb..658ae4a 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/DslTest.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/DslTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,21 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; +import net.helenus.core.Helenus; +import net.helenus.support.DslPropertyException; import org.junit.BeforeClass; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.support.DslPropertyException; - public class DslTest { static Account account; @BeforeClass public static void beforeTests() { - account = Casser.dsl(Account.class); + account = Helenus.dsl(Account.class); } @Test diff --git a/src/test/java/net/helenus/test/unit/core/dsl/Rocket.java b/src/test/java/net/helenus/test/unit/core/dsl/Rocket.java new file mode 100644 index 0000000..491abb0 --- /dev/null +++ b/src/test/java/net/helenus/test/unit/core/dsl/Rocket.java @@ -0,0 +1,12 @@ +package net.helenus.test.unit.core.dsl; + +import net.helenus.mapping.annotation.UDT; + +@UDT +public interface Rocket { + + int length(); + + double price(); + +} diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/UDTCollectionsDlsTest.java b/src/test/java/net/helenus/test/unit/core/dsl/UDTCollectionsDlsTest.java similarity index 85% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/UDTCollectionsDlsTest.java rename to src/test/java/net/helenus/test/unit/core/dsl/UDTCollectionsDlsTest.java index 9de59c1..db71dff 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/UDTCollectionsDlsTest.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/UDTCollectionsDlsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; import java.util.HashMap; import java.util.Map; @@ -21,40 +21,40 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.core.Casser; +import net.helenus.core.Helenus; public class UDTCollectionsDlsTest { @Test public void testMap() { - + Map comments = new HashMap(); Map firstMap = new HashMap(); firstMap.put("length", 100); firstMap.put("price", 100.0); - - Rocket first = Casser.map(Rocket.class, firstMap); + + Rocket first = Helenus.map(Rocket.class, firstMap); Map secondMap = new HashMap(); secondMap.put("length", 50); secondMap.put("price", 70.0); - - Rocket second = Casser.map(Rocket.class, secondMap); + + Rocket second = Helenus.map(Rocket.class, secondMap); Assert.assertEquals(first.hashCode(), first.hashCode()); Assert.assertEquals(second.hashCode(), second.hashCode()); - + Assert.assertFalse(first.equals(second)); Assert.assertTrue(first.equals(first)); Assert.assertTrue(second.equals(second)); - + comments.put(first, "fast"); comments.put(second, "nice"); - + Assert.assertEquals("fast", comments.get(first)); Assert.assertEquals("nice", comments.get(second)); - + } - + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/WrapperTest.java b/src/test/java/net/helenus/test/unit/core/dsl/WrapperTest.java similarity index 73% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/WrapperTest.java rename to src/test/java/net/helenus/test/unit/core/dsl/WrapperTest.java index 67bfc2b..3f50a83 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/WrapperTest.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/WrapperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; import java.util.HashMap; import java.util.Map; @@ -21,47 +21,47 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.core.Casser; -import com.noorq.casser.support.CasserException; +import net.helenus.core.Helenus; +import net.helenus.support.HelenusException; public class WrapperTest { - + @Test public void testWrap() throws Exception { - + Map map = new HashMap(); - + map.put("id", 123L); map.put("active", Boolean.TRUE); map.put("unknownField", "he-he"); - - Account account = Casser.map(Account.class, map); - + + Account account = Helenus.map(Account.class, map); + Assert.assertEquals(Long.valueOf(123L), account.id()); Assert.assertTrue(account.active()); - + } - + @Test public void testPrimitive() throws Exception { - + Map map = new HashMap(); - + map.put("id", 123L); - - Account account = Casser.map(Account.class, map); - + + Account account = Helenus.map(Account.class, map); + Assert.assertFalse(account.active()); - + } - - @Test(expected=CasserException.class) + + @Test(expected=HelenusException.class) public void testWrongMethods() throws Exception { - - WrongAccount wrongAccount = Casser.map(WrongAccount.class, new HashMap()); - + + WrongAccount wrongAccount = Helenus.map(WrongAccount.class, new HashMap()); + wrongAccount.id(); } - + } diff --git a/src/test/java/com/noorq/casser/test/unit/core/dsl/WrongAccount.java b/src/test/java/net/helenus/test/unit/core/dsl/WrongAccount.java similarity index 87% rename from src/test/java/com/noorq/casser/test/unit/core/dsl/WrongAccount.java rename to src/test/java/net/helenus/test/unit/core/dsl/WrongAccount.java index d188f94..d4143d1 100644 --- a/src/test/java/com/noorq/casser/test/unit/core/dsl/WrongAccount.java +++ b/src/test/java/net/helenus/test/unit/core/dsl/WrongAccount.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.core.dsl; +package net.helenus.test.unit.core.dsl; public interface WrongAccount { void id(); - + } diff --git a/src/test/java/com/noorq/casser/test/unit/support/ImmutablesTest.java b/src/test/java/net/helenus/test/unit/support/ImmutablesTest.java similarity index 91% rename from src/test/java/com/noorq/casser/test/unit/support/ImmutablesTest.java rename to src/test/java/net/helenus/test/unit/support/ImmutablesTest.java index 62a3583..24730d2 100644 --- a/src/test/java/com/noorq/casser/test/unit/support/ImmutablesTest.java +++ b/src/test/java/net/helenus/test/unit/support/ImmutablesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,94 +13,93 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.support; +package net.helenus.test.unit.support; import java.util.List; import java.util.Map; import java.util.Set; +import net.helenus.support.Immutables; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.support.Immutables; - public class ImmutablesTest { @Test public void testSet() { - + Set set = Immutables.setOf(123); - + Assert.assertEquals(1, set.size()); Assert.assertFalse(set.isEmpty()); - + Assert.assertTrue(set.contains(123)); Assert.assertFalse(set.contains(125)); - + int c = 0; for (Integer v : set) { Assert.assertEquals(Integer.valueOf(123), v); c++; } - + Assert.assertEquals(1, c); } - + @Test public void testList() { - + List list = Immutables.listOf(123); - + Assert.assertEquals(1, list.size()); Assert.assertFalse(list.isEmpty()); - + Assert.assertTrue(list.contains(123)); Assert.assertFalse(list.contains(125)); - + int c = 0; for (Integer v : list) { Assert.assertEquals(Integer.valueOf(123), v); c++; } - + Assert.assertEquals(1, c); } - + @Test public void testMap() { - + Map map = Immutables.mapOf(123, 555); - + Assert.assertEquals(1, map.size()); Assert.assertFalse(map.isEmpty()); - + Assert.assertTrue(map.containsKey(123)); Assert.assertFalse(map.containsKey(125)); - + int c = 0; for (Integer v : map.keySet()) { Assert.assertEquals(Integer.valueOf(123), v); c++; } - + Assert.assertEquals(1, c); - + c = 0; for (Integer v : map.values()) { Assert.assertEquals(Integer.valueOf(555), v); c++; } - + Assert.assertEquals(1, c); - + c = 0; for (Map.Entry e : map.entrySet()) { Assert.assertEquals(Integer.valueOf(123), e.getKey()); Assert.assertEquals(Integer.valueOf(555), e.getValue()); c++; } - + Assert.assertEquals(1, c); } - + } diff --git a/src/test/java/com/noorq/casser/test/unit/support/TransformersTest.java b/src/test/java/net/helenus/test/unit/support/TransformersTest.java similarity index 93% rename from src/test/java/com/noorq/casser/test/unit/support/TransformersTest.java rename to src/test/java/net/helenus/test/unit/support/TransformersTest.java index 3659353..fb23559 100644 --- a/src/test/java/com/noorq/casser/test/unit/support/TransformersTest.java +++ b/src/test/java/net/helenus/test/unit/support/TransformersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Casser Authors + * Copyright (C) 2015 The Helenus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.noorq.casser.test.unit.support; +package net.helenus.test.unit.support; import java.util.ArrayList; import java.util.Iterator; @@ -23,18 +23,18 @@ import java.util.ListIterator; import org.junit.Assert; import org.junit.Test; -import com.noorq.casser.support.Transformers; +import net.helenus.support.Transformers; public class TransformersTest { @Test public void testList() { - + List source = new ArrayList(); source.add(555); source.add(777); source.add(999); - + List out = Transformers.transformList(source, x -> "_" + x); Assert.assertEquals(3, out.size()); @@ -42,7 +42,7 @@ public class TransformersTest { Assert.assertEquals("_555", out.get(0)); Assert.assertEquals("_777", out.get(1)); Assert.assertEquals("_999", out.get(2)); - + Iterator i = out.iterator(); Assert.assertTrue(i.hasNext()); Assert.assertEquals("_555", i.next()); @@ -51,7 +51,7 @@ public class TransformersTest { Assert.assertTrue(i.hasNext()); Assert.assertEquals("_999", i.next()); Assert.assertFalse(i.hasNext()); - + ListIterator li = out.listIterator(); Assert.assertTrue(li.hasNext()); Assert.assertEquals(0, li.nextIndex()); @@ -68,23 +68,23 @@ public class TransformersTest { Assert.assertFalse(li.hasNext()); Assert.assertEquals(3, li.nextIndex()); Assert.assertEquals(2, li.previousIndex()); - - + + } - + @Test public void testNullsInList() { - + List source = new ArrayList(); source.add(555); source.add(null); source.add(999); - + List out = Transformers.transformList(source, x -> "_" + x); - + Assert.assertEquals(3, out.size()); Assert.assertEquals("_null", out.get(1)); - + } - + } diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index 1a74d06..0c219e8 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -2,5 +2,5 @@ log4j.rootLogger=WARN, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n -log4j.logger.casser=WARN -log4j.logger.org.cassandraunit=ERROR \ No newline at end of file +log4j.logger.helenus=WARN +log4j.logger.org.cassandraunit=ERROR