From b0ab810781152c5f41cde4d77c2e4ac4cd3d4fab Mon Sep 17 00:00:00 2001 From: Sai Pullabhotla Date: Sat, 30 Sep 2017 14:16:22 -0500 Subject: [PATCH] Update Maven Build Process to incorporate CheckStyle plugin #84 --- .classpath | 27 + .gitignore | 3 - .project | 23 + .settings/org.eclipse.core.resources.prefs | 4 + .settings/org.eclipse.jdt.core.prefs | 423 ++ .settings/org.eclipse.jdt.ui.prefs | 125 + .settings/org.eclipse.m2e.core.prefs | 4 + checkstyle.java.header | 15 + checkstyle.xml | 218 + pom.xml | 443 +- .../jmethods/catatumbo/BaseQueryRequest.java | 325 +- .../catatumbo/ConnectionParameters.java | 542 +- .../jmethods/catatumbo/CreatedTimestamp.java | 33 +- .../jmethods/catatumbo/DatastoreAccess.java | 683 +- .../jmethods/catatumbo/DatastoreBatch.java | 500 +- .../jmethods/catatumbo/DatastoreCursor.java | 16 +- .../com/jmethods/catatumbo/DatastoreKey.java | 150 +- .../jmethods/catatumbo/DatastoreMetadata.java | 168 +- .../jmethods/catatumbo/DatastoreProperty.java | 278 +- .../jmethods/catatumbo/DatastoreStats.java | 256 +- .../catatumbo/DatastoreTransaction.java | 186 +- .../java/com/jmethods/catatumbo/Decimal.java | 53 +- .../catatumbo/DefaultDatastoreCursor.java | 86 +- .../catatumbo/DefaultDatastoreKey.java | 220 +- .../catatumbo/DefaultQueryResponse.java | 118 +- .../com/jmethods/catatumbo/Embeddable.java | 60 +- .../java/com/jmethods/catatumbo/Embedded.java | 81 +- .../java/com/jmethods/catatumbo/Entity.java | 93 +- .../EntityAlreadyExistsException.java | 91 +- .../jmethods/catatumbo/EntityListener.java | 38 +- .../jmethods/catatumbo/EntityListeners.java | 62 +- .../com/jmethods/catatumbo/EntityManager.java | 209 +- .../catatumbo/EntityManagerException.java | 87 +- .../catatumbo/EntityManagerFactory.java | 518 +- .../EntityManagerFactoryException.java | 82 +- .../catatumbo/EntityNotFoundException.java | 90 +- .../catatumbo/EntityQueryRequest.java | 18 +- .../catatumbo/ExcludeDefaultListeners.java | 18 +- .../catatumbo/ExcludeSuperclassListeners.java | 11 +- .../java/com/jmethods/catatumbo/Exploded.java | 19 +- .../com/jmethods/catatumbo/GeoLocation.java | 172 +- .../com/jmethods/catatumbo/Identifier.java | 53 +- .../java/com/jmethods/catatumbo/Ignore.java | 7 +- .../java/com/jmethods/catatumbo/Imploded.java | 19 +- .../java/com/jmethods/catatumbo/Indexer.java | 23 +- .../jmethods/catatumbo/IndexerFactory.java | 199 +- .../jmethods/catatumbo/IndexingException.java | 81 +- src/main/java/com/jmethods/catatumbo/Key.java | 10 +- .../jmethods/catatumbo/KeyQueryRequest.java | 24 +- .../jmethods/catatumbo/MappedSuperClass.java | 25 +- .../java/com/jmethods/catatumbo/Mapper.java | 40 +- .../com/jmethods/catatumbo/MapperFactory.java | 455 +- .../jmethods/catatumbo/MappingException.java | 81 +- .../catatumbo/NoAccessorMethodException.java | 80 +- .../NoDefaultConstructorException.java | 82 +- .../catatumbo/NoMutatorMethodException.java | 80 +- .../catatumbo/NoSuitableIndexerException.java | 82 +- .../catatumbo/NoSuitableMapperException.java | 81 +- .../catatumbo/OptimisticLockException.java | 85 +- .../com/jmethods/catatumbo/ParentKey.java | 8 +- .../com/jmethods/catatumbo/PostDelete.java | 13 +- .../com/jmethods/catatumbo/PostInsert.java | 13 +- .../java/com/jmethods/catatumbo/PostLoad.java | 13 +- .../com/jmethods/catatumbo/PostUpdate.java | 13 +- .../com/jmethods/catatumbo/PostUpsert.java | 13 +- .../com/jmethods/catatumbo/PreDelete.java | 13 +- .../com/jmethods/catatumbo/PreInsert.java | 13 +- .../com/jmethods/catatumbo/PreUpdate.java | 13 +- .../com/jmethods/catatumbo/PreUpsert.java | 13 +- .../jmethods/catatumbo/ProjectedEntity.java | 28 +- .../catatumbo/ProjectionQueryRequest.java | 23 +- .../java/com/jmethods/catatumbo/Property.java | 80 +- .../jmethods/catatumbo/PropertyIndexer.java | 22 +- .../jmethods/catatumbo/PropertyMapper.java | 30 +- .../jmethods/catatumbo/PropertyOverride.java | 33 +- .../jmethods/catatumbo/PropertyOverrides.java | 22 +- .../com/jmethods/catatumbo/QueryRequest.java | 66 +- .../com/jmethods/catatumbo/QueryResponse.java | 45 +- .../jmethods/catatumbo/SecondaryIndex.java | 65 +- .../java/com/jmethods/catatumbo/Tenant.java | 108 +- .../jmethods/catatumbo/TransactionalTask.java | 21 +- .../com/jmethods/catatumbo/Unmodeled.java | 8 +- ...upportedConstructionStrategyException.java | 27 +- .../jmethods/catatumbo/UpdatedTimestamp.java | 40 +- .../java/com/jmethods/catatumbo/Utility.java | 115 +- .../java/com/jmethods/catatumbo/Version.java | 50 +- .../impl/AbstractListenerMetadata.java | 105 +- .../com/jmethods/catatumbo/impl/Cache.java | 147 +- .../catatumbo/impl/CallbackMetadata.java | 196 +- .../jmethods/catatumbo/impl/CallbackType.java | 136 +- .../impl/ConstructorIntrospector.java | 272 +- .../catatumbo/impl/ConstructorMetadata.java | 517 +- .../catatumbo/impl/DatastoreUtils.java | 403 +- .../catatumbo/impl/DefaultDatastoreBatch.java | 440 +- .../impl/DefaultDatastoreMetadata.java | 233 +- .../impl/DefaultDatastoreReader.java | 838 +-- .../catatumbo/impl/DefaultDatastoreStats.java | 298 +- .../impl/DefaultDatastoreTransaction.java | 627 +- .../impl/DefaultDatastoreWriter.java | 1023 ++- .../catatumbo/impl/DefaultEntityManager.java | 1007 +-- .../impl/EmbeddableIntrospector.java | 177 +- .../catatumbo/impl/EmbeddableMetadata.java | 18 +- .../catatumbo/impl/EmbeddedField.java | 255 +- .../catatumbo/impl/EmbeddedIntrospector.java | 282 +- .../catatumbo/impl/EmbeddedMetadata.java | 317 +- .../catatumbo/impl/EntityIntrospector.java | 883 ++- .../catatumbo/impl/EntityListenerType.java | 33 +- .../impl/EntityListenersIntrospector.java | 374 +- .../impl/EntityListenersMetadata.java | 245 +- .../catatumbo/impl/EntityMetadata.java | 833 +- .../impl/ExternalListenerIntrospector.java | 211 +- .../impl/ExternalListenerMetadata.java | 18 +- .../catatumbo/impl/FieldMetadata.java | 135 +- .../catatumbo/impl/IdClassMetadata.java | 213 +- .../catatumbo/impl/IdentifierMetadata.java | 264 +- .../impl/InternalListenerIntrospector.java | 211 +- .../impl/InternalListenerMetadata.java | 18 +- .../catatumbo/impl/IntrospectionUtils.java | 879 ++- .../jmethods/catatumbo/impl/KeyMetadata.java | 19 +- .../com/jmethods/catatumbo/impl/LRUCache.java | 196 +- .../catatumbo/impl/ListenerFactory.java | 113 +- .../jmethods/catatumbo/impl/Marshaller.java | 1256 ++-- .../jmethods/catatumbo/impl/MetadataBase.java | 254 +- .../catatumbo/impl/ParentKeyMetadata.java | 19 +- .../catatumbo/impl/PropertyMetadata.java | 391 +- .../jmethods/catatumbo/impl/QueryUtils.java | 383 +- .../catatumbo/impl/StorageStrategy.java | 18 +- .../jmethods/catatumbo/impl/Unmarshaller.java | 624 +- .../jmethods/catatumbo/impl/package-info.java | 7 +- .../indexers/LowerCaseStringIndexer.java | 30 +- .../indexers/LowerCaseStringListIndexer.java | 47 +- .../indexers/UpperCaseStringIndexer.java | 30 +- .../indexers/UpperCaseStringListIndexer.java | 48 +- .../catatumbo/indexers/package-info.java | 1 + .../catatumbo/mappers/BigDecimalMapper.java | 31 +- .../catatumbo/mappers/BooleanMapper.java | 32 +- .../catatumbo/mappers/ByteArrayMapper.java | 31 +- .../catatumbo/mappers/CalendarMapper.java | 53 +- .../catatumbo/mappers/CatchAllMapper.java | 170 +- .../catatumbo/mappers/CharArrayMapper.java | 31 +- .../catatumbo/mappers/CharMapper.java | 39 +- .../mappers/CollectionMapperFactory.java | 198 +- .../catatumbo/mappers/DateMapper.java | 51 +- .../catatumbo/mappers/DecimalMapper.java | 205 +- .../catatumbo/mappers/DoubleMapper.java | 32 +- .../mappers/EmbeddedObjectMapper.java | 140 +- .../catatumbo/mappers/EnumMapper.java | 65 +- .../catatumbo/mappers/FloatMapper.java | 42 +- .../catatumbo/mappers/GeoLocationMapper.java | 38 +- .../catatumbo/mappers/IntegerMapper.java | 40 +- .../jmethods/catatumbo/mappers/KeyMapper.java | 35 +- .../catatumbo/mappers/ListMapper.java | 166 +- .../catatumbo/mappers/LocalDateMapper.java | 45 +- .../mappers/LocalDateTimeMapper.java | 63 +- .../catatumbo/mappers/LocalTimeMapper.java | 61 +- .../catatumbo/mappers/LongMapper.java | 32 +- .../jmethods/catatumbo/mappers/MapMapper.java | 203 +- .../mappers/OffsetDateTimeMapper.java | 62 +- .../jmethods/catatumbo/mappers/SetMapper.java | 174 +- .../catatumbo/mappers/ShortMapper.java | 40 +- .../catatumbo/mappers/StringMapper.java | 31 +- .../mappers/ZonedDateTimeMapper.java | 61 +- .../catatumbo/mappers/package-info.java | 4 +- .../com/jmethods/catatumbo/package-info.java | 37 +- .../jmethods/catatumbo/stats/StatBase.java | 215 +- .../catatumbo/stats/StatCompositeIndex.java | 8 +- .../stats/StatCompositeIndexBase.java | 141 +- .../catatumbo/stats/StatCompositeIndexNs.java | 8 +- .../catatumbo/stats/StatConstants.java | 202 +- .../jmethods/catatumbo/stats/StatKind.java | 8 +- .../catatumbo/stats/StatKindBase.java | 358 +- .../jmethods/catatumbo/stats/StatKindNs.java | 8 +- .../catatumbo/stats/StatNamespace.java | 361 +- .../jmethods/catatumbo/stats/StatTotal.java | 11 +- .../catatumbo/stats/StatTotalBase.java | 311 +- .../jmethods/catatumbo/stats/StatTotalNs.java | 8 +- .../java/com/jmethods/catatumbo/AllTests.java | 68 +- .../jmethods/catatumbo/CustomTypeTest.java | 30 +- .../catatumbo/DatastoreBatchTest.java | 752 +- .../catatumbo/DatastoreMetadataTest.java | 252 +- .../catatumbo/DatastoreStatsTest.java | 405 +- .../catatumbo/DatastoreTransactionTest.java | 462 +- .../jmethods/catatumbo/DecimalFieldsTest.java | 698 +- .../DefaultAndExternalListenersTest.java | 430 +- .../catatumbo/DefaultListenerTest.java | 98 +- .../catatumbo/EmbeddedCollectionTest.java | 128 +- .../catatumbo/EntityManagerFactoryTest.java | 567 +- .../jmethods/catatumbo/EntityManagerTest.java | 6693 +++++++++-------- .../catatumbo/ExcludeDefaultListenerTest.java | 398 +- .../catatumbo/ExternalListenerTest.java | 94 +- .../catatumbo/IndexerFactoryTest.java | 26 +- .../catatumbo/InternalListenerTest.java | 332 +- .../catatumbo/ListenerInheritanceTest.java | 92 +- .../jmethods/catatumbo/MapperFactoryTest.java | 430 +- .../catatumbo/OptionalFieldsTest.java | 282 +- .../catatumbo/SecondaryIndexTest.java | 183 +- .../com/jmethods/catatumbo/TenantTest.java | 22 +- .../com/jmethods/catatumbo/TestUtils.java | 160 +- .../catatumbo/TwoDefaultListenersTest.java | 368 +- .../catatumbo/TwoExternalListenersTest.java | 364 +- .../catatumbo/custommappers/ByteMapper.java | 40 +- .../custommappers/CurrencyMapper.java | 80 +- .../custommappers/DeviceTypeMapper.java | 44 +- .../entities/AccessorTestEntity.java | 529 +- .../jmethods/catatumbo/entities/Account.java | 118 +- .../jmethods/catatumbo/entities/Address.java | 326 +- .../catatumbo/entities/AddressMap.java | 114 +- .../jmethods/catatumbo/entities/Animal.java | 72 +- .../catatumbo/entities/AnotherEmbeddable.java | 108 +- .../catatumbo/entities/ArrayIndex.java | 222 +- .../entities/AutoTimestampCalendar.java | 164 +- .../catatumbo/entities/AutoTimestampDate.java | 166 +- .../catatumbo/entities/AutoTimestampLong.java | 166 +- .../entities/AutoTimestampOffsetDateTime.java | 152 +- .../entities/AutoTimestampZonedDateTime.java | 152 +- .../catatumbo/entities/BadBuilderEntity1.java | 44 +- .../catatumbo/entities/BadBuilderEntity2.java | 46 +- .../catatumbo/entities/BadBuilderEntity3.java | 98 +- .../catatumbo/entities/BadBuilderEntity4.java | 68 +- .../catatumbo/entities/BigDecimalField.java | 108 +- .../catatumbo/entities/BooleanField.java | 58 +- .../catatumbo/entities/BooleanObject.java | 58 +- .../catatumbo/entities/ByteArrayField.java | 58 +- .../catatumbo/entities/CalculatorEntity.java | 376 +- .../catatumbo/entities/CalendarField.java | 58 +- .../com/jmethods/catatumbo/entities/Cat.java | 14 +- .../catatumbo/entities/CharArrayField.java | 68 +- .../catatumbo/entities/CharField.java | 58 +- .../catatumbo/entities/CharObject.java | 58 +- .../catatumbo/entities/ChildEntity.java | 160 +- .../jmethods/catatumbo/entities/Color.java | 2 +- .../jmethods/catatumbo/entities/Contact.java | 376 +- .../catatumbo/entities/ContactProjection.java | 76 +- .../jmethods/catatumbo/entities/Country.java | 88 +- .../com/jmethods/catatumbo/entities/Cow.java | 14 +- .../catatumbo/entities/CustomTypeEntity.java | 68 +- .../jmethods/catatumbo/entities/Customer.java | 312 +- .../catatumbo/entities/DateField.java | 58 +- .../catatumbo/entities/DecimalFields.java | 286 +- .../catatumbo/entities/DeleteAll.java | 74 +- .../catatumbo/entities/Department.java | 88 +- .../catatumbo/entities/DeviceType.java | 2 +- .../com/jmethods/catatumbo/entities/Dog.java | 28 +- .../catatumbo/entities/DoubleField.java | 58 +- .../catatumbo/entities/DoubleObject.java | 58 +- .../catatumbo/entities/EmbeddedListIndex.java | 88 +- .../jmethods/catatumbo/entities/Employee.java | 118 +- .../catatumbo/entities/EnumField.java | 64 +- .../entities/ExternalCalculatorEntity.java | 26 +- .../entities/ExternalCalculatorEntity2.java | 26 +- .../entities/ExternalCalculatorEntity3.java | 26 +- .../entities/ExternalCalculatorEntity4.java | 26 +- .../catatumbo/entities/FarmAnimal.java | 14 +- .../catatumbo/entities/FloatField.java | 58 +- .../catatumbo/entities/FloatObject.java | 58 +- .../catatumbo/entities/GenericListField.java | 58 +- .../catatumbo/entities/GenericLongId.java | 42 +- .../catatumbo/entities/GeoLocationField.java | 159 +- .../entities/GlobalCalculatorEntity.java | 26 +- .../catatumbo/entities/GrandchildEntity.java | 162 +- .../catatumbo/entities/IgnoreField.java | 88 +- .../catatumbo/entities/IgnoreField2.java | 86 +- .../catatumbo/entities/ImmutableAddress.java | 277 +- .../catatumbo/entities/ImmutablePerson.java | 417 +- .../catatumbo/entities/ImmutablePhone.java | 191 +- .../catatumbo/entities/ImmutableSubClass.java | 139 +- .../entities/ImmutableSuperClass.java | 138 +- .../catatumbo/entities/ImmutableZipCode.java | 171 +- .../catatumbo/entities/IntegerField.java | 58 +- .../catatumbo/entities/IntegerObject.java | 58 +- .../entities/InternalCalculatorEntity.java | 44 +- .../com/jmethods/catatumbo/entities/Item.java | 165 +- .../catatumbo/entities/KeyListField.java | 58 +- .../com/jmethods/catatumbo/entities/Lion.java | 14 +- .../catatumbo/entities/ListFields.java | 1058 +-- .../catatumbo/entities/LocalDateField.java | 66 +- .../entities/LocalDateTimeField.java | 66 +- .../catatumbo/entities/LocalTimeField.java | 66 +- .../catatumbo/entities/LongField.java | 66 +- .../jmethods/catatumbo/entities/LongId.java | 74 +- .../jmethods/catatumbo/entities/LongId2.java | 58 +- .../catatumbo/entities/LongListField.java | 58 +- .../catatumbo/entities/LongObject.java | 66 +- .../catatumbo/entities/LongObjectId.java | 92 +- .../catatumbo/entities/MapFields.java | 1198 +-- .../catatumbo/entities/NestedMapEntity.java | 163 +- .../entities/NoDefaultConstrctorEntity.java | 72 +- .../entities/NoGetterMethodEntity.java | 56 +- .../entities/NoSetterMethodEntity.java | 54 +- .../entities/NoSetterMethodEntity2.java | 76 +- .../entities/NoSuitableMapperEntity.java | 58 +- .../entities/OffsetDateTimeField.java | 66 +- .../catatumbo/entities/OptimisticLock1.java | 96 +- .../entities/OptimisticLockBad1.java | 88 +- .../entities/OptimisticLockBad2.java | 118 +- .../entities/OptionalCreatedTimestamp.java | 62 +- .../entities/OptionalFieldsEntity.java | 702 +- .../entities/OptionalFieldsEntity2.java | 140 +- .../entities/OptionalFieldsEntity3.java | 94 +- .../catatumbo/entities/OptionalPrimitive.java | 112 +- .../catatumbo/entities/OptionalSubClass.java | 88 +- .../entities/OptionalUpdatedTimestamp.java | 62 +- .../catatumbo/entities/OptionalVersion.java | 62 +- .../catatumbo/entities/ParentEntity.java | 173 +- .../com/jmethods/catatumbo/entities/Pet.java | 14 +- .../catatumbo/entities/PhoneList.java | 134 +- .../catatumbo/entities/PhoneNumber.java | 249 +- .../catatumbo/entities/SetFields.java | 854 +-- .../catatumbo/entities/ShortField.java | 58 +- .../catatumbo/entities/ShortObject.java | 58 +- .../catatumbo/entities/StringField.java | 58 +- .../jmethods/catatumbo/entities/StringId.java | 82 +- .../catatumbo/entities/StringId2.java | 66 +- .../catatumbo/entities/StringIndex.java | 186 +- .../catatumbo/entities/StringIndex2.java | 250 +- .../catatumbo/entities/StringListField.java | 58 +- .../catatumbo/entities/StringListIndex.java | 150 +- .../catatumbo/entities/StringListIndex2.java | 180 +- .../catatumbo/entities/StringSetIndex.java | 150 +- .../catatumbo/entities/StringSetIndex2.java | 180 +- .../catatumbo/entities/SubClass1.java | 88 +- .../catatumbo/entities/SubClass2.java | 64 +- .../catatumbo/entities/SubClass3.java | 99 +- .../catatumbo/entities/SubClass4.java | 92 +- .../catatumbo/entities/SuperClass1.java | 164 +- .../catatumbo/entities/SuperClass2.java | 162 +- .../catatumbo/entities/SuperClass3.java | 112 +- .../catatumbo/entities/SuperClass4.java | 112 +- .../catatumbo/entities/SuperSuperClass.java | 90 +- .../com/jmethods/catatumbo/entities/Tag.java | 88 +- .../com/jmethods/catatumbo/entities/Task.java | 192 +- .../jmethods/catatumbo/entities/TaskName.java | 70 +- .../entities/UnindexedByteArrayField.java | 60 +- .../entities/UnindexedStringField.java | 60 +- .../com/jmethods/catatumbo/entities/User.java | 156 +- .../catatumbo/entities/UserContact.java | 184 +- .../jmethods/catatumbo/entities/UserId.java | 12 +- .../jmethods/catatumbo/entities/Visitor.java | 146 +- .../catatumbo/entities/WildAnimal.java | 14 +- .../catatumbo/entities/WrappedIntegerId.java | 14 +- .../entities/WrappedIntegerIdEntity.java | 58 +- .../catatumbo/entities/WrappedLongId.java | 56 +- .../entities/WrappedLongIdEntity.java | 146 +- .../entities/WrappedLongObjectId.java | 56 +- .../entities/WrappedLongObjectIdEntity.java | 161 +- .../catatumbo/entities/WrappedStringId.java | 56 +- .../entities/WrappedStringIdEntity.java | 161 +- .../jmethods/catatumbo/entities/ZipCode.java | 161 +- .../entities/ZonedDateTimeField.java | 66 +- .../com/jmethods/catatumbo/impl/AllTests.java | 4 +- .../impl/EntityIntrospectorTest.java | 491 +- .../ExternalListenerIntrospectorTest.java | 75 +- .../InternalListenerIntrospectorTest.java | 124 +- .../impl/IntrospectionUtilsTest.java | 362 +- .../jmethods/catatumbo/impl/LRUCacheTest.java | 222 +- .../catatumbo/impl/MarshallerTest.java | 255 +- .../catatumbo/impl/UnmarshallerTest.java | 108 +- .../jmethods/catatumbo/indexers/AllTests.java | 2 +- .../indexers/LowerCaseStringIndexerTest.java | 58 +- .../LowerCaseStringListIndexerTest.java | 111 +- .../indexers/UpperCaseStringIndexerTest.java | 58 +- .../UpperCaseStringListIndexerTest.java | 111 +- .../jmethods/catatumbo/listeners/Adder.java | 74 +- .../catatumbo/listeners/AnimalListener.java | 18 +- .../listeners/BadExternalListener1.java | 8 +- .../listeners/BadExternalListener2.java | 38 +- .../listeners/BadExternalListener3.java | 10 +- .../listeners/BadInternalListener1.java | 6 +- .../listeners/BadInternalListener2.java | 8 +- .../listeners/BadInternalListener3.java | 6 +- .../listeners/BadInternalListener4.java | 6 +- .../listeners/FarmAnimalListener.java | 18 +- .../listeners/GoodExternalListener1.java | 14 +- .../catatumbo/listeners/Multiplier.java | 74 +- .../catatumbo/listeners/Subtractor.java | 74 +- .../jmethods/catatumbo/mappers/AllTests.java | 2 +- .../catatumbo/mappers/DecimalMapperTest.java | 491 +- .../catatumbo/mappers/FloatMapperTest.java | 349 +- .../mappers/OffsetDateTimeMapperTest.java | 95 +- .../mappers/ZonedDateTimeMapperTest.java | 97 +- 380 files changed, 32177 insertions(+), 31447 deletions(-) create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.jdt.ui.prefs create mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 checkstyle.java.header create mode 100644 checkstyle.xml diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..02d550f --- /dev/null +++ b/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore index f8cfffd..e89d4af 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,2 @@ /target/ -/.classpath -/.project -/.settings/ .DS_Store diff --git a/.project b/.project new file mode 100644 index 0000000..e5b639d --- /dev/null +++ b/.project @@ -0,0 +1,23 @@ + + + catatumbo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..f9fe345 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..0514a79 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,423 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=warning +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.8 +org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 +org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=1 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=100 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=2 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=100 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=2 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..685d664 --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,125 @@ +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=false +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=false +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_functional_interfaces=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=false +cleanup.format_source_code=false +cleanup.format_source_code_changes_only=false +cleanup.insert_inferred_type_arguments=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=false +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=false +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=false +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_redundant_type_arguments=false +cleanup.remove_trailing_whitespaces=false +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_anonymous_class_creation=false +cleanup.use_blocks=false +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_lambda=true +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=false +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.use_this_for_non_static_method_access=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=org.eclipse.jdt.ui.default.eclipse_clean_up_profile +cleanup_settings_version=2 +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_Catatumbo +formatter_settings_version=12 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;org;com; +org.eclipse.jdt.ui.javadoc=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.staticondemandthreshold=99 +org.eclipse.jdt.ui.text.custom_code_templates= +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_methods=false +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_missing_override_annotations_interface_methods=true +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=false +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_functional_interfaces=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.correct_indentation=false +sp_cleanup.format_source_code=true +sp_cleanup.format_source_code_changes_only=false +sp_cleanup.insert_inferred_type_arguments=false +sp_cleanup.make_local_variable_final=true +sp_cleanup.make_parameters_final=false +sp_cleanup.make_private_fields_final=true +sp_cleanup.make_type_abstract_if_missing_method=false +sp_cleanup.make_variable_declarations_final=false +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=true +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_redundant_type_arguments=false +sp_cleanup.remove_trailing_whitespaces=false +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=false +sp_cleanup.remove_unused_imports=false +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=false +sp_cleanup.sort_members_all=false +sp_cleanup.use_anonymous_class_creation=false +sp_cleanup.use_blocks=false +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_lambda=true +sp_cleanup.use_parentheses_in_expressions=false +sp_cleanup.use_this_for_non_static_field_access=false +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true +sp_cleanup.use_this_for_non_static_method_access=false +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/checkstyle.java.header b/checkstyle.java.header new file mode 100644 index 0000000..4b421f1 --- /dev/null +++ b/checkstyle.java.header @@ -0,0 +1,15 @@ +^/\*$ +^ \* Copyright \d\d\d\d Sai Pullabhotla\.$ +^ \*$ +^ \* 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\.$ +^ \*/$ \ No newline at end of file diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 0000000..b01eeb1 --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,218 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 0dab855..596bd96 100644 --- a/pom.xml +++ b/pom.xml @@ -1,197 +1,250 @@ - - 4.0.0 - - com.jmethods - catatumbo - 2.3.1-SNAPSHOT - jar - Catatumbo - + + 4.0.0 + com.jmethods + catatumbo + 2.3.1-SNAPSHOT + jar + Catatumbo + Object Mapping and Persistence Framework for Google Cloud Datastore - http://www.jMethods.com - 2016 - - - UTF-8 - 1.8 - 1.8 - - - - - Apache License Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - - - - - - Sai Pullabhotla - Sai.Pullabhotla@jMethods.com - - - - - scm:git:https://github.com/sai-pullabhotla/catatumbo.git - scm:git:https://github.com/sai-pullabhotla/catatumbo.git - scm:git:https://github.com/sai-pullabhotla/catatumbo.git - HEAD - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - junit - junit - 4.12 - test - - - com.google.cloud - google-cloud-datastore - 1.5.1 - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.20 - - - **/AllTests.class - - - - - org.eluder.coveralls - coveralls-maven-plugin - 4.3.0 - - - org.jacoco - jacoco-maven-plugin - 0.7.9 - - - prepare-agent - - prepare-agent - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - true - true - - true - true - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - false - - - - org.apache.maven.plugins - maven-release-plugin - 2.5 - - true - false - release - deploy - - - - scm - - - - - - - - - release - - - - org.apache.maven.plugins - maven-source-plugin - 3.0.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - - - - - + http://www.jMethods.com + 2016 + + UTF-8 + 1.8 + 1.8 + + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + Sai Pullabhotla + Sai.Pullabhotla@jMethods.com + + + + scm:git:https://github.com/sai-pullabhotla/catatumbo.git + scm:git:https://github.com/sai-pullabhotla/catatumbo.git + scm:git:https://github.com/sai-pullabhotla/catatumbo.git + HEAD + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + junit + junit + 4.12 + test + + + com.google.cloud + google-cloud-datastore + 1.5.1 + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + + maven-checkstyle-plugin + + [2.17,) + + + check + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + com.puppycrawl.tools + checkstyle + 8.2 + + + + checkstyle.xml + checkstyle.java.header + UTF-8 + true + false + false + + + + validate + validate + + check + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.20 + + + **/AllTests.class + + + + + org.eluder.coveralls + coveralls-maven-plugin + 4.3.0 + + + org.jacoco + jacoco-maven-plugin + 0.7.9 + + + prepare-agent + + prepare-agent + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + true + true + + true + true + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + false + + + + org.apache.maven.plugins + maven-release-plugin + 2.5 + + true + false + release + deploy + + + + scm + + + + + + + + release + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/jmethods/catatumbo/BaseQueryRequest.java b/src/main/java/com/jmethods/catatumbo/BaseQueryRequest.java index b8bafa5..5d6211d 100644 --- a/src/main/java/com/jmethods/catatumbo/BaseQueryRequest.java +++ b/src/main/java/com/jmethods/catatumbo/BaseQueryRequest.java @@ -30,170 +30,165 @@ */ public abstract class BaseQueryRequest implements QueryRequest { - /** - * GQL Query - */ - protected String query = null; - - /** - * Named bindings - */ - protected Map namedBindings = null; - - /** - * Positional bindings - */ - protected List positionalBindings = null; - - /** - * Whether or not to allow literals in the query - */ - protected boolean allowLiterals = false; - - /** - * Creates a new instance of BaseQueryRequest. - * - * @param query - * the GQL query string - */ - public BaseQueryRequest(String query) { - this.query = query; - this.allowLiterals = false; - // Initialize the named and positional bindings. - namedBindings = new HashMap<>(); - positionalBindings = new ArrayList<>(); - } - - @Override - public String getQuery() { - return query; - } - - /** - * Sets the GQL query to the given value. - * - * @param query - * the GQL query - */ - public void setQuery(String query) { - this.query = query; - } - - @Override - public Map getNamedBindings() { - return namedBindings; - } - - /** - * Sets the named bindings that are needed for any named parameters in the - * GQL query. - * - * @param namedBindings - * the named bindings. - * @throws NullPointerException - * if the namedBindings argument is - * null. - */ - public void setNamedBindings(Map namedBindings) { - if (namedBindings == null) { - throw new NullPointerException(); - } - this.namedBindings = namedBindings; - } - - @Override - public List getPositionalBindings() { - return positionalBindings; - } - - /** - * Sets the positional bindings that are needed for any positional - * parameters in the GQL Query. - * - * @param positionalBindings - * the positional bindings. - * @throws NullPointerException - * if the positionalArguments is null. - */ - public void setPositionalBindings(List positionalBindings) { - if (positionalBindings == null) { - throw new NullPointerException(); - } - this.positionalBindings = positionalBindings; - } - - /** - * Adds or replaces the given named binding to the list of named bindings. - * - * @param bindingName - * the binding name - * @param bindingValue - * the binding value - */ - public void setNamedBinding(String bindingName, Object bindingValue) { - namedBindings.put(bindingName, bindingValue); - } - - /** - * Adds the given value to the list of positional bindings. - * - * @param bindingValue - * the binding value - */ - public void addPositionalBinding(Object bindingValue) { - positionalBindings.add(bindingValue); - } - - /** - * Adds the positional bindings that are needed for any positional - * parameters in the GQL query. - * - * @param first - * the first positional binding - * @param others - * subsequent positional bindings, if any - */ - public void addPositionalBindings(Object first, Object... others) { - positionalBindings.add(first); - positionalBindings.addAll(Arrays.asList(others)); - } - - /** - * Clears the positional bindings, if any. - */ - public void clearPositionalBindings() { - positionalBindings.clear(); - } - - /** - * Clears the named bindings, if any. - */ - public void clearNamedBindings() { - namedBindings.clear(); - } - - /** - * Clears all bindings (positional and named), if any. - */ - public void clearBindings() { - clearPositionalBindings(); - clearNamedBindings(); - } - - @Override - public boolean isAllowLiterals() { - return allowLiterals; - } - - /** - * Allows or disallows presence of any literals (constants or synthetic - * literals) in the query. - * - * @param allowLiterals - * whether or not to allow literals in the query. - */ - public void setAllowLiterals(boolean allowLiterals) { - this.allowLiterals = allowLiterals; - } + /** + * GQL Query + */ + protected String query = null; + + /** + * Named bindings + */ + protected Map namedBindings = null; + + /** + * Positional bindings + */ + protected List positionalBindings = null; + + /** + * Whether or not to allow literals in the query + */ + protected boolean allowLiterals = false; + + /** + * Creates a new instance of BaseQueryRequest. + * + * @param query + * the GQL query string + */ + public BaseQueryRequest(String query) { + this.query = query; + this.allowLiterals = false; + // Initialize the named and positional bindings. + namedBindings = new HashMap<>(); + positionalBindings = new ArrayList<>(); + } + + @Override + public String getQuery() { + return query; + } + + /** + * Sets the GQL query to the given value. + * + * @param query + * the GQL query + */ + public void setQuery(String query) { + this.query = query; + } + + @Override + public Map getNamedBindings() { + return namedBindings; + } + + /** + * Sets the named bindings that are needed for any named parameters in the GQL query. + * + * @param namedBindings + * the named bindings. + * @throws NullPointerException + * if the namedBindings argument is null. + */ + public void setNamedBindings(Map namedBindings) { + if (namedBindings == null) { + throw new NullPointerException(); + } + this.namedBindings = namedBindings; + } + + @Override + public List getPositionalBindings() { + return positionalBindings; + } + + /** + * Sets the positional bindings that are needed for any positional parameters in the GQL Query. + * + * @param positionalBindings + * the positional bindings. + * @throws NullPointerException + * if the positionalArguments is null. + */ + public void setPositionalBindings(List positionalBindings) { + if (positionalBindings == null) { + throw new NullPointerException(); + } + this.positionalBindings = positionalBindings; + } + + /** + * Adds or replaces the given named binding to the list of named bindings. + * + * @param bindingName + * the binding name + * @param bindingValue + * the binding value + */ + public void setNamedBinding(String bindingName, Object bindingValue) { + namedBindings.put(bindingName, bindingValue); + } + + /** + * Adds the given value to the list of positional bindings. + * + * @param bindingValue + * the binding value + */ + public void addPositionalBinding(Object bindingValue) { + positionalBindings.add(bindingValue); + } + + /** + * Adds the positional bindings that are needed for any positional parameters in the GQL query. + * + * @param first + * the first positional binding + * @param others + * subsequent positional bindings, if any + */ + public void addPositionalBindings(Object first, Object... others) { + positionalBindings.add(first); + positionalBindings.addAll(Arrays.asList(others)); + } + + /** + * Clears the positional bindings, if any. + */ + public void clearPositionalBindings() { + positionalBindings.clear(); + } + + /** + * Clears the named bindings, if any. + */ + public void clearNamedBindings() { + namedBindings.clear(); + } + + /** + * Clears all bindings (positional and named), if any. + */ + public void clearBindings() { + clearPositionalBindings(); + clearNamedBindings(); + } + + @Override + public boolean isAllowLiterals() { + return allowLiterals; + } + + /** + * Allows or disallows presence of any literals (constants or synthetic literals) in the query. + * + * @param allowLiterals + * whether or not to allow literals in the query. + */ + public void setAllowLiterals(boolean allowLiterals) { + this.allowLiterals = allowLiterals; + } } diff --git a/src/main/java/com/jmethods/catatumbo/ConnectionParameters.java b/src/main/java/com/jmethods/catatumbo/ConnectionParameters.java index a8b9f13..4467264 100644 --- a/src/main/java/com/jmethods/catatumbo/ConnectionParameters.java +++ b/src/main/java/com/jmethods/catatumbo/ConnectionParameters.java @@ -23,24 +23,22 @@ import com.google.datastore.v1.client.DatastoreFactory; /** - * Objects of this class contain various parameters that are needed for - * connecting to the Datastore. Instances of this class can be sent to - * {@link EntityManagerFactory} to create an {@link EntityManager}. + * Objects of this class contain various parameters that are needed for connecting to the Datastore. + * Instances of this class can be sent to {@link EntityManagerFactory} to create an + * {@link EntityManager}. * *

* Note:
- * Credentials can be specified using one of the - * setJsonCredentials* methods. If credentials are set using both - * an InputStream and File or Path, the - * stream will be used for authentication. + * Credentials can be specified using one of the setJsonCredentials* methods. If + * credentials are set using both an InputStream and File or + * Path, the stream will be used for authentication. *

* *

* Connecting to the Datastore Emulator:
- * Call the {@link ConnectionParameters#setServiceURL(String)} method to connect - * to the Datastore Emulator. For example, to connect to the Datastore Emulator - * running on port 9999 on localhost, call - * setServiceURL("http://localhost:9999");. + * Call the {@link ConnectionParameters#setServiceURL(String)} method to connect to the Datastore + * Emulator. For example, to connect to the Datastore Emulator running on port 9999 on + * localhost, call setServiceURL("http://localhost:9999");. *

* * @author Sai Pullabhotla @@ -48,267 +46,265 @@ */ public class ConnectionParameters { - /** - * Default Service URL for connecting to Datastore on GCP. - */ - public static final String DEFAULT_SERVICE_URL = DatastoreFactory.DEFAULT_HOST; - - /** - * Default connection timeout - */ - public static final int DEFAULT_CONNECTION_TIMEOUT = 20000; - - /** - * Default read timeout - */ - public static final int DEFAULT_READ_TIMEOUT = 20000; - - /** - * Service URL - */ - private String serviceURL; - - /** - * Datastore namespace - */ - private String namespace; - - /** - * Project ID - */ - private String projectId; - - /** - * JSON credentials file - */ - private File jsonCredentialsFile; - - /** - * JSON credentials for authentication - */ - private InputStream jsonCredentialsStream; - - /** - * Connection timeout - */ - private int connectionTimeout; - - /** - * Read timeout - */ - private int readTimeout; - - /** - * HTTP Transport Factory - */ - private HttpTransportFactory httpTransportFactory; - - /** - * Creates a new instance of ConnectionParameters. - */ - public ConnectionParameters() { - this.serviceURL = DEFAULT_SERVICE_URL; - this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; - this.readTimeout = DEFAULT_READ_TIMEOUT; - } - - /** - * Returns the service URL. - * - * @return the service URL. - */ - public String getServiceURL() { - return serviceURL; - } - - /** - * Sets the service URL. The service URL is typically of the form - - * http[s]://host[:port]. A null or empty string - * would result in connecting to the default Datastore on GCP. All other - * values, except {@link ConnectionParameters#DEFAULT_SERVICE_URL}, would be - * interpreted as a connection to the Datastore Emulator. - * - * @param serviceURL - * the serviceURL to set. - */ - public void setServiceURL(String serviceURL) { - if (Utility.isNullOrEmpty(serviceURL)) { - this.serviceURL = DEFAULT_SERVICE_URL; - } else { - this.serviceURL = serviceURL; - } - } - - /** - * Returns the Datastore namespace. - * - * @return the Datastore namespace. - */ - public String getNamespace() { - return namespace; - } - - /** - * Sets the Datastore namespace.A null value would be - * interpreted as default namespace. - * - * @param namespace - * the Datastore namespace. - */ - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - /** - * Returns the Project ID. - * - * @return the Project ID. - */ - public String getProjectId() { - return projectId; - } - - /** - * Sets the Project ID.A null value would use the default - * project ID, if it can be determined from the environment. - * - * @param projectId - * the Project ID. - */ - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - /** - * Returns the JSON credentials file. - * - * @return the JSON credentials file. - */ - public File getJsonCredentialsFile() { - return jsonCredentialsFile; - } - - /** - * Sets the JSON credentials file. - * - * @param jsonCredentialsFile - * the JSON credentials file. - */ - public void setJsonCredentialsFile(File jsonCredentialsFile) { - this.jsonCredentialsFile = jsonCredentialsFile; - } - - /** - * Sets the JSON credentials path. - * - * @param jsonCredentialsPath - * the JSON credentials path. - */ - public void setJsonCredentialsFile(String jsonCredentialsPath) { - if (!Utility.isNullOrEmpty(jsonCredentialsPath)) { - setJsonCredentialsFile(new File(jsonCredentialsPath)); - } else { - setJsonCredentialsFile((File) null); - } - } - - /** - * Returns an InputStream that contains the JSON credentials. - * - * @return an InputStream that contains the JSON credentials. - */ - public InputStream getJsonCredentialsStream() { - return jsonCredentialsStream; - } - - /** - * Sets the JSON credentials. - * - * @param jsonCredentialsStream - * An {@link InputStream} containing the JSON credentials. - */ - public void setJsonCredentialsStream(InputStream jsonCredentialsStream) { - this.jsonCredentialsStream = jsonCredentialsStream; - } - - /** - * Returns the connection timeout, in milliseconds. - * - * @return the connection timeout, in milliseconds. - */ - public int getConnectionTimeout() { - return connectionTimeout; - } - - /** - * Sets the connection timeout, in milliseconds. A value of zero is - * interpreted as infinite timeout. A negative value implies to use the - * default timeout. - * - * @param connectionTimeout - * the connection timeout, in milliseconds. - */ - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout < 0 ? DEFAULT_CONNECTION_TIMEOUT : connectionTimeout; - } - - /** - * Returns the read timeout, in milliseconds. - * - * @return the read timeout, in milliseconds. - */ - public int getReadTimeout() { - return readTimeout; - } - - /** - * Sets the read timeout, in milliseconds. A value of zero is interpreted as - * infinite timeout. A negative value implies to use the default timeout. - * - * @param readTimeout - * the read timeout, in milliseconds. - */ - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout < 0 ? DEFAULT_READ_TIMEOUT : readTimeout; - } - - /** - * Returns the HttpTransportFactory. - * - * @return the HttpTransportFactory. - */ - public HttpTransportFactory getHttpTransportFactory() { - return httpTransportFactory; - } - - /** - * Sets the HttpTransportFactory. - * - * @param httpTransportFactory - * the HttpTransportFactory - */ - public void setHttpTransportFactory(HttpTransportFactory httpTransportFactory) { - this.httpTransportFactory = httpTransportFactory; - } - - /** - * Tells whether or not these connection parameters indicate a connection to - * a Datastore Emulator. - * - * @return true, if these connection parameters indicate a - * connection to the Datastore Emulator; false, - * otherwise. - */ - public boolean isEmulator() { - return !DEFAULT_SERVICE_URL.equals(serviceURL); - } - - @Override - public String toString() { - return "ConnectionParameters [serviceURL=" + serviceURL + ", namespace=" + namespace + ", projectId=" - + projectId + ", jsonCredentialsFile=" + jsonCredentialsFile + ", jsonCredentialsStream=" - + jsonCredentialsStream + ", connectionTimeout=" + connectionTimeout + ", readTimeout=" + readTimeout - + ", httpTransportFactory=" + httpTransportFactory + ", emulator=" + isEmulator() + "]"; - } + /** + * Default Service URL for connecting to Datastore on GCP. + */ + public static final String DEFAULT_SERVICE_URL = DatastoreFactory.DEFAULT_HOST; + + /** + * Default connection timeout + */ + public static final int DEFAULT_CONNECTION_TIMEOUT = 20000; + + /** + * Default read timeout + */ + public static final int DEFAULT_READ_TIMEOUT = 20000; + + /** + * Service URL + */ + private String serviceURL; + + /** + * Datastore namespace + */ + private String namespace; + + /** + * Project ID + */ + private String projectId; + + /** + * JSON credentials file + */ + private File jsonCredentialsFile; + + /** + * JSON credentials for authentication + */ + private InputStream jsonCredentialsStream; + + /** + * Connection timeout + */ + private int connectionTimeout; + + /** + * Read timeout + */ + private int readTimeout; + + /** + * HTTP Transport Factory + */ + private HttpTransportFactory httpTransportFactory; + + /** + * Creates a new instance of ConnectionParameters. + */ + public ConnectionParameters() { + this.serviceURL = DEFAULT_SERVICE_URL; + this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; + this.readTimeout = DEFAULT_READ_TIMEOUT; + } + + /** + * Returns the service URL. + * + * @return the service URL. + */ + public String getServiceURL() { + return serviceURL; + } + + /** + * Sets the service URL. The service URL is typically of the form - + * http[s]://host[:port]. A null or empty string would result in + * connecting to the default Datastore on GCP. All other values, except + * {@link ConnectionParameters#DEFAULT_SERVICE_URL}, would be interpreted as a connection to the + * Datastore Emulator. + * + * @param serviceURL + * the serviceURL to set. + */ + public void setServiceURL(String serviceURL) { + if (Utility.isNullOrEmpty(serviceURL)) { + this.serviceURL = DEFAULT_SERVICE_URL; + } else { + this.serviceURL = serviceURL; + } + } + + /** + * Returns the Datastore namespace. + * + * @return the Datastore namespace. + */ + public String getNamespace() { + return namespace; + } + + /** + * Sets the Datastore namespace.A null value would be interpreted as default + * namespace. + * + * @param namespace + * the Datastore namespace. + */ + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + /** + * Returns the Project ID. + * + * @return the Project ID. + */ + public String getProjectId() { + return projectId; + } + + /** + * Sets the Project ID.A null value would use the default project ID, if it can be + * determined from the environment. + * + * @param projectId + * the Project ID. + */ + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + /** + * Returns the JSON credentials file. + * + * @return the JSON credentials file. + */ + public File getJsonCredentialsFile() { + return jsonCredentialsFile; + } + + /** + * Sets the JSON credentials file. + * + * @param jsonCredentialsFile + * the JSON credentials file. + */ + public void setJsonCredentialsFile(File jsonCredentialsFile) { + this.jsonCredentialsFile = jsonCredentialsFile; + } + + /** + * Sets the JSON credentials path. + * + * @param jsonCredentialsPath + * the JSON credentials path. + */ + public void setJsonCredentialsFile(String jsonCredentialsPath) { + if (!Utility.isNullOrEmpty(jsonCredentialsPath)) { + setJsonCredentialsFile(new File(jsonCredentialsPath)); + } else { + setJsonCredentialsFile((File) null); + } + } + + /** + * Returns an InputStream that contains the JSON credentials. + * + * @return an InputStream that contains the JSON credentials. + */ + public InputStream getJsonCredentialsStream() { + return jsonCredentialsStream; + } + + /** + * Sets the JSON credentials. + * + * @param jsonCredentialsStream + * An {@link InputStream} containing the JSON credentials. + */ + public void setJsonCredentialsStream(InputStream jsonCredentialsStream) { + this.jsonCredentialsStream = jsonCredentialsStream; + } + + /** + * Returns the connection timeout, in milliseconds. + * + * @return the connection timeout, in milliseconds. + */ + public int getConnectionTimeout() { + return connectionTimeout; + } + + /** + * Sets the connection timeout, in milliseconds. A value of zero is interpreted as infinite + * timeout. A negative value implies to use the default timeout. + * + * @param connectionTimeout + * the connection timeout, in milliseconds. + */ + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout < 0 ? DEFAULT_CONNECTION_TIMEOUT : connectionTimeout; + } + + /** + * Returns the read timeout, in milliseconds. + * + * @return the read timeout, in milliseconds. + */ + public int getReadTimeout() { + return readTimeout; + } + + /** + * Sets the read timeout, in milliseconds. A value of zero is interpreted as infinite timeout. A + * negative value implies to use the default timeout. + * + * @param readTimeout + * the read timeout, in milliseconds. + */ + public void setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout < 0 ? DEFAULT_READ_TIMEOUT : readTimeout; + } + + /** + * Returns the HttpTransportFactory. + * + * @return the HttpTransportFactory. + */ + public HttpTransportFactory getHttpTransportFactory() { + return httpTransportFactory; + } + + /** + * Sets the HttpTransportFactory. + * + * @param httpTransportFactory + * the HttpTransportFactory + */ + public void setHttpTransportFactory(HttpTransportFactory httpTransportFactory) { + this.httpTransportFactory = httpTransportFactory; + } + + /** + * Tells whether or not these connection parameters indicate a connection to a Datastore Emulator. + * + * @return true, if these connection parameters indicate a connection to the + * Datastore Emulator; false, otherwise. + */ + public boolean isEmulator() { + return !DEFAULT_SERVICE_URL.equals(serviceURL); + } + + @Override + public String toString() { + return "ConnectionParameters [serviceURL=" + serviceURL + ", namespace=" + namespace + + ", projectId=" + projectId + ", jsonCredentialsFile=" + jsonCredentialsFile + + ", jsonCredentialsStream=" + jsonCredentialsStream + ", connectionTimeout=" + + connectionTimeout + ", readTimeout=" + readTimeout + ", httpTransportFactory=" + + httpTransportFactory + ", emulator=" + isEmulator() + "]"; + } } diff --git a/src/main/java/com/jmethods/catatumbo/CreatedTimestamp.java b/src/main/java/com/jmethods/catatumbo/CreatedTimestamp.java index 3a59aac..7479678 100644 --- a/src/main/java/com/jmethods/catatumbo/CreatedTimestamp.java +++ b/src/main/java/com/jmethods/catatumbo/CreatedTimestamp.java @@ -27,10 +27,9 @@ import java.util.Date; /** - * Annotation for automatically setting the entity's creation timestamp. This - * annotation can be applied to a field of an {@link Entity} or - * {@link MappedSuperClass}. Only one field can have this annotation in a given - * Entity hierarchy. + * Annotation for automatically setting the entity's creation timestamp. This annotation can be + * applied to a field of an {@link Entity} or {@link MappedSuperClass}. Only one field can have this + * annotation in a given Entity hierarchy. * *

* Valid data types for the field include - @@ -45,25 +44,23 @@ * * *

- * When inserting entities (any variation of insert methods) that have a field - * with this annotation, the framework sets the corresponding Datastore property - * to the current timestamp as returned by the host JVM. Any value set in the - * entity will be ignored/overwritten. + * When inserting entities (any variation of insert methods) that have a field with this annotation, + * the framework sets the corresponding Datastore property to the current timestamp as returned by + * the host JVM. Any value set in the entity will be ignored/overwritten. *

* *

- * Update and Upsert operations ignore this annotation, meaning the field does - * not get any special treatment during UPSERT or UPDATE operations. However, - * any value set in the entity (may be null) will be persisted to the Datastore. + * Update and Upsert operations ignore this annotation, meaning the field does not get any special + * treatment during UPSERT or UPDATE operations. However, any value set in the entity (may be null) + * will be persisted to the Datastore. *

* *

- * The field with this annotation is no different than any other property of the - * entity. This means, this field could also have the {@link Property} - * annotation and specify the property name to use in the Datastore as well as - * whether or not the property should be indexed. The field will be mapped using - * the specified {@link Mapper}, if a {@link PropertyMapper} is specified, - * otherwise a default mapper for the data type is used. + * The field with this annotation is no different than any other property of the entity. This means, + * this field could also have the {@link Property} annotation and specify the property name to use + * in the Datastore as well as whether or not the property should be indexed. The field will be + * mapped using the specified {@link Mapper}, if a {@link PropertyMapper} is specified, otherwise a + * default mapper for the data type is used. *

* * @author Sai Pullabhotla @@ -72,5 +69,5 @@ @Retention(RUNTIME) @Target(FIELD) public @interface CreatedTimestamp { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreAccess.java b/src/main/java/com/jmethods/catatumbo/DatastoreAccess.java index 3c28f9a..7532bbe 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreAccess.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreAccess.java @@ -19,386 +19,371 @@ import java.util.List; /** - * An interface for working with (reading from and writing to) the Cloud - * Datastore. + * An interface for working with (reading from and writing to) the Cloud Datastore. * * @author Sai Pullabhotla * */ public interface DatastoreAccess { - /** - * Inserts the given entity into the Cloud Datastore. - * - * @param entity - * the entity to insert - * @return the inserted entity. The inserted entity will not be same as the - * passed in entity. For example, the inserted entity may contain - * any generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E insert(E entity); + /** + * Inserts the given entity into the Cloud Datastore. + * + * @param entity + * the entity to insert + * @return the inserted entity. The inserted entity will not be same as the passed in entity. For + * example, the inserted entity may contain any generated ID, key, parent key, etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E insert(E entity); - /** - * Inserts the given list of entities into the Cloud Datastore. - * - * @param entities - * the entities to insert. - * @return the inserted entities. The inserted entities will not be same as - * the passed in entities. For example, the inserted entities may - * contain generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List insert(List entities); + /** + * Inserts the given list of entities into the Cloud Datastore. + * + * @param entities + * the entities to insert. + * @return the inserted entities. The inserted entities will not be same as the passed in + * entities. For example, the inserted entities may contain generated ID, key, parent key, + * etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List insert(List entities); - /** - * Updates the given entity in the Cloud Datastore. The passed in Entity - * must have its ID set for the update to work. - * - * @param entity - * the entity to update - * @return the updated entity. - * @throws EntityManagerException - * if any error occurs while updating. - */ - E update(E entity); + /** + * Updates the given entity in the Cloud Datastore. The passed in Entity must have its ID set for + * the update to work. + * + * @param entity + * the entity to update + * @return the updated entity. + * @throws EntityManagerException + * if any error occurs while updating. + */ + E update(E entity); - /** - * Updates the given list of entities in the Cloud Datastore. - * - * @param entities - * the entities to update. The passed in entities must have their - * ID set for the update to work. - * @return the updated entities - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List update(List entities); + /** + * Updates the given list of entities in the Cloud Datastore. + * + * @param entities + * the entities to update. The passed in entities must have their ID set for the update + * to work. + * @return the updated entities + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List update(List entities); - /** - * Updates or inserts the given entity in the Cloud Datastore. If the entity - * does not have an ID, it may be generated. - * - * @param entity - * the entity to update or insert - * @return the updated/inserted entity. - * @throws EntityManagerException - * if any error occurs while saving. - */ - E upsert(E entity); + /** + * Updates or inserts the given entity in the Cloud Datastore. If the entity does not have an ID, + * it may be generated. + * + * @param entity + * the entity to update or insert + * @return the updated/inserted entity. + * @throws EntityManagerException + * if any error occurs while saving. + */ + E upsert(E entity); - /** - * Updates or inserts the given list of entities in the Cloud Datastore. If - * the entities do not have a valid ID, IDs may be generated. - * - * @param entities - * the entities to update/or insert. - * @return the updated or inserted entities - * @throws EntityManagerException - * if any error occurs while saving. - */ - List upsert(List entities); + /** + * Updates or inserts the given list of entities in the Cloud Datastore. If the entities do not + * have a valid ID, IDs may be generated. + * + * @param entities + * the entities to update/or insert. + * @return the updated or inserted entities + * @throws EntityManagerException + * if any error occurs while saving. + */ + List upsert(List entities); - /** - * Deletes the given entity from the Cloud Datastore. - * - * @param entity - * the entity to delete. The entity must have it ID set for the - * deletion to succeed. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void delete(Object entity); + /** + * Deletes the given entity from the Cloud Datastore. + * + * @param entity + * the entity to delete. The entity must have it ID set for the deletion to succeed. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void delete(Object entity); - /** - * Deletes the given entities from the Cloud Datastore. - * - * @param entities - * the entities to delete. The entities must have it ID set for - * the deletion to succeed. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void delete(List entities); + /** + * Deletes the given entities from the Cloud Datastore. + * + * @param entities + * the entities to delete. The entities must have it ID set for the deletion to succeed. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void delete(List entities); - /** - * Deletes an entity given its key. - * - * @param key - * the entity's key - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void deleteByKey(DatastoreKey key); + /** + * Deletes the entity with the given ID. The entity is assumed to be a root entity (no parent). + * The entity kind will be determined from the supplied entity class. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, long id); - /** - * Deletes the entities having the given keys. - * - * @param keys - * the entities' keys - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void deleteByKey(List keys); + /** + * Deletes the entity with the given ID. The entity is assumed to be a root entity (no parent). + * The entity kind will be determined from the supplied entity class. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, String id); - /** - * Deletes the entity with the given ID. The entity is assumed to be a root - * entity (no parent). The entity kind will be determined from the supplied - * entity class. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, long id); + /** + * Deletes the entity with the given ID and parent key. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, DatastoreKey parentKey, long id); - /** - * Deletes the entity with the given ID. The entity is assumed to be a root - * entity (no parent). The entity kind will be determined from the supplied - * entity class. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, String id); + /** + * Deletes the entity with the given ID and parent key. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, DatastoreKey parentKey, String id); - /** - * Deletes the entity with the given ID and parent key. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, DatastoreKey parentKey, long id); + /** + * Deletes an entity given its key. + * + * @param key + * the entity's key + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void deleteByKey(DatastoreKey key); - /** - * Deletes the entity with the given ID and parent key. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, DatastoreKey parentKey, String id); + /** + * Deletes the entities having the given keys. + * + * @param keys + * the entities' keys + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void deleteByKey(List keys); - /** - * Loads and returns the entity with the given ID. The entity is assumed to - * be a root entity (no parent). The entity kind is determined from the - * supplied class. - * - * @param entityClass - * the entity class - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E load(Class entityClass, long id); + /** + * Loads and returns the entity with the given ID. The entity is assumed to be a root entity (no + * parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E load(Class entityClass, long id); - /** - * Loads and returns the entities with the given numeric IDs. The - * entities are assumed to be a root entities (no parent). The entity kind - * is determined from the supplied class. - * - * @param entityClass - * the entity class - * @param identifiers - * the IDs of the entities - * @return the list of entity objects in the same order as the given list of - * identifiers. If one or more requested IDs do not exist in the - * Cloud Datastore, the corresponding item in the returned list be - * null. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List loadById(Class entityClass, List identifiers); + /** + * Loads and returns the entity with the given ID. The entity is assumed to be a root entity (no + * parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E load(Class entityClass, String id); - /** - * Loads and returns the entity with the given ID. The entity is assumed to - * be a root entity (no parent). The entity kind is determined from the - * supplied class. - * - * @param entityClass - * the entity class - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E load(Class entityClass, String id); + /** + * Loads and returns the entity with the given ID. The entity kind is determined from the supplied + * class. + * + * @param entityClass + * the entity class + * @param parentKey + * the parent key of the entity. + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E load(Class entityClass, DatastoreKey parentKey, long id); - /** - * Loads and returns the entities with the given names (a.k.a String - * IDs). The entities are assumed to be root entities (no parent). The - * entity kind is determined from the supplied class. - * - * @param entityClass - * the entity class - * @param identifiers - * the IDs of the entities - * @return the list of entity objects in the same order as the given list of - * identifiers. If one or more requested IDs do not exist in the - * Cloud Datastore, the corresponding item in the returned list be - * null. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List loadByName(Class entityClass, List identifiers); + /** + * Loads and returns the entity with the given ID. The entity kind is determined from the supplied + * class. + * + * @param entityClass + * the entity class + * @param parentKey + * the parent key of the entity. + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E load(Class entityClass, DatastoreKey parentKey, String id); - /** - * Loads and returns the entity with the given ID. The entity kind is - * determined from the supplied class. - * - * @param entityClass - * the entity class - * @param parentKey - * the parent key of the entity. - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E load(Class entityClass, DatastoreKey parentKey, long id); + /** + * Loads and returns the entity with the given key. + * + * @param entityClass + * the entity class (expected result type) + * @param key + * full key of the entity + * @return the Entity object or null, if the the entity with the given key does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while accessing the Cloud Datastore. + */ + E load(Class entityClass, DatastoreKey key); - /** - * Loads and returns the entity with the given ID. The entity kind is - * determined from the supplied class. - * - * @param entityClass - * the entity class - * @param parentKey - * the parent key of the entity. - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E load(Class entityClass, DatastoreKey parentKey, String id); + /** + * Loads and returns the entities with the given numeric IDs. The entities are assumed to + * be a root entities (no parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param identifiers + * the IDs of the entities + * @return the list of entity objects in the same order as the given list of identifiers. If one + * or more requested IDs do not exist in the Cloud Datastore, the corresponding item in + * the returned list be null. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List loadById(Class entityClass, List identifiers); - /** - * Loads and returns the entity with the given key. - * - * @param entityClass - * the entity class (expected result type) - * @param key - * full key of the entity - * @return the Entity object or null, if the the entity with - * the given key does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while accessing the Cloud Datastore. - */ - E load(Class entityClass, DatastoreKey key); + /** + * Loads and returns the entities with the given names (a.k.a String IDs). The entities are + * assumed to be root entities (no parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param identifiers + * the IDs of the entities + * @return the list of entity objects in the same order as the given list of identifiers. If one + * or more requested IDs do not exist in the Cloud Datastore, the corresponding item in + * the returned list be null. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List loadByName(Class entityClass, List identifiers); - /** - * Loads and returns the entities for the given keys. - * - * @param entityClass - * the entity class (expected result type) - * @param keys - * entity keys to load - * @return the Entity objects for the given keys. If one or more requested - * keys do not exist in the Cloud Datastore, the corresponding item - * in the returned list be null. - * - * @throws EntityManagerException - * if any error occurs while accessing the Cloud Datastore. - */ - List loadByKey(Class entityClass, List keys); + /** + * Loads and returns the entities for the given keys. + * + * @param entityClass + * the entity class (expected result type) + * @param keys + * entity keys to load + * @return the Entity objects for the given keys. If one or more requested keys do not exist in + * the Cloud Datastore, the corresponding item in the returned list be null. + * + * @throws EntityManagerException + * if any error occurs while accessing the Cloud Datastore. + */ + List loadByKey(Class entityClass, List keys); - /** - * Creates and returns a new {@link EntityQueryRequest} for the given GQL - * query string. The returned {@link EntityQueryRequest} can be further - * customized to set any bindings (positional or named), and then be - * executed by calling the execute or - * executeEntityQuery methods. - * - * @param query - * the GQL query - * @return a new QueryRequest for the given GQL query - */ - EntityQueryRequest createEntityQueryRequest(String query); + /** + * Creates and returns a new {@link EntityQueryRequest} for the given GQL query string. The + * returned {@link EntityQueryRequest} can be further customized to set any bindings (positional + * or named), and then be executed by calling the execute or + * executeEntityQuery methods. + * + * @param query + * the GQL query + * @return a new QueryRequest for the given GQL query + */ + EntityQueryRequest createEntityQueryRequest(String query); - /** - * Creates and returns a new {@link ProjectionQueryRequest} for the given - * GQL query string. The returned {@link ProjectionQueryRequest} can further - * be customized to set any positional and/or named bindings, and then be - * executed by calling the execute or - * executeProjectionQuery methods. - * - * @param query - * the GQL projection query - * @return a new ProjectionQueryRequest for the given query - */ - ProjectionQueryRequest createProjectionQueryRequest(String query); + /** + * Creates and returns a new {@link ProjectionQueryRequest} for the given GQL query string. The + * returned {@link ProjectionQueryRequest} can further be customized to set any positional and/or + * named bindings, and then be executed by calling the execute or + * executeProjectionQuery methods. + * + * @param query + * the GQL projection query + * @return a new ProjectionQueryRequest for the given query + */ + ProjectionQueryRequest createProjectionQueryRequest(String query); - /** - * Creates and returns a new {@link KeyQueryRequest} for the given GQL query - * string. Key query requests must only have __key__ in the - * SELECT list of field. The returned {@link KeyQueryRequest} - * can further be customized to set any positional and/or named bindings, - * and then be executed by calling the executeKeyQuery method. - * - * @param query - * the GQL projection query - * @return a new ProjectionQueryRequest for the given query - */ - KeyQueryRequest createKeyQueryRequest(String query); + /** + * Creates and returns a new {@link KeyQueryRequest} for the given GQL query string. Key query + * requests must only have __key__ in the SELECT list of field. The returned + * {@link KeyQueryRequest} can further be customized to set any positional and/or named bindings, + * and then be executed by calling the executeKeyQuery method. + * + * @param query + * the GQL projection query + * @return a new ProjectionQueryRequest for the given query + */ + KeyQueryRequest createKeyQueryRequest(String query); - /** - * Executes the given {@link EntityQueryRequest} and returns the response. - * - * @param expectedResultType - * the expected type of results. - * @param request - * the entity query request - * @return the query response - */ - QueryResponse executeEntityQueryRequest(Class expectedResultType, EntityQueryRequest request); + /** + * Executes the given {@link EntityQueryRequest} and returns the response. + * + * @param expectedResultType + * the expected type of results. + * @param request + * the entity query request + * @return the query response + */ + QueryResponse executeEntityQueryRequest(Class expectedResultType, + EntityQueryRequest request); - /** - * Executes the given {@link ProjectionQueryRequest} and returns the - * response. - * - * @param expectedResultType - * the expected type of results. - * @param request - * the projection query request - * @return the query response - */ - QueryResponse executeProjectionQueryRequest(Class expectedResultType, ProjectionQueryRequest request); + /** + * Executes the given {@link ProjectionQueryRequest} and returns the response. + * + * @param expectedResultType + * the expected type of results. + * @param request + * the projection query request + * @return the query response + */ + QueryResponse executeProjectionQueryRequest(Class expectedResultType, + ProjectionQueryRequest request); - /** - * Executes the given {@link KeyQueryRequest} and returns the response. - * - * @param request - * the key query request - * @return the query response - */ - QueryResponse executeKeyQueryRequest(KeyQueryRequest request); + /** + * Executes the given {@link KeyQueryRequest} and returns the response. + * + * @param request + * the key query request + * @return the query response + */ + QueryResponse executeKeyQueryRequest(KeyQueryRequest request); } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreBatch.java b/src/main/java/com/jmethods/catatumbo/DatastoreBatch.java index 830ea28..de6278b 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreBatch.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreBatch.java @@ -19,287 +19,275 @@ import java.util.List; /** - * Interface for executing Batch updates (Insert/Update/Delete). Instances of - * this class are obtained by calling {@link EntityManager#newBatch()}. + * Interface for executing Batch updates (Insert/Update/Delete). Instances of this class are + * obtained by calling {@link EntityManager#newBatch()}. * * @author Sai Pullabhotla * */ public interface DatastoreBatch { - /** - * Adds the given entity to this batch for insertion. If the entity does not - * have an identifier set, ID may be automatically generated. If the same - * entity was added to this batch for deletion, the insert request is - * changed into an upsert request. - * - * @param entity - * the entity to insert. - * @return the inserted entity. The inserted entity may not be same as the - * passed in entity. For example, the inserted entity may contain - * any generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - E insert(E entity); + /** + * Adds the given entity to this batch for insertion. If the entity does not have an identifier + * set, ID may be automatically generated. If the same entity was added to this batch for + * deletion, the insert request is changed into an upsert request. + * + * @param entity + * the entity to insert. + * @return the inserted entity. The inserted entity may not be same as the passed in entity. For + * example, the inserted entity may contain any generated ID, key, parent key, etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + E insert(E entity); - /** - * Adds the given entities to this batch for insertion. If any of the - * entities do not have an identifier set, ID may be generated - * automatically. If any of entities were added to this batch for deletion, - * the insert request is changed to an upsert request. - * - * @param entities - * the entities to insert. - * @return the inserted entities. The inserted entities may not be same as - * the passed in entities. For example, the inserted entities may - * contain generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List insert(List entities); + /** + * Adds the given entities to this batch for insertion. If any of the entities do not have an + * identifier set, ID may be generated automatically. If any of entities were added to this batch + * for deletion, the insert request is changed to an upsert request. + * + * @param entities + * the entities to insert. + * @return the inserted entities. The inserted entities may not be same as the passed in entities. + * For example, the inserted entities may contain generated ID, key, parent key, etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List insert(List entities); - /** - * Adds the given entity to this batch for insertion. The ID allocation is - * deferred to the submit time of this batch. Generated keys can be - * retrieved using {@link DatastoreBatch.Response#getGeneratedKeys()}.This - * method throws {@link EntityManagerException} if the entity is using a - * String identifier. String identifiers are allocated at add time, instead - * of submit time. For entities with String identifiers, use the - * {@link DatastoreBatch#insert(Object)} method. - * - * @param entity - * the entity to insert - * @throws EntityManagerException - * if the entity has a String identifier or if any error occurs - */ - void insertWithDeferredIdAllocation(E entity); + /** + * Adds the given entity to this batch for insertion. The ID allocation is deferred to the submit + * time of this batch. Generated keys can be retrieved using + * {@link DatastoreBatch.Response#getGeneratedKeys()}.This method throws + * {@link EntityManagerException} if the entity is using a String identifier. String identifiers + * are allocated at add time, instead of submit time. For entities with String identifiers, use + * the {@link DatastoreBatch#insert(Object)} method. + * + * @param entity + * the entity to insert + * @throws EntityManagerException + * if the entity has a String identifier or if any error occurs + */ + void insertWithDeferredIdAllocation(E entity); - /** - * Adds the given entities to this batch for insertion. The ID allocation is - * deferred to the submit time of this batch. Generated keys can be - * retrieved using {@link DatastoreBatch.Response#getGeneratedKeys()}.This - * method throws {@link EntityManagerException} if the entity is using a - * String identifier. String identifiers are allocated at add time, instead - * of submit time. For entities with String identifiers, use the - * {@link DatastoreBatch#insert(List)} method. - * - * @param entities - * the entities to insert - * @throws EntityManagerException - * if the entity have a String identifier any error occurs - */ - void insertWithDeferredIdAllocation(List entities); + /** + * Adds the given entities to this batch for insertion. The ID allocation is deferred to the + * submit time of this batch. Generated keys can be retrieved using + * {@link DatastoreBatch.Response#getGeneratedKeys()}.This method throws + * {@link EntityManagerException} if the entity is using a String identifier. String identifiers + * are allocated at add time, instead of submit time. For entities with String identifiers, use + * the {@link DatastoreBatch#insert(List)} method. + * + * @param entities + * the entities to insert + * @throws EntityManagerException + * if the entity have a String identifier any error occurs + */ + void insertWithDeferredIdAllocation(List entities); - /** - * Adds the given entity to this batch for update. The operation will fail - * if the entity with the same key does not exist in the underlying - * Datastore. This method does not use optimistic locking even if the given - * entity has a field with {@link Version} annotation. - * - * @param entity - * the entity to update - * @return the updated entity. - * @throws EntityManagerException - * if any error occurs while updating. - */ - E update(E entity); + /** + * Adds the given entity to this batch for update. The operation will fail if the entity with the + * same key does not exist in the underlying Datastore. This method does not use optimistic + * locking even if the given entity has a field with {@link Version} annotation. + * + * @param entity + * the entity to update + * @return the updated entity. + * @throws EntityManagerException + * if any error occurs while updating. + */ + E update(E entity); - /** - * Adds the given entities to this batch for update. The operation will fail - * if the entities with the same key do not already exist in the underlying - * datastore. This method does not use optimistic locking even if the given - * entity has a field with {@link Version} annotation. - * - * - * @param entities - * the entities to update. - * @return the updated entities - * @throws EntityManagerException - * if any error occurs while inserting. - */ - List update(List entities); + /** + * Adds the given entities to this batch for update. The operation will fail if the entities with + * the same key do not already exist in the underlying datastore. This method does not use + * optimistic locking even if the given entity has a field with {@link Version} annotation. + * + * + * @param entities + * the entities to update. + * @return the updated entities + * @throws EntityManagerException + * if any error occurs while inserting. + */ + List update(List entities); - /** - * Adds the given entity to this batch for update or insert. Any prior - * writes to this entity in this batch will be removed from this batch. If - * the entity does not have an ID set, ID may be generated automatically. - * - * @param entity - * the entity to update or insert - * @return the updated/inserted entity. - * @throws EntityManagerException - * if any error occurs while saving. - */ - E upsert(E entity); + /** + * Adds the given entity to this batch for update or insert. Any prior writes to this entity in + * this batch will be removed from this batch. If the entity does not have an ID set, ID may be + * generated automatically. + * + * @param entity + * the entity to update or insert + * @return the updated/inserted entity. + * @throws EntityManagerException + * if any error occurs while saving. + */ + E upsert(E entity); - /** - * Adds the given entities to this batch for update or insert. Any prior - * writes of any of the entities will be removed from this batch. If any of - * the entities do not have their IDs set, IDs may be generated - * automatically. - * - * @param entities - * the entities to update/or insert. - * @return the updated or inserted entities - * @throws EntityManagerException - * if any error occurs while saving. - */ - List upsert(List entities); + /** + * Adds the given entities to this batch for update or insert. Any prior writes of any of the + * entities will be removed from this batch. If any of the entities do not have their IDs set, IDs + * may be generated automatically. + * + * @param entities + * the entities to update/or insert. + * @return the updated or inserted entities + * @throws EntityManagerException + * if any error occurs while saving. + */ + List upsert(List entities); - /** - * Adds the given entity to this batch for insert or update. The ID (for - * numeric ID) allocation will be deferred to the submit time of this batch. - * This method throws an {@link EntityManagerException} if the entity is - * using a String ID. Entity with String ID should use - * {@link DatastoreBatch#upsert(Object)} method. - * - * @param entity - * the entity to update or insert - * @throws EntityManagerException - * if the entity has a String ID or any other error occurs while - * accessing the underlying datastore. - */ - void upsertWithDeferredIdAllocation(E entity); + /** + * Adds the given entity to this batch for insert or update. The ID (for numeric ID) allocation + * will be deferred to the submit time of this batch. This method throws an + * {@link EntityManagerException} if the entity is using a String ID. Entity with String ID should + * use {@link DatastoreBatch#upsert(Object)} method. + * + * @param entity + * the entity to update or insert + * @throws EntityManagerException + * if the entity has a String ID or any other error occurs while accessing the + * underlying datastore. + */ + void upsertWithDeferredIdAllocation(E entity); - /** - * Adds the given entities to this batch for update or insert. The ID (for - * numeric ID) allocation will be deferred to the submit time of this batch. - * This method throws an {@link EntityManagerException} if the entities have - * String identifiers. Entities with String identifiers should use - * {@link DatastoreBatch#upsert(List)} method. - * - * @param entities - * the entities to update or insert - * @throws EntityManagerException - * if the entities have String identifiers or any other error - * occurs while accessing the underlying datastore. - */ - void upsertWithDeferredIdAllocation(List entities); + /** + * Adds the given entities to this batch for update or insert. The ID (for numeric ID) allocation + * will be deferred to the submit time of this batch. This method throws an + * {@link EntityManagerException} if the entities have String identifiers. Entities with String + * identifiers should use {@link DatastoreBatch#upsert(List)} method. + * + * @param entities + * the entities to update or insert + * @throws EntityManagerException + * if the entities have String identifiers or any other error occurs while accessing the + * underlying datastore. + */ + void upsertWithDeferredIdAllocation(List entities); - /** - * Adds the given entity to this batch for deletion. - * - * @param entity - * the entity to delete. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void delete(Object entity); + /** + * Adds the given entity to this batch for deletion. + * + * @param entity + * the entity to delete. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void delete(Object entity); - /** - * Adds the given entities to this batch for deletion. - * - * @param entities - * the entities to delete. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void delete(List entities); + /** + * Adds the given entities to this batch for deletion. + * + * @param entities + * the entities to delete. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void delete(List entities); - /** - * Adds the given key to this batch for deletion. - * - * @param key - * the key to delete - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void deleteByKey(DatastoreKey key); + /** + * Adds the given ID and entity type to this batch for deletion. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, long id); - /** - * Adds the given keys to this batch for deletion. - * - * @param keys - * the keys to delete - * @throws EntityManagerException - * if any error occurs while deleting. - */ - void deleteByKey(List keys); + /** + * Adds the given ID and entity type to this batch for deletion. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, String id); - /** - * Adds the given ID and entity type to this batch for deletion. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, long id); + /** + * Adds the given entity type, parent key and ID to this batch for deletion. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, DatastoreKey parentKey, long id); - /** - * Adds the given ID and entity type to this batch for deletion. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, String id); + /** + * Adds the given entity type, parent key and ID to this batch for deletion. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + void delete(Class entityClass, DatastoreKey parentKey, String id); - /** - * Adds the given entity type, parent key and ID to this batch for deletion. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, DatastoreKey parentKey, long id); + /** + * Adds the given key to this batch for deletion. + * + * @param key + * the key to delete + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void deleteByKey(DatastoreKey key); - /** - * Adds the given entity type, parent key and ID to this batch for deletion. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - void delete(Class entityClass, DatastoreKey parentKey, String id); + /** + * Adds the given keys to this batch for deletion. + * + * @param keys + * the keys to delete + * @throws EntityManagerException + * if any error occurs while deleting. + */ + void deleteByKey(List keys); - /** - * Tells whether or not this DatastoreBatch is still active. A - * DatastoreBatch is considered active if it is not submitted yet. - * - * @return true, if this batch is active; false, - * otherwise. - */ - boolean isActive(); + /** + * Tells whether or not this DatastoreBatch is still active. A DatastoreBatch is considered active + * if it is not submitted yet. + * + * @return true, if this batch is active; false, otherwise. + */ + boolean isActive(); - /** - * Submits the batch operations to the Cloud Datastore. - * - * @return the response of the batch operation. - * @throws EntityManagerException - * if any error occurs - */ - Response submit(); + /** + * Submits the batch operations to the Cloud Datastore. + * + * @return the response of the batch operation. + * @throws EntityManagerException + * if any error occurs + */ + Response submit(); - /** - * Response when the the batch is submitted. - * - * @author Sai Pullabhotla - * - */ - interface Response { - /** - * Returns a list of generated keys. - * - * @return a list of generated keys. - */ - List getGeneratedKeys(); - } + /** + * Response when the the batch is submitted. + * + * @author Sai Pullabhotla + * + */ + interface Response { + /** + * Returns a list of generated keys. + * + * @return a list of generated keys. + */ + List getGeneratedKeys(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreCursor.java b/src/main/java/com/jmethods/catatumbo/DatastoreCursor.java index 9efd4f6..2280f1d 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreCursor.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreCursor.java @@ -17,19 +17,19 @@ package com.jmethods.catatumbo; /** - * Defines a contract for Datastore Cursors. Cursors are used to indicate the - * starting/ending point of a result set. + * Defines a contract for Datastore Cursors. Cursors are used to indicate the starting/ending point + * of a result set. * * @author Sai Pullabhotla * */ public interface DatastoreCursor { - /** - * Returns the encoded value of this cursor as a String. - * - * @return the encoded value of this cursor. - */ - String getEncoded(); + /** + * Returns the encoded value of this cursor as a String. + * + * @return the encoded value of this cursor. + */ + String getEncoded(); } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreKey.java b/src/main/java/com/jmethods/catatumbo/DatastoreKey.java index 9ddd3de..4cdb211 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreKey.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreKey.java @@ -19,99 +19,93 @@ import java.io.Serializable; /** - * Objects of this class represent Keys in the Cloud Datastore. Keys contain the - * kind and identifier (long or String) as well as any ancestor keys.The primary - * purpose of this interface is to facilitate support for Keys, Parent Keys and - * Key References. The EntityManager sets the keys when entities are loaded from - * the Datastore or saved to the Datastore. + * Objects of this class represent Keys in the Cloud Datastore. Keys contain the kind and identifier + * (long or String) as well as any ancestor keys.The primary purpose of this interface is to + * facilitate support for Keys, Parent Keys and Key References. The EntityManager sets the keys when + * entities are loaded from the Datastore or saved to the Datastore. * * @author Sai Pullabhotla * */ public interface DatastoreKey extends Serializable { - /** - * Returns the project ID. - * - * @return the project ID. - */ - String projectId(); + /** + * Returns the project ID. + * + * @return the project ID. + */ + String projectId(); - /** - * Returns the namespace. - * - * @return the namespace. - */ - String namespace(); + /** + * Returns the namespace. + * + * @return the namespace. + */ + String namespace(); - /** - * Returns the kind. - * - * @return the kind. - */ - String kind(); + /** + * Returns the kind. + * + * @return the kind. + */ + String kind(); - /** - * Tells whether or not this key has a numeric (long) ID. - * - * @return true, if this key has a numeric (long) ID; - * false, otherwise. - */ - boolean hasId(); + /** + * Tells whether or not this key has a numeric (long) ID. + * + * @return true, if this key has a numeric (long) ID; false, otherwise. + */ + boolean hasId(); - /** - * Tells whether or not this key has a String ID. - * - * @return true, if this key has a String ID; - * false, otherwise. - */ - boolean hasName(); + /** + * Tells whether or not this key has a String ID. + * + * @return true, if this key has a String ID; false, otherwise. + */ + boolean hasName(); - /** - * Returns the numeric ID of this key. - * - * @return the numeric ID of this key. - */ - long id(); + /** + * Returns the numeric ID of this key. + * + * @return the numeric ID of this key. + */ + long id(); - /** - * Returns the String ID of this key. - * - * @return the String ID of this key. - */ - String name(); + /** + * Returns the String ID of this key. + * + * @return the String ID of this key. + */ + String name(); - /** - * Returns the ID of this key. Returned type depends on if this key has a - * numeric ID or String ID. - * - * @return the ID of this key. Returned type depends on if this key has a - * numeric ID or String ID. - * - */ - Object nameOrId(); + /** + * Returns the ID of this key. Returned type depends on if this key has a numeric ID or String ID. + * + * @return the ID of this key. Returned type depends on if this key has a numeric ID or String ID. + * + */ + Object nameOrId(); - /** - * Returns the parent key, if one exists. - * - * @return the parent key or null, if this key is a root key - * (no parent). - */ - DatastoreKey parent(); + /** + * Returns the parent key, if one exists. + * + * @return the parent key or null, if this key is a root key (no parent). + */ + DatastoreKey parent(); - /** - * Returns a String representation of this key. - * - * @return a String representation of this key. - */ - String getEncoded(); + /** + * Returns a String representation of this key. + * + * @return a String representation of this key. + */ + String getEncoded(); - /** - * Returns the underlying Datastore key. - * - * @return the underlying Datastore key. - */ - // Don't really like this here. - com.google.cloud.datastore.Key nativeKey(); + /** + * Returns the underlying Datastore key. + * + * @return the underlying Datastore key. + */ + // Don't really like this here. + com.google.cloud.datastore.Key nativeKey(); } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreMetadata.java b/src/main/java/com/jmethods/catatumbo/DatastoreMetadata.java index e090868..d277e21 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreMetadata.java @@ -19,102 +19,98 @@ import java.util.List; /** - * Interface that provides the metadata of the Datastore, such as the namespaces - * in the Datastore, the various Kinds in a namespace and the Properties of a - * Kind. - * - * Objects of this class may be obtained from the {@link EntityManager} by - * calling the {@link EntityManager#getDatastoreMetadata()}. + * Interface that provides the metadata of the Datastore, such as the namespaces in the Datastore, + * the various Kinds in a namespace and the Properties of a Kind. + *

+ * Objects of this class may be obtained from the {@link EntityManager} by calling the + * {@link EntityManager#getDatastoreMetadata()}. + *

* * @author Sai Pullabhotla * */ public interface DatastoreMetadata { - /** - * Returns all the namespaces in the Datastore. The results will be ordered - * by name in ascending order. Exercise caution when using this method on a - * Datastore that has many many namespaces. Use one of the overloaded - * methods to get a page of namespaces. - * - * @return the list of namespaces. The default namespace, if exists, would - * be returned as an empty string, typically the first namespace in - * the returned list. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - List getNamespaces(); + /** + * Returns all the namespaces in the Datastore. The results will be ordered by name in ascending + * order. Exercise caution when using this method on a Datastore that has many many namespaces. + * Use one of the overloaded methods to get a page of namespaces. + * + * @return the list of namespaces. The default namespace, if exists, would be returned as an empty + * string, typically the first namespace in the returned list. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + List getNamespaces(); - /** - * Returns the namespaces, up to the specified limit. The returned results - * will be ordered by name in ascending order. - * - * @param limit - * the maximum number of namespaces to return. A limit of zero or - * less is interpreted as no limit and returns all results. - * @return the namespaces, up to the specified limit. The default namespace, - * if exists, would be returned as an empty string. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - QueryResponse getNamespaces(int limit); + /** + * Returns the namespaces, up to the specified limit. The returned results will be ordered by name + * in ascending order. + * + * @param limit + * the maximum number of namespaces to return. A limit of zero or less is interpreted as + * no limit and returns all results. + * @return the namespaces, up to the specified limit. The default namespace, if exists, would be + * returned as an empty string. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + QueryResponse getNamespaces(int limit); - /** - * Returns the namespaces, up to the specified limit, from the specified - * cursor location. The results will be ordered by name in ascending order. - * - * @param fromCursor - * the cursor location from which the results should start. - * @param limit - * the maximum number of namespaces to return - * @return the namespaces from the specified cursor location. The default - * namespace, if exists, would be returned as an empty string. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - QueryResponse getNamespaces(DatastoreCursor fromCursor, int limit); + /** + * Returns the namespaces, up to the specified limit, from the specified cursor location. The + * results will be ordered by name in ascending order. + * + * @param fromCursor + * the cursor location from which the results should start. + * @param limit + * the maximum number of namespaces to return + * @return the namespaces from the specified cursor location. The default namespace, if exists, + * would be returned as an empty string. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + QueryResponse getNamespaces(DatastoreCursor fromCursor, int limit); - /** - * Returns the available Kinds from the current namespace, where current - * namespace is the the namespace set using {@link Tenant} or the namespace - * with which the {@link EntityManager} was created. - * - * @return the Kinds in the current namespace. The returned results will be - * order by Kind's name in ascending order. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - List getKinds(); + /** + * Returns the available Kinds from the current namespace, where current namespace is the the + * namespace set using {@link Tenant} or the namespace with which the {@link EntityManager} was + * created. + * + * @return the Kinds in the current namespace. The returned results will be order by Kind's name + * in ascending order. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + List getKinds(); - /** - * Returns the available Kinds from the current namespace, where current - * namespace is the the namespace set using {@link Tenant} or the namespace - * with which the {@link EntityManager} was created. - * - * @param excludeSystemKinds - * whether or not to exclude System Kinds (e.g. Kinds begin with - * two underscores). - * - * @return the Kinds in the current namespace. The returned results will be - * order by Kind's name in ascending order. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - List getKinds(boolean excludeSystemKinds); + /** + * Returns the available Kinds from the current namespace, where current namespace is the the + * namespace set using {@link Tenant} or the namespace with which the {@link EntityManager} was + * created. + * + * @param excludeSystemKinds + * whether or not to exclude System Kinds (e.g. Kinds begin with two underscores). + * + * @return the Kinds in the current namespace. The returned results will be order by Kind's name + * in ascending order. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + List getKinds(boolean excludeSystemKinds); - /** - * Returns the list of Properties in the specified Kind. The returned list - * only contains indexed properties. If the {@link Tenant} has a namespace - * set, it will be used. Otherwise, the namespace with which the - * {@link EntityManager} was created. The returned list is order by property - * name in ascending order. - * - * @param kind - * the Kind - * @return the indexed properties in the given Kind. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - List getProperties(String kind); + /** + * Returns the list of Properties in the specified Kind. The returned list only contains indexed + * properties. If the {@link Tenant} has a namespace set, it will be used. Otherwise, the + * namespace with which the {@link EntityManager} was created. The returned list is order by + * property name in ascending order. + * + * @param kind + * the Kind + * @return the indexed properties in the given Kind. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + List getProperties(String kind); } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreProperty.java b/src/main/java/com/jmethods/catatumbo/DatastoreProperty.java index 7085fb2..1313f1e 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreProperty.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreProperty.java @@ -30,144 +30,144 @@ @Entity(kind = "__property__") public class DatastoreProperty implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 6647639868379397875L; - - /** - * Property name - */ - @Identifier - private String name; - - /** - * The full key of this property - */ - @Key - private DatastoreKey key; - - /** - * Entity Key - */ - @ParentKey - private DatastoreKey entityKey; - - /** - * The data types - */ - @Property(name = "property_representation") - private List dataTypes; - - /** - * Returns the name of this Property. - * - * @return the name of this Property. - */ - public String getName() { - return name; - } - - /** - * Sets the name of this property. - * - * @param name - * the property name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the full key of this property. - * - * @return the full key of this property. - */ - public DatastoreKey getKey() { - return key; - } - - /** - * Sets the full key of this property. - * - * @param key - * the full key of this property. - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * Returns the key of the owning entity. - * - * @return the key of the owning entity. - */ - public DatastoreKey getEntityKey() { - return entityKey; - } - - /** - * Sets the owning entity's key. - * - * @param entityKey - * the owning entity's key. - */ - public void setEntityKey(DatastoreKey entityKey) { - this.entityKey = entityKey; - } - - /** - * Returns the data types. - * - * @return the data types - */ - public List getDataTypes() { - return dataTypes; - } - - /** - * Sets the data types. - * - * @param dataTypes - * the data types - */ - public void setDataTypes(List dataTypes) { - this.dataTypes = dataTypes; - } - - /** - * Returns the name of the owning entity. - * - * @return the name of the owning entity. - */ - public String getEntityName() { - return entityKey.name(); - } - - /** - * Returns a String representation of this DatastoreProperty. The returned - * value will be of the form - EntityName.PropertyName. - */ - @Override - public String toString() { - return getEntityName() + "." + name; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !(obj instanceof DatastoreProperty)) { - return false; - } - DatastoreProperty that = (DatastoreProperty) obj; - return Objects.equals(this.key, that.key); - } - - @Override - public int hashCode() { - return Objects.hashCode(key); - } + /** + * Serial version UID + */ + private static final long serialVersionUID = 6647639868379397875L; + + /** + * Property name + */ + @Identifier + private String name; + + /** + * The full key of this property + */ + @Key + private DatastoreKey key; + + /** + * Entity Key + */ + @ParentKey + private DatastoreKey entityKey; + + /** + * The data types + */ + @Property(name = "property_representation") + private List dataTypes; + + /** + * Returns the name of this Property. + * + * @return the name of this Property. + */ + public String getName() { + return name; + } + + /** + * Sets the name of this property. + * + * @param name + * the property name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the full key of this property. + * + * @return the full key of this property. + */ + public DatastoreKey getKey() { + return key; + } + + /** + * Sets the full key of this property. + * + * @param key + * the full key of this property. + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * Returns the key of the owning entity. + * + * @return the key of the owning entity. + */ + public DatastoreKey getEntityKey() { + return entityKey; + } + + /** + * Sets the owning entity's key. + * + * @param entityKey + * the owning entity's key. + */ + public void setEntityKey(DatastoreKey entityKey) { + this.entityKey = entityKey; + } + + /** + * Returns the data types. + * + * @return the data types + */ + public List getDataTypes() { + return dataTypes; + } + + /** + * Sets the data types. + * + * @param dataTypes + * the data types + */ + public void setDataTypes(List dataTypes) { + this.dataTypes = dataTypes; + } + + /** + * Returns the name of the owning entity. + * + * @return the name of the owning entity. + */ + public String getEntityName() { + return entityKey.name(); + } + + /** + * Returns a String representation of this DatastoreProperty. The returned value will be of the + * form - EntityName.PropertyName. + */ + @Override + public String toString() { + return getEntityName() + "." + name; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !(obj instanceof DatastoreProperty)) { + return false; + } + DatastoreProperty that = (DatastoreProperty) obj; + return Objects.equals(this.key, that.key); + } + + @Override + public int hashCode() { + return Objects.hashCode(key); + } } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreStats.java b/src/main/java/com/jmethods/catatumbo/DatastoreStats.java index 628aafc..43aa071 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreStats.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreStats.java @@ -26,141 +26,137 @@ import com.jmethods.catatumbo.stats.StatTotalNs; /** - * Provides access to various Datastore statistics. An instance of - * {@link DatastoreStats} is obtained by calling - * {@link EntityManager#getDatastoreStats()}. + * Provides access to various Datastore statistics. An instance of {@link DatastoreStats} is + * obtained by calling {@link EntityManager#getDatastoreStats()}. * * @author Sai Pullabhotla * */ public interface DatastoreStats { - /** - * Returns the Summary statistic. This includes the information from all - * namespaces. - * - * @return the Summary statistic. May be null, if the statistic - * is not available. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatTotal getSummary() throws EntityManagerException; - - /** - * Returns the summary statistic for the current namespace. If the - * {@link Tenant} has a namespace set, it will be used. Otherwise, the - * namespace with which the {@link EntityManager} was created. - * - * @return the summary statistic for the current namespace. May be - * null, if the statistic is not available. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatTotalNs getSummaryNs() throws EntityManagerException; - - /** - * Returns the summary statistics for the given namespace. - * - * @param namespace - * the namespace - * - * @return the summary statistics for the given namespace. May be - * null, if the statistic is not available. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatTotalNs getSummaryNs(String namespace) throws EntityManagerException; - - /** - * Returns the statistics by Kind, across all namespaces. The returned list - * contains one Statistic entity for each Kind. - * - * @return the statistics by Kind, across all namespaces. Returns an empty - * list if the statistics are not available. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - List getKinds() throws EntityManagerException; - - /** - * Returns the statistics for the given Kind, across all namespaces. - * - * @param kind - * the Kind name - * - * @return the statistics for the given Kind, across all namespaces. Returns - * null, if the statistic is not available. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatKind getKind(String kind) throws EntityManagerException; - - /** - * Returns the statistics by Kind, for the current namespace. The returned - * list contains one Statistic entity for each Kind. If the {@link Tenant} - * has a namespace set, it will be used. Otherwise, the namespace with which - * the {@link EntityManager} was created. - * - * @return the statistics by Kind, for the current namespace. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - List getKindsNs() throws EntityManagerException; - - /** - * Returns the statistics for the given Kind in the current namespace. If - * the {@link Tenant} has a namespace set, it will be used. Otherwise, the - * namespace with which the {@link EntityManager} was created. - * - * @param kind - * the Kind name - * - * @return the statistics for the given Kind in the current namespace. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatKindNs getKindNs(String kind) throws EntityManagerException; - - /** - * Returns the statistics for the given Kind and namespace. If the - * {@link Tenant} has a namespace set, it will be used. Otherwise, the - * namespace with which the {@link EntityManager} was created. - * - * @param namespace - * the namespace - * @param kind - * the Kind name - * - * @return the statistics for the given Kind and namespace. - * @throws EntityManagerException - * if any error occurs while retrieving the statistics. - */ - StatKindNs getKindNs(String namespace, String kind) throws EntityManagerException; - - /** - * Returns the statistics for composite indexes, across all namespaces. - * - * @return the statistics for composite indexes, across all namespaces. - */ - List getCompositeIndexes(); - - /** - * Returns the statistics for composite indexes for the current namespace. - * If the {@link Tenant} has a namespace set, it will be used. Otherwise, - * the namespace with which the {@link EntityManager} was created. - * - * @return the statistics for composite indexes in the current namespace. - */ - List getCompositeIndexesNs(); - - /** - * Returns the statistics for composite indexes for the given namespace. - * - * @param namespace - * the namespace for which the statistics should be retrieved. - * - * @return the statistics for composite indexes for the given namespace. - */ - List getCompositeIndexesNs(String namespace); + /** + * Returns the Summary statistic. This includes the information from all namespaces. + * + * @return the Summary statistic. May be null, if the statistic is not available. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatTotal getSummary() throws EntityManagerException; + + /** + * Returns the summary statistic for the current namespace. If the {@link Tenant} has a namespace + * set, it will be used. Otherwise, the namespace with which the {@link EntityManager} was + * created. + * + * @return the summary statistic for the current namespace. May be null, if the + * statistic is not available. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatTotalNs getSummaryNs() throws EntityManagerException; + + /** + * Returns the summary statistics for the given namespace. + * + * @param namespace + * the namespace + * + * @return the summary statistics for the given namespace. May be null, if the + * statistic is not available. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatTotalNs getSummaryNs(String namespace) throws EntityManagerException; + + /** + * Returns the statistics by Kind, across all namespaces. The returned list contains one Statistic + * entity for each Kind. + * + * @return the statistics by Kind, across all namespaces. Returns an empty list if the statistics + * are not available. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + List getKinds() throws EntityManagerException; + + /** + * Returns the statistics for the given Kind, across all namespaces. + * + * @param kind + * the Kind name + * + * @return the statistics for the given Kind, across all namespaces. Returns null, if + * the statistic is not available. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatKind getKind(String kind) throws EntityManagerException; + + /** + * Returns the statistics by Kind, for the current namespace. The returned list contains one + * Statistic entity for each Kind. If the {@link Tenant} has a namespace set, it will be used. + * Otherwise, the namespace with which the {@link EntityManager} was created. + * + * @return the statistics by Kind, for the current namespace. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + List getKindsNs() throws EntityManagerException; + + /** + * Returns the statistics for the given Kind in the current namespace. If the {@link Tenant} has a + * namespace set, it will be used. Otherwise, the namespace with which the {@link EntityManager} + * was created. + * + * @param kind + * the Kind name + * + * @return the statistics for the given Kind in the current namespace. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatKindNs getKindNs(String kind) throws EntityManagerException; + + /** + * Returns the statistics for the given Kind and namespace. If the {@link Tenant} has a namespace + * set, it will be used. Otherwise, the namespace with which the {@link EntityManager} was + * created. + * + * @param namespace + * the namespace + * @param kind + * the Kind name + * + * @return the statistics for the given Kind and namespace. + * @throws EntityManagerException + * if any error occurs while retrieving the statistics. + */ + StatKindNs getKindNs(String namespace, String kind) throws EntityManagerException; + + /** + * Returns the statistics for composite indexes, across all namespaces. + * + * @return the statistics for composite indexes, across all namespaces. + */ + List getCompositeIndexes(); + + /** + * Returns the statistics for composite indexes for the current namespace. If the {@link Tenant} + * has a namespace set, it will be used. Otherwise, the namespace with which the + * {@link EntityManager} was created. + * + * @return the statistics for composite indexes in the current namespace. + */ + List getCompositeIndexesNs(); + + /** + * Returns the statistics for composite indexes for the given namespace. + * + * @param namespace + * the namespace for which the statistics should be retrieved. + * + * @return the statistics for composite indexes for the given namespace. + */ + List getCompositeIndexesNs(String namespace); } diff --git a/src/main/java/com/jmethods/catatumbo/DatastoreTransaction.java b/src/main/java/com/jmethods/catatumbo/DatastoreTransaction.java index 302d271..874fe39 100644 --- a/src/main/java/com/jmethods/catatumbo/DatastoreTransaction.java +++ b/src/main/java/com/jmethods/catatumbo/DatastoreTransaction.java @@ -19,13 +19,11 @@ import java.util.List; /** - * A Datastore Transaction. This interface extends the {@link DatastoreAccess}. - * DatastoreTransaction objects are created with a call to - * {@link EntityManager#newTransaction()}. Once a handle to - * {@link DatastoreTransaction} is obtained, it can be used to perform various - * database operations (read/write) within a transaction. Transactions are - * committed with the call to {@link DatastoreTransaction#commit()} method. - * Transactions can be rolled back with a call to + * A Datastore Transaction. This interface extends the {@link DatastoreAccess}. DatastoreTransaction + * objects are created with a call to {@link EntityManager#newTransaction()}. Once a handle to + * {@link DatastoreTransaction} is obtained, it can be used to perform various database operations + * (read/write) within a transaction. Transactions are committed with the call to + * {@link DatastoreTransaction#commit()} method. Transactions can be rolled back with a call to * {@link DatastoreTransaction#rollback()}. * * @author Sai Pullabhotla @@ -33,100 +31,98 @@ */ public interface DatastoreTransaction extends DatastoreAccess { - /** - * Inserts the given entity. ID allocation is deferred to the submit time. - * Generated key, if any, can be retrieved by calling - * {@link DatastoreTransaction.Response#getGeneratedKeys()}. - * - * @param entity - * the entity to insert. - * @throws EntityManagerException - * if the entity has a String Identifier or any other error - * occurs while accessing the underlying Datastore. - */ - void insertWithDeferredIdAllocation(E entity); + /** + * Inserts the given entity. ID allocation is deferred to the submit time. Generated key, if any, + * can be retrieved by calling {@link DatastoreTransaction.Response#getGeneratedKeys()}. + * + * @param entity + * the entity to insert. + * @throws EntityManagerException + * if the entity has a String Identifier or any other error occurs while accessing the + * underlying Datastore. + */ + void insertWithDeferredIdAllocation(E entity); - /** - * Inserts the given entities. ID allocation is deferred to the submit time. - * Generated keys, if any, can be retrieved by calling - * {@link DatastoreTransaction.Response#getGeneratedKeys()}. - * - * @param entities - * the entities to insert - * @throws EntityManagerException - * if the entity has a String Identifier or any other error - * occurs while accessing the underlying Datastore. - */ - void insertWithDeferredIdAllocation(List entities); + /** + * Inserts the given entities. ID allocation is deferred to the submit time. Generated keys, if + * any, can be retrieved by calling {@link DatastoreTransaction.Response#getGeneratedKeys()}. + * + * @param entities + * the entities to insert + * @throws EntityManagerException + * if the entity has a String Identifier or any other error occurs while accessing the + * underlying Datastore. + */ + void insertWithDeferredIdAllocation(List entities); - /** - * Updates or inserts the given entity. ID allocation is deferred to the - * submit time. Generated key, if any, can be retrieved by calling - * {@link DatastoreTransaction.Response#getGeneratedKeys()}. - * - * - * @param entity - * the entity to update or insert. - * @throws EntityManagerException - * if the entity has a String Identifier or any other error - * occurs while accessing the underlying Datastore. - */ - void upsertWithDeferredIdAllocation(E entity); + /** + * Updates or inserts the given entity. ID allocation is deferred to the submit time. Generated + * key, if any, can be retrieved by calling + * {@link DatastoreTransaction.Response#getGeneratedKeys()}. + * + * + * @param entity + * the entity to update or insert. + * @throws EntityManagerException + * if the entity has a String Identifier or any other error occurs while accessing the + * underlying Datastore. + */ + void upsertWithDeferredIdAllocation(E entity); - /** - * Updates or Inserts the given entities. ID allocation is deferred to the - * submit time. Generated keys, if any, can be retrieved by calling - * {@link DatastoreTransaction.Response#getGeneratedKeys()}. - * - * - * @param entities - * the entities to update or insert - * @throws EntityManagerException - * if the entity has a String Identifier or any other error - * occurs while accessing the underlying Datastore. - */ - void upsertWithDeferredIdAllocation(List entities); + /** + * Updates or Inserts the given entities. ID allocation is deferred to the submit time. Generated + * keys, if any, can be retrieved by calling + * {@link DatastoreTransaction.Response#getGeneratedKeys()}. + * + * + * @param entities + * the entities to update or insert + * @throws EntityManagerException + * if the entity has a String Identifier or any other error occurs while accessing the + * underlying Datastore. + */ + void upsertWithDeferredIdAllocation(List entities); - /** - * Tells if this DatastoreTransaction is still active. - * - * @return true, if this DatastoreTransaction is still active; - * false, otherwise. - */ - boolean isActive(); + /** + * Tells if this DatastoreTransaction is still active. + * + * @return true, if this DatastoreTransaction is still active; false, + * otherwise. + */ + boolean isActive(); - /** - * Commits changes made within this transaction. - * - * @return Response. The response contains any generated. - * - * @throws EntityManagerException - * if the commit fails. - */ - Response commit(); + /** + * Commits changes made within this transaction. + * + * @return Response. The response contains any generated. + * + * @throws EntityManagerException + * if the commit fails. + */ + Response commit(); - /** - * Rolls back the changes made in this transaction. - * - * @throws EntityManagerException - * if this transaction was already committed. - */ - void rollback(); + /** + * Rolls back the changes made in this transaction. + * + * @throws EntityManagerException + * if this transaction was already committed. + */ + void rollback(); - /** - * Transaction's commit Response. Used for returning generated keys for - * entities whose id allocation was deferred until submit/commit time. - * - * @author Sai Pullabhotla - * - */ - interface Response { - /** - * Returns a list of generated keys. - * - * @return a list of generated keys. - */ - List getGeneratedKeys(); - } + /** + * Transaction's commit Response. Used for returning generated keys for entities whose id + * allocation was deferred until submit/commit time. + * + * @author Sai Pullabhotla + * + */ + interface Response { + /** + * Returns a list of generated keys. + * + * @return a list of generated keys. + */ + List getGeneratedKeys(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/Decimal.java b/src/main/java/com/jmethods/catatumbo/Decimal.java index 5d16d95..3e80907 100644 --- a/src/main/java/com/jmethods/catatumbo/Decimal.java +++ b/src/main/java/com/jmethods/catatumbo/Decimal.java @@ -16,8 +16,8 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @@ -25,21 +25,19 @@ import com.jmethods.catatumbo.mappers.DecimalMapper; /** - * Specifies that the annotated field is of type decimal (aka numeric). This - * annotation can be applied to any BigDecimal field of an Entity, - * MappedSuperClass or Embeddable. When this annotation is present on a field, - * the persistence framework attaches a custom mapper, {@link DecimalMapper}, to - * map the data between model and Cloud Datastore. The custom mapper stores the - * data as a 64-bit integer in the Cloud Datastore. When reading data from the - * Datastore, the mapper converts the 64-bit integer to a BigDecimal based on - * the specified scale. + * Specifies that the annotated field is of type decimal (aka numeric). This annotation can be + * applied to any BigDecimal field of an Entity, MappedSuperClass or Embeddable. When this + * annotation is present on a field, the persistence framework attaches a custom mapper, + * {@link DecimalMapper}, to map the data between model and Cloud Datastore. The custom mapper + * stores the data as a 64-bit integer in the Cloud Datastore. When reading data from the Datastore, + * the mapper converts the 64-bit integer to a BigDecimal based on the specified scale. * *

* WARNING:
- * DO NOT CHANGE THE SCALE WHEN THERE IS ALREADY DATA IN THE DATASTORE. DOING SO - * WILL YIELD INCORRECT RESULTS. YOU MAY INCREASE THE PRECISION, BUT DO NOT - * DECREASE. IF IT IS NECESSARY TO CHANGE THE PRECISION OR SCALE, EXISTING DATA - * MUST BE UPDATED BEFORE CHANGING YOUR ENTITY.
+ * DO NOT CHANGE THE SCALE WHEN THERE IS ALREADY DATA IN THE DATASTORE. DOING SO WILL YIELD + * INCORRECT RESULTS. YOU MAY INCREASE THE PRECISION, BUT DO NOT DECREASE. IF IT IS NECESSARY TO + * CHANGE THE PRECISION OR SCALE, EXISTING DATA MUST BE UPDATED BEFORE CHANGING YOUR ENTITY. + * *

* * @author Sai Pullabhotla @@ -49,20 +47,19 @@ @Target(FIELD) public @interface Decimal { - /** - * The precision for a decimal property. Precision is the total number of - * digits before and after the decimal point. - * - * @return the precision - */ - int precision(); + /** + * The precision for a decimal property. Precision is the total number of digits before and after + * the decimal point. + * + * @return the precision + */ + int precision(); - /** - * The scale for a decimal property. Scale is maximum number of digits after - * the decimal point. - * - * @return the scale - */ - int scale(); + /** + * The scale for a decimal property. Scale is maximum number of digits after the decimal point. + * + * @return the scale + */ + int scale(); } diff --git a/src/main/java/com/jmethods/catatumbo/DefaultDatastoreCursor.java b/src/main/java/com/jmethods/catatumbo/DefaultDatastoreCursor.java index 9a75d33..8eb9440 100644 --- a/src/main/java/com/jmethods/catatumbo/DefaultDatastoreCursor.java +++ b/src/main/java/com/jmethods/catatumbo/DefaultDatastoreCursor.java @@ -27,54 +27,54 @@ */ public class DefaultDatastoreCursor implements DatastoreCursor, Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -6434001816829294681L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -6434001816829294681L; - /** - * Cursor data in URL-safe format - */ - private String encoded = null; + /** + * Cursor data in URL-safe format + */ + private String encoded = null; - /** - * Creates a new instance of DefaultDatastoreCursor. - * - * @param encoded - * cursor data, in URL-safe format. A null value - * will be converted to an empty string. - */ - public DefaultDatastoreCursor(String encoded) { - this.encoded = encoded != null ? encoded : ""; - } + /** + * Creates a new instance of DefaultDatastoreCursor. + * + * @param encoded + * cursor data, in URL-safe format. A null value will be converted to an + * empty string. + */ + public DefaultDatastoreCursor(String encoded) { + this.encoded = encoded != null ? encoded : ""; + } - /** - * Returns the encoded value of this cursor, in URL-safe format. - * - * @return the encoded value of this cursor, in URL-safe format. - */ - @Override - public String getEncoded() { - return encoded; - } + /** + * Returns the encoded value of this cursor, in URL-safe format. + * + * @return the encoded value of this cursor, in URL-safe format. + */ + @Override + public String getEncoded() { + return encoded; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof DefaultDatastoreCursor)) { - return false; - } - DefaultDatastoreCursor that = (DefaultDatastoreCursor) obj; - return this.encoded.equals(that.encoded); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof DefaultDatastoreCursor)) { + return false; + } + DefaultDatastoreCursor that = (DefaultDatastoreCursor) obj; + return this.encoded.equals(that.encoded); + } - @Override - public int hashCode() { - return Objects.hashCode(encoded); - } + @Override + public int hashCode() { + return Objects.hashCode(encoded); + } - @Override - public String toString() { - return encoded; - } + @Override + public String toString() { + return encoded; + } } diff --git a/src/main/java/com/jmethods/catatumbo/DefaultDatastoreKey.java b/src/main/java/com/jmethods/catatumbo/DefaultDatastoreKey.java index 3be9aa7..80a1c1d 100644 --- a/src/main/java/com/jmethods/catatumbo/DefaultDatastoreKey.java +++ b/src/main/java/com/jmethods/catatumbo/DefaultDatastoreKey.java @@ -28,115 +28,115 @@ */ public class DefaultDatastoreKey implements DatastoreKey, Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -5298686524012987642L; - - /** - * Native key from gcloud API - */ - private Key key; - - /** - * Creates a new instance of DefaultDatastoreKey. - * - * @param encoded - * the encoded string from which the key should be constructed. - */ - public DefaultDatastoreKey(String encoded) { - this(Key.fromUrlSafe(encoded)); - } - - /** - * Creates a new instance of DefaultDatastoreKey. - * - * @param key - * the native key. - */ - public DefaultDatastoreKey(Key key) { - this.key = key; - } - - @Override - public String namespace() { - return key.getNamespace(); - } - - @Override - public String projectId() { - return key.getProjectId(); - } - - @Override - public String kind() { - return key.getKind(); - } - - @Override - public boolean hasId() { - return key.hasId(); - } - - @Override - public boolean hasName() { - return key.hasName(); - } - - @Override - public long id() { - return key.getId(); - } - - @Override - public String name() { - return key.getName(); - } - - @Override - public Object nameOrId() { - return key.getNameOrId(); - } - - @Override - public DatastoreKey parent() { - Key parent = key.getParent(); - if (parent != null) { - return new DefaultDatastoreKey(parent); - } - return null; - } - - @Override - public String getEncoded() { - return key.toUrlSafe(); - } - - @Override - public Key nativeKey() { - return key; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof DefaultDatastoreKey)) { - return false; - } - DefaultDatastoreKey that = (DefaultDatastoreKey) obj; - return this.key.equals(that.key); - } - - @Override - public int hashCode() { - return key.hashCode(); - } - - @Override - public String toString() { - return key.toUrlSafe(); - } + /** + * Serial version UID + */ + private static final long serialVersionUID = -5298686524012987642L; + + /** + * Native key from gcloud API + */ + private Key key; + + /** + * Creates a new instance of DefaultDatastoreKey. + * + * @param encoded + * the encoded string from which the key should be constructed. + */ + public DefaultDatastoreKey(String encoded) { + this(Key.fromUrlSafe(encoded)); + } + + /** + * Creates a new instance of DefaultDatastoreKey. + * + * @param key + * the native key. + */ + public DefaultDatastoreKey(Key key) { + this.key = key; + } + + @Override + public String namespace() { + return key.getNamespace(); + } + + @Override + public String projectId() { + return key.getProjectId(); + } + + @Override + public String kind() { + return key.getKind(); + } + + @Override + public boolean hasId() { + return key.hasId(); + } + + @Override + public boolean hasName() { + return key.hasName(); + } + + @Override + public long id() { + return key.getId(); + } + + @Override + public String name() { + return key.getName(); + } + + @Override + public Object nameOrId() { + return key.getNameOrId(); + } + + @Override + public DatastoreKey parent() { + Key parent = key.getParent(); + if (parent != null) { + return new DefaultDatastoreKey(parent); + } + return null; + } + + @Override + public String getEncoded() { + return key.toUrlSafe(); + } + + @Override + public Key nativeKey() { + return key; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof DefaultDatastoreKey)) { + return false; + } + DefaultDatastoreKey that = (DefaultDatastoreKey) obj; + return this.key.equals(that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public String toString() { + return key.toUrlSafe(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/DefaultQueryResponse.java b/src/main/java/com/jmethods/catatumbo/DefaultQueryResponse.java index e36da26..a930209 100644 --- a/src/main/java/com/jmethods/catatumbo/DefaultQueryResponse.java +++ b/src/main/java/com/jmethods/catatumbo/DefaultQueryResponse.java @@ -22,78 +22,78 @@ * Default implementation of {@link QueryResponse} interface. * * @param - * the expected result type + * the expected result type * @author Sai Pullabhotla * */ public class DefaultQueryResponse implements QueryResponse { - /** - * A list to hold the results of the query - */ - protected List results = null; + /** + * A list to hold the results of the query + */ + protected List results = null; - /** - * Start cursor - */ - protected DatastoreCursor startCursor = null; + /** + * Start cursor + */ + protected DatastoreCursor startCursor = null; - /** - * End cursor - */ - protected DatastoreCursor endCursor = null; + /** + * End cursor + */ + protected DatastoreCursor endCursor = null; - /** - * Creates a new instance of BaseQueryResponse. - * - */ - public DefaultQueryResponse() { - // Do nothing - } + /** + * Creates a new instance of BaseQueryResponse. + * + */ + public DefaultQueryResponse() { + // Do nothing + } - @Override - public List getResults() { - return results; - } + @Override + public List getResults() { + return results; + } - /** - * Sets the results to the given results. - * - * @param results - * the results - */ - public void setResults(List results) { - this.results = results; - } + /** + * Sets the results to the given results. + * + * @param results + * the results + */ + public void setResults(List results) { + this.results = results; + } - @Override - public DatastoreCursor getStartCursor() { - return startCursor; - } + @Override + public DatastoreCursor getStartCursor() { + return startCursor; + } - /** - * Sets the starting cursor to the given value. - * - * @param startCursor - * the start cursor - */ - public void setStartCursor(DatastoreCursor startCursor) { - this.startCursor = startCursor; - } + /** + * Sets the starting cursor to the given value. + * + * @param startCursor + * the start cursor + */ + public void setStartCursor(DatastoreCursor startCursor) { + this.startCursor = startCursor; + } - @Override - public DatastoreCursor getEndCursor() { - return endCursor; - } + @Override + public DatastoreCursor getEndCursor() { + return endCursor; + } - /** - * Sets the end cursor to the given value. - * - * @param endCursor - * the end cursor - */ - public void setEndCursor(DatastoreCursor endCursor) { - this.endCursor = endCursor; - } + /** + * Sets the end cursor to the given value. + * + * @param endCursor + * the end cursor + */ + public void setEndCursor(DatastoreCursor endCursor) { + this.endCursor = endCursor; + } } diff --git a/src/main/java/com/jmethods/catatumbo/Embeddable.java b/src/main/java/com/jmethods/catatumbo/Embeddable.java index 40f03da..405c99d 100644 --- a/src/main/java/com/jmethods/catatumbo/Embeddable.java +++ b/src/main/java/com/jmethods/catatumbo/Embeddable.java @@ -23,59 +23,51 @@ import java.lang.annotation.Target; /** - * Specifies a class whose instances are stored as an intrinsic part of an - * owning entity and share the identity of the entity. Each of the persistent - * properties or fields of the embedded object are mapped to the owning entity - * in the Cloud Datastore. An Embeddable can contain other properties (with or - * without {@link Property} annotation). Further more, the embeddable objects + * Specifies a class whose instances are stored as an intrinsic part of an owning entity and share + * the identity of the entity. Each of the persistent properties or fields of the embedded object + * are mapped to the owning entity in the Cloud Datastore. An Embeddable can contain other + * properties (with or without {@link Property} annotation). Further more, the embeddable objects * can contain other {@link Embedded} objects. * *

- * Like {@link Entity entities}, the Embeddable class may use either the classic - * Java Beans pattern or the Builder pattern. + * Like {@link Entity entities}, the Embeddable class may use either the classic Java Beans pattern + * or the Builder pattern. *

* *

* Embeddable classes must adhere to the following rules: *

*
    - *
  • When using the classic Java Beans pattern, the class must have a public - * no-argument constructor
  • - *
  • Absence of public no-argument constructor assumes the use of Builder - * pattern.
  • - *
  • If using the Builder pattern, the class must have a public static method - * that returns an instance of Builder. The name of this method must be one of - * the following: + *
  • When using the classic Java Beans pattern, the class must have a public no-argument + * constructor
  • + *
  • Absence of public no-argument constructor assumes the use of Builder pattern.
  • + *
  • If using the Builder pattern, the class must have a public static method that returns an + * instance of Builder. The name of this method must be one of the following: *
      *
    • {@code newBuilder}
    • *
    • {@code builder}
    • *
    *
  • - *
  • The Builder class must have a public {@code build} method that returns an - * instance of Embeddable.
  • - *
  • For each persistable field, there must be corresponding accessor methods. - *
  • - *
  • When using the classic Java Beans pattern, each persistable field must - * have a corresponding mutator method.
  • - *
  • When using the Builder pattern, each persistable field must have a - * corresponding mutator method in the Builder class. The mutator methods must - * follow any of the below naming convention: + *
  • The Builder class must have a public {@code build} method that returns an instance of + * Embeddable.
  • + *
  • For each persistable field, there must be corresponding accessor methods.
  • + *
  • When using the classic Java Beans pattern, each persistable field must have a corresponding + * mutator method.
  • + *
  • When using the Builder pattern, each persistable field must have a corresponding mutator + * method in the Builder class. The mutator methods must follow any of the below naming convention: *
      *
    • setXXX (e.g. {@code setFirstName})
    • *
    • withXXX (e.g. {@code withFirstName})
    • *
    • xxx (e.g. {@code firstName})
    • *
    *
  • - *
  • Fields that should not be persisted, must be annotated - * with @{@link Ignore} annotation.
  • - *
  • Complex objects may be present in the Embeddable class, as long as they - * have an annotation of @{@link Embedded} or @{@link Ignore}
  • - *
  • Persistable fields may have @{@link Property} annotation to map the field - * with a custom name as well as to specify if the property should be indexed. - *
  • - *
  • Embeddable objects must not have {@link Identifier}s, {@link Key}s or - * {@link ParentKey}s. Even if they contain these annotations, they are ignored. - *
  • + *
  • Fields that should not be persisted, must be annotated with @{@link Ignore} annotation.
  • + *
  • Complex objects may be present in the Embeddable class, as long as they have an annotation + * of @{@link Embedded} or @{@link Ignore}
  • + *
  • Persistable fields may have @{@link Property} annotation to map the field with a custom name + * as well as to specify if the property should be indexed.
  • + *
  • Embeddable objects must not have {@link Identifier}s, {@link Key}s or {@link ParentKey}s. + * Even if they contain these annotations, they are ignored.
  • *
* * @author Sai Pullabhotla @@ -84,5 +76,5 @@ @Retention(RUNTIME) @Target(TYPE) public @interface Embeddable { - // Just used for tagging a class as Embeddable + // Just used for tagging a class as Embeddable } diff --git a/src/main/java/com/jmethods/catatumbo/Embedded.java b/src/main/java/com/jmethods/catatumbo/Embedded.java index 0179658..eef6889 100644 --- a/src/main/java/com/jmethods/catatumbo/Embedded.java +++ b/src/main/java/com/jmethods/catatumbo/Embedded.java @@ -23,36 +23,33 @@ import java.lang.annotation.Target; /** - * Specifies a persistent property of an entity whose value is an instance of an - * embeddable class. The embeddable class must be annotated as - * {@link Embeddable}. + * Specifies a persistent property of an entity whose value is an instance of an embeddable class. + * The embeddable class must be annotated as {@link Embeddable}. * *

* Embedded objects in an entity can be stored using two strategies: *

*
    - *
  • EXPLODED - Each primitive field (processed recursively, - * if the embedded object contains nested embedded objects) in the embedded - * object is created as a separate property in the Cloud Datastore.
  • - *
  • IMPLODED - The embedded object and any nested embedded - * objects will be stored as a single property in the Cloud Datastore. The type - * of the property in the Datastore will be Embedded Entity.
  • + *
  • EXPLODED - Each primitive field (processed recursively, if the embedded + * object contains nested embedded objects) in the embedded object is created as a separate property + * in the Cloud Datastore.
  • + *
  • IMPLODED - The embedded object and any nested embedded objects will be + * stored as a single property in the Cloud Datastore. The type of the property in the Datastore + * will be Embedded Entity.
  • *
* *

- * By default, Embedded objects are stored using the EXPLODED strategy. To - * change the strategy to IMPLODED, simply add the {@link Imploded} annotation - * to the Embedded field. You may also annotate the field explicitly with the - * {@link Exploded} annotation. + * By default, Embedded objects are stored using the EXPLODED strategy. To change the strategy to + * IMPLODED, simply add the {@link Imploded} annotation to the Embedded field. You may also annotate + * the field explicitly with the {@link Exploded} annotation. *

* *

- * The class that has an Embedded field, must have a corresponding accessor - * methods. For example, if homeAddress is of type - * Address and is a field defined in Person class, - * then the Person class must have - * setHomeAddress(Address homeAddress) and - * Address getHomeAddress() methods. + * The class that has an Embedded field, must have a corresponding accessor methods. For example, if + * homeAddress is of type Address and is a field defined in + * Person class, then the Person class must have + * setHomeAddress(Address homeAddress) and Address getHomeAddress() + * methods. *

* * @author Sai Pullabhotla @@ -62,30 +59,28 @@ @Target(FIELD) public @interface Embedded { - /** - * Property name to use for this embedded in the Cloud Datastore. This is - * only used if the embedded object is stored using the {@link Imploded} - * strategy. - * - * @return the property name. - */ - String name() default ""; + /** + * Property name to use for this embedded in the Cloud Datastore. This is only used if the + * embedded object is stored using the {@link Imploded} strategy. + * + * @return the property name. + */ + String name() default ""; - /** - * Whether or not to index this property. This is only used if the embedded - * object is stored using the {@link Imploded} strategy. - * - * @return Whether or not to index this property. - */ - boolean indexed() default true; + /** + * Whether or not to index this property. This is only used if the embedded object is stored using + * the {@link Imploded} strategy. + * + * @return Whether or not to index this property. + */ + boolean indexed() default true; - /** - * Whether or not the corresponding field is optional. For fields declared - * as optional, the property will be omitted when the field has a - * null value. This is only valid/used if the embedded object - * is stored using {@link Imploded} strategy. - * - * @return whether or not the corresponding embedded field is optional. - */ - boolean optional() default false; + /** + * Whether or not the corresponding field is optional. For fields declared as optional, the + * property will be omitted when the field has a null value. This is only valid/used + * if the embedded object is stored using {@link Imploded} strategy. + * + * @return whether or not the corresponding embedded field is optional. + */ + boolean optional() default false; } diff --git a/src/main/java/com/jmethods/catatumbo/Entity.java b/src/main/java/com/jmethods/catatumbo/Entity.java index e29ecd3..294bd36 100644 --- a/src/main/java/com/jmethods/catatumbo/Entity.java +++ b/src/main/java/com/jmethods/catatumbo/Entity.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,63 +22,55 @@ import java.lang.annotation.Target; /** - * Specifies that a class is an entity. Classes with this annotation can be - * managed by the {@link EntityManager} to save objects to the Cloud Datastore - * and load objects from the Cloud Datastore. + * Specifies that a class is an entity. Classes with this annotation can be managed by the + * {@link EntityManager} to save objects to the Cloud Datastore and load objects from the Cloud + * Datastore. * *

- * Entity Classes and other persistence classes ({@link Embeddable}, - * {@link MappedSuperClass}) may either use classic Java Beans pattern or the - * Builder pattern. Builder Pattern is recommended when persistence objects that - * need to be immutable. + * Entity Classes and other persistence classes ({@link Embeddable}, {@link MappedSuperClass}) may + * either use classic Java Beans pattern or the Builder pattern. Builder Pattern is recommended when + * persistence objects that need to be immutable. *

* *

* Classes annotated with this annotation must adhere to the following rules: *

*
    - *
  • If using the classic Java Beans pattern, the class must have a public - * no-arg (zero arguments) constructor. Absence of a public no-arg constructor - * assumes that the class is using the Builder pattern.
  • - *
  • For Builder pattern, the class must have a public static - * {@code newBuilder} or {@code builder} method that returns an instance of - * corresponding Builder class.
  • - *
  • When using the Builder pattern, the Builder class must have a public - * {@code build} method.
  • - *
  • Must have exactly one field annotated with @{@link Identifier} - * annotation.
  • - *
  • The type of identifier field must be a supported type as defined in the - * {@link Identifier} documentation.
  • - *
  • May contain zero or more fields. All fields that need to be persisted to - * the Cloud Datastore must have public accessor methods.
  • - *
  • For classic Java Beans pattern, all persistable fields must also have - * their corresponding mutator methods.
  • - *
  • For the Builder pattern, all persistable fields must have their - * corresponding mutator methods in the Builder class. The mutator methods may - * use any of the below naming conventions: + *
  • If using the classic Java Beans pattern, the class must have a public no-arg (zero arguments) + * constructor. Absence of a public no-arg constructor assumes that the class is using the Builder + * pattern.
  • + *
  • For Builder pattern, the class must have a public static {@code newBuilder} or + * {@code builder} method that returns an instance of corresponding Builder class.
  • + *
  • When using the Builder pattern, the Builder class must have a public {@code build} + * method.
  • + *
  • Must have exactly one field annotated with @{@link Identifier} annotation.
  • + *
  • The type of identifier field must be a supported type as defined in the {@link Identifier} + * documentation.
  • + *
  • May contain zero or more fields. All fields that need to be persisted to the Cloud Datastore + * must have public accessor methods.
  • + *
  • For classic Java Beans pattern, all persistable fields must also have their corresponding + * mutator methods.
  • + *
  • For the Builder pattern, all persistable fields must have their corresponding mutator methods + * in the Builder class. The mutator methods may use any of the below naming conventions: *
      *
    • setXXX (e.g. {@code setFirstName})
    • *
    • withXXX (e.g. {@code withFirstName})
    • *
    • xxx (e.g. {@code firstName})
    • *
    *
  • - *
  • If a field is to be skipped by the EntityManager, it needs to have @ - * {@link Ignore} annotation.
  • - *
  • May have no more than one field with @{@link Key} annotation which will - * hold the full key to the entity.
  • - *
  • Field annotated with @{@link Key} must have a data type of - * {@link DatastoreKey} .
  • - *
  • May have no more than one field with @{@link ParentKey} annotation which - * will hold the full key to the parent entity.
  • - *
  • Field annotated with @{@link ParentKey} must have a data type of - * {@link DatastoreKey}.
  • - *
  • May have zero or more embedded objects with an annotation - * of @{@link Embedded}. - *
  • All other fields can be any of the types for which a {@link Mapper} - * exists. The framework provides Mappers for various commonly used types. - * CustomMappers can be specified using - * {@link MapperFactory#setDefaultMapper(java.lang.reflect.Type, Mapper)} or - * {@link PropertyMapper} annotation.
  • + *
  • If a field is to be skipped by the EntityManager, it needs to have @ {@link Ignore} + * annotation.
  • + *
  • May have no more than one field with @{@link Key} annotation which will hold the full key to + * the entity.
  • + *
  • Field annotated with @{@link Key} must have a data type of {@link DatastoreKey} .
  • + *
  • May have no more than one field with @{@link ParentKey} annotation which will hold the full + * key to the parent entity.
  • + *
  • Field annotated with @{@link ParentKey} must have a data type of {@link DatastoreKey}.
  • + *
  • May have zero or more embedded objects with an annotation of @{@link Embedded}. + *
  • All other fields can be any of the types for which a {@link Mapper} exists. The framework + * provides Mappers for various commonly used types. CustomMappers can be specified using + * {@link MapperFactory#setDefaultMapper(java.lang.reflect.Type, Mapper)} or {@link PropertyMapper} + * annotation.
  • *
* * @author Sai Pullabhotla @@ -86,12 +79,12 @@ @Target(ElementType.TYPE) public @interface Entity { - /** - * Specifies the entity kind (equivalent to table name). If not specified, - * the kind defaults to unqualified name of the entity class. - * - * @return the entity kind - */ - String kind() default ""; + /** + * Specifies the entity kind (equivalent to table name). If not specified, the kind defaults to + * unqualified name of the entity class. + * + * @return the entity kind + */ + String kind() default ""; } diff --git a/src/main/java/com/jmethods/catatumbo/EntityAlreadyExistsException.java b/src/main/java/com/jmethods/catatumbo/EntityAlreadyExistsException.java index 40ca328..08dd763 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityAlreadyExistsException.java +++ b/src/main/java/com/jmethods/catatumbo/EntityAlreadyExistsException.java @@ -13,64 +13,61 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; /** - * Exception thrown by EntityManager to indicate another entity with the same - * Key already exists. This exception may be thrown from any of the variations - * of INSERT methods of {@link EntityManager}, {@link DatastoreTransaction} and - * {@link DatastoreBatch}. + * Exception thrown by EntityManager to indicate another entity with the same Key already exists. + * This exception may be thrown from any of the variations of INSERT methods of + * {@link EntityManager}, {@link DatastoreTransaction} and {@link DatastoreBatch}. * * @author Sai Pullabhotla */ public class EntityAlreadyExistsException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -2594975589977183143L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -2594975589977183143L; - /** - * Creates a new instance of {@code EntityAlreadyExistsException} without - * detail message. - */ - public EntityAlreadyExistsException() { - super(); - } + /** + * Creates a new instance of {@code EntityAlreadyExistsException} without detail message. + */ + public EntityAlreadyExistsException() { + super(); + } - /** - * Constructs an instance of {@code EntityAlreadyExistsException} with the - * specified detail message. - * - * @param msg - * the detail message. - */ - public EntityAlreadyExistsException(String msg) { - super(msg); - } + /** + * Constructs an instance of {@code EntityAlreadyExistsException} with the specified detail + * message. + * + * @param msg + * the detail message. + */ + public EntityAlreadyExistsException(String msg) { + super(msg); + } - /** - * Creates an instance of {@code EntityAlreadyExistsException} with the - * given message and cause. - * - * @param message - * the message - * @param cause - * the cause - */ - public EntityAlreadyExistsException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates an instance of {@code EntityAlreadyExistsException} with the given message and cause. + * + * @param message + * the message + * @param cause + * the cause + */ + public EntityAlreadyExistsException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of {@code EntityAlreadyExistsException} with the - * given cause. - * - * @param cause - * the cause. - */ - public EntityAlreadyExistsException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of {@code EntityAlreadyExistsException} with the given cause. + * + * @param cause + * the cause. + */ + public EntityAlreadyExistsException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/EntityListener.java b/src/main/java/com/jmethods/catatumbo/EntityListener.java index c13c593..ec591b6 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityListener.java +++ b/src/main/java/com/jmethods/catatumbo/EntityListener.java @@ -16,24 +16,22 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Specifies that a class is an EntityListener. Classes marked with this - * annotation should implement one or more callback methods for processing - * entity lifecycle events. Each callback method must be of the form - * public void methodName(Object entity). The parameter type can be - * more specific type than Object, as needed. + * Specifies that a class is an EntityListener. Classes marked with this annotation should implement + * one or more callback methods for processing entity lifecycle events. Each callback method must be + * of the form public void methodName(Object entity). The parameter type can be more + * specific type than Object, as needed. * *

- * EntityListeners are registered with {@link Entity} classes and/or - * {@link MappedSuperClass} classes using the {@link EntityListeners} - * annotation. For each lifecycle event of an entity, the callback methods of - * the registered listeners will be invoked. + * EntityListeners are registered with {@link Entity} classes and/or {@link MappedSuperClass} + * classes using the {@link EntityListeners} annotation. For each lifecycle event of an entity, the + * callback methods of the registered listeners will be invoked. *

* *

@@ -58,17 +56,13 @@ * *

    *
  • Must have a default (no-arg) constructor
  • - *
  • Each callback method must be public, must not be static, abstract or - * final.
  • - *
  • The callback method must be of the form - * public void methodName(Object). The Object argument is the - * entity instance for which the callback method is invoked. The type may be + *
  • Each callback method must be public, must not be static, abstract or final.
  • + *
  • The callback method must be of the form public void methodName(Object). The + * Object argument is the entity instance for which the callback method is invoked. The type may be * more specific type than Object.
  • - *
  • At most one method can exist for a given type of callback (e.g. - * PostUpdate)
  • - *
  • A single method may handle more than one type of callback (e.g. A method - * can have both {@link PreInsert}, {@link PreUpdate} and {@link PreUpsert} - * annotations.
  • + *
  • At most one method can exist for a given type of callback (e.g. PostUpdate)
  • + *
  • A single method may handle more than one type of callback (e.g. A method can have both + * {@link PreInsert}, {@link PreUpdate} and {@link PreUpsert} annotations.
  • *
* * @author Sai Pullabhotla @@ -78,5 +72,5 @@ @Retention(RUNTIME) @Target(TYPE) public @interface EntityListener { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/EntityListeners.java b/src/main/java/com/jmethods/catatumbo/EntityListeners.java index 21f4d48..7206b24 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityListeners.java +++ b/src/main/java/com/jmethods/catatumbo/EntityListeners.java @@ -16,54 +16,48 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Specifies the callback listener classes to be used for an entity. This - * annotation may be applied to: + * Specifies the callback listener classes to be used for an entity. This annotation may be applied + * to: *
    *
  • Entity classes (classes that have an annotation of {@link Entity}).
  • - *
  • Mapped super classes (classes that have an annotation of - * {@link MappedSuperClass}).
  • + *
  • Mapped super classes (classes that have an annotation of {@link MappedSuperClass}).
  • *
* *

- * The listeners will be invoked in the order they are defined. The order of - * execution is as follows: + * The listeners will be invoked in the order they are defined. The order of execution is as + * follows: *

*
    - *
  • Default Listeners - Default listeners are - * {@link EntityListener}s that are registered with the entity manager using - * {@link EntityManager#setDefaultListeners(Class...)}. Default listeners are - * invoked for all types of entities that are managed by the + *
  • Default Listeners - Default listeners are {@link EntityListener}s that are + * registered with the entity manager using {@link EntityManager#setDefaultListeners(Class...)}. + * Default listeners are invoked for all types of entities that are managed by the * {@link EntityManager}.
  • - *
  • External Listeners - External listeners are attached to - * an {@link Entity} or {@link MappedSuperClass} using the - * {@link EntityListeners} annotation. Super class listeners are executed first, - * followed by subclass' listeners.
  • - *
  • Internal Listeners - Internal listeners are callback - * methods defined within the {@link Entity} or {@link MappedSuperClass}. The - * signature of these methods differs slightly from the signature of methods in - * the {@link EntityListener}. The signature should be of the form - * public void methodName(). Internal listeners defined in the - * super class are executed first and then the subclass listeners.
  • + *
  • External Listeners - External listeners are attached to an {@link Entity} or + * {@link MappedSuperClass} using the {@link EntityListeners} annotation. Super class listeners are + * executed first, followed by subclass' listeners.
  • + *
  • Internal Listeners - Internal listeners are callback methods defined within + * the {@link Entity} or {@link MappedSuperClass}. The signature of these methods differs slightly + * from the signature of methods in the {@link EntityListener}. The signature should be of the form + * public void methodName(). Internal listeners defined in the super class are executed + * first and then the subclass listeners.
  • *
* *

- * It is possible to exclude the execution of Default Listeners and listeners - * defined in the super classes (both external and internal) using the - * annotations {@link ExcludeDefaultListeners} and + * It is possible to exclude the execution of Default Listeners and listeners defined in the super + * classes (both external and internal) using the annotations {@link ExcludeDefaultListeners} and * {@link ExcludeSuperclassListeners} annotations, respectively. *

* *

- * Callback methods may throw RuntimeExceptions. All RuntimeExceptions will be - * re-thrown as {@link EntityManagerException} with the original exception set - * as the cause. + * Callback methods may throw RuntimeExceptions. All RuntimeExceptions will be re-thrown as + * {@link EntityManagerException} with the original exception set as the cause. *

* * @author Sai Pullabhotla @@ -73,11 +67,11 @@ @Target(TYPE) public @interface EntityListeners { - /** - * The callback listener classes. - * - * @return the callback listener classes. - */ - Class[] value(); + /** + * The callback listener classes. + * + * @return the callback listener classes. + */ + Class[] value(); } diff --git a/src/main/java/com/jmethods/catatumbo/EntityManager.java b/src/main/java/com/jmethods/catatumbo/EntityManager.java index 923b10c..f1f1ffb 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityManager.java +++ b/src/main/java/com/jmethods/catatumbo/EntityManager.java @@ -19,129 +19,120 @@ import java.util.List; /** - * Manages mapping and persistence of entities. EntityManager objects are - * created using the {@link EntityManagerFactory}. + * Manages mapping and persistence of entities. EntityManager objects are created using the + * {@link EntityManagerFactory}. * * @author Sai Pullabhotla * */ public interface EntityManager extends DatastoreAccess { - /** - * Deletes all entities of given Kind. - * - * @param entityClass - * the entity class - The entity Kind will be determined from - * this class. - * @return the number of entities that were deleted - * @throws EntityManagerException - * if any error occurs while deleting. - */ - long deleteAll(Class entityClass); + /** + * Deletes all entities of given Kind. + * + * @param entityClass + * the entity class - The entity Kind will be determined from this class. + * @return the number of entities that were deleted + * @throws EntityManagerException + * if any error occurs while deleting. + */ + long deleteAll(Class entityClass); - /** - * Deletes all entities of given Kind. - * - * @param kind - * the entity Kind. - * @return the number of entities that were deleted - * @throws EntityManagerException - * if any error occurs while deleting. - */ - long deleteAll(String kind); + /** + * Deletes all entities of given Kind. + * + * @param kind + * the entity Kind. + * @return the number of entities that were deleted + * @throws EntityManagerException + * if any error occurs while deleting. + */ + long deleteAll(String kind); - /** - * Returns a new Transaction that can be used to perform a set of - * operations. - * - * @return a new Transaction that can be used to perform a set of - * operations. - */ - DatastoreTransaction newTransaction(); + /** + * Returns a new Transaction that can be used to perform a set of operations. + * + * @return a new Transaction that can be used to perform a set of operations. + */ + DatastoreTransaction newTransaction(); - /** - * Creates and returns a new {@link DatastoreBatch} that can be used for - * processing multiple write operations in one request. - * - * @return a new DatastoreBatch for processing multiple write - * operations in one request. - */ - DatastoreBatch newBatch(); + /** + * Creates and returns a new {@link DatastoreBatch} that can be used for processing multiple write + * operations in one request. + * + * @return a new DatastoreBatch for processing multiple write operations in one + * request. + */ + DatastoreBatch newBatch(); - /** - * Runs the given {@link TransactionalTask} in a new transaction. The - * {@link TransactionalTask#execute(DatastoreTransaction)} will receive a - * reference to the newly created {@link DatastoreTransaction} to perform - * reads/writes from/to the Cloud Datastore. When the - * {@link TransactionalTask} finishes, the transaction is committed. If any - * error occurs during the execution of the {@link TransactionalTask}, the - * transaction will be rolled back. - * - * @param task - * the task (or call back) to execute - * @return the return value from the execution of - * {@link TransactionalTask#execute(DatastoreTransaction)}. - * - */ - T executeInTransaction(TransactionalTask task); + /** + * Runs the given {@link TransactionalTask} in a new transaction. The + * {@link TransactionalTask#execute(DatastoreTransaction)} will receive a reference to the newly + * created {@link DatastoreTransaction} to perform reads/writes from/to the Cloud Datastore. When + * the {@link TransactionalTask} finishes, the transaction is committed. If any error occurs + * during the execution of the {@link TransactionalTask}, the transaction will be rolled back. + * + * @param task + * the task (or call back) to execute + * @return the return value from the execution of + * {@link TransactionalTask#execute(DatastoreTransaction)}. + * + */ + T executeInTransaction(TransactionalTask task); - /** - * Registers the given entity lifecycle listeners with this entity manager. - * - * @param classes - * the classes that should receive entity lifecycle events. - * Lifecycle callbacks are executed for all types of entities - * that are managed by this EntityManager. - */ - void setDefaultListeners(Class... classes); + /** + * Registers the given entity lifecycle listeners with this entity manager. + * + * @param classes + * the classes that should receive entity lifecycle events. Lifecycle callbacks are + * executed for all types of entities that are managed by this EntityManager. + */ + void setDefaultListeners(Class... classes); - /** - * Returns the {@link DatastoreMetadata} object that can be used to retrieve - * metadata information. - * - * @return the {@link DatastoreMetadata} object that can be used to retrieve - * metadata information. - */ - DatastoreMetadata getDatastoreMetadata(); + /** + * Returns the {@link DatastoreMetadata} object that can be used to retrieve metadata information. + * + * @return the {@link DatastoreMetadata} object that can be used to retrieve metadata information. + */ + DatastoreMetadata getDatastoreMetadata(); - /** - * Returns the {@link DatastoreStats} object that can be used to retrieve - * various statistics on the data stored in the Datastore. - * - * @return the {@link DatastoreStats} object that can be used to retrieve - * various statistics on the data stored in the Datastore. - */ - DatastoreStats getDatastoreStats(); + /** + * Returns the {@link DatastoreStats} object that can be used to retrieve various statistics on + * the data stored in the Datastore. + * + * @return the {@link DatastoreStats} object that can be used to retrieve various statistics on + * the data stored in the Datastore. + */ + DatastoreStats getDatastoreStats(); - /** - * Allocates IDs for the given entities and returns the allocated IDs. Each - * entity in the list must have a its identifier of type numeric - * (long/Long). - * - * @param entities - * the entities - * @return a list of {@link DatastoreKey}s. - * @throws IllegalArgumentException - * if any of the entities in the list do not have a numeric ID - * type or a valid ID is already set. - * @throws EntityManagerException - * if any error occurs during key allocation - */ - List allocateId(List entities); + /** + * Allocates IDs for the given entities and returns the allocated IDs. Each entity in the list + * must have a its identifier of type numeric (long/Long). + * + * @param entities + * the entities + * @return a list of {@link DatastoreKey}s. + * @throws IllegalArgumentException + * if any of the entities in the list do not have a numeric ID type or a valid ID is + * already set. + * @throws EntityManagerException + * if any error occurs during key allocation + */ + List allocateId(List entities); - /** - * Allocates ID for the given entity and returns the allocated ID. The - * entity must have its identifier of type numeric (long/Long). - * - * @param entity - * the the entity. - * @return the allocated ID {@link DatastoreKey}. - * @throws IllegalArgumentException - * if the ID type of the entity is not numeric, or if the entity - * has a valid ID (non-null and non-zero). - * @throws EntityManagerException - * if any error occurs during ID allocation - */ - DatastoreKey allocateId(Object entity); + /** + * Allocates ID for the given entity and returns the allocated ID. The entity must have its + * identifier of type numeric (long/Long). + * + * @param entity + * the the entity. + * @return the allocated ID {@link DatastoreKey}. + * @throws IllegalArgumentException + * if the ID type of the entity is not numeric, or if the entity has a valid ID + * (non-null and non-zero). + * @throws EntityManagerException + * if any error occurs during ID allocation + */ + DatastoreKey allocateId(Object entity); } diff --git a/src/main/java/com/jmethods/catatumbo/EntityManagerException.java b/src/main/java/com/jmethods/catatumbo/EntityManagerException.java index a45ac0a..14752da 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityManagerException.java +++ b/src/main/java/com/jmethods/catatumbo/EntityManagerException.java @@ -13,62 +13,59 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; /** - * Exception thrown by EntityManager when mapping objects to/from the Cloud - * Datastore. + * Exception thrown by EntityManager when mapping objects to/from the Cloud Datastore. * * @author Sai Pullabhotla */ public class EntityManagerException extends RuntimeException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -4427708611101283783L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -4427708611101283783L; - /** - * Creates a new instance of EntityManagerException without - * detail message. - */ - public EntityManagerException() { - super(); - } + /** + * Creates a new instance of EntityManagerException without detail message. + */ + public EntityManagerException() { + super(); + } - /** - * Constructs an instance of EntityManagerException with the - * specified detail message. - * - * @param msg - * the detail message. - */ - public EntityManagerException(String msg) { - super(msg); - } + /** + * Constructs an instance of EntityManagerException with the specified detail + * message. + * + * @param msg + * the detail message. + */ + public EntityManagerException(String msg) { + super(msg); + } - /** - * Creates an instance of EntityManagerException with the given - * message and cause. - * - * @param message - * the message - * @param cause - * the cause - */ - public EntityManagerException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates an instance of EntityManagerException with the given message and cause. + * + * @param message + * the message + * @param cause + * the cause + */ + public EntityManagerException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of EntityManagerException with the - * given cause. - * - * @param cause - * the cause. - */ - public EntityManagerException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of EntityManagerException with the given cause. + * + * @param cause + * the cause. + */ + public EntityManagerException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java b/src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java index 85b6f5f..be6a9bc 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java +++ b/src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java @@ -38,289 +38,269 @@ */ public class EntityManagerFactory { - /** - * Singleton instance - */ - private static final EntityManagerFactory INSTANCE = new EntityManagerFactory(); + /** + * Singleton instance + */ + private static final EntityManagerFactory INSTANCE = new EntityManagerFactory(); - /** - * Returns the singleton instance of EntityManagerFactory. - * - * @return the instance the singleton instance. - */ - public static EntityManagerFactory getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of EntityManagerFactory. + * + * @return the instance the singleton instance. + */ + public static EntityManagerFactory getInstance() { + return INSTANCE; + } - /** - * Creates and returns a new {@link EntityManager} using the default - * options. - * - * @return a new {@link EntityManager} using the default options. - */ - public EntityManager createDefaultEntityManager() { - return createDefaultEntityManager(null); - } + /** + * Creates and returns a new {@link EntityManager} using the default options. + * + * @return a new {@link EntityManager} using the default options. + */ + public EntityManager createDefaultEntityManager() { + return createDefaultEntityManager(null); + } - /** - * Creates and returns a new {@link EntityManager} using the default - * options. - * - * @param namespace - * the namespace to work with (for multitenancy) - * - * @return a new {@link EntityManager} using the default options. - */ - public EntityManager createDefaultEntityManager(String namespace) { - ConnectionParameters parameters = new ConnectionParameters(); - parameters.setNamespace(namespace); - return createEntityManager(parameters); - } + /** + * Creates and returns a new {@link EntityManager} using the default options. + * + * @param namespace + * the namespace to work with (for multitenancy) + * + * @return a new {@link EntityManager} using the default options. + */ + public EntityManager createDefaultEntityManager(String namespace) { + ConnectionParameters parameters = new ConnectionParameters(); + parameters.setNamespace(namespace); + return createEntityManager(parameters); + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsFile - * the JSON formatted credentials file for the target Cloud - * project. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, String jsonCredentialsFile) { - return createEntityManager(projectId, jsonCredentialsFile, null); - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsFile + * the JSON formatted credentials file for the target Cloud project. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, String jsonCredentialsFile) { + return createEntityManager(projectId, jsonCredentialsFile, null); + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsFile - * the JSON formatted credentials file for the target Cloud - * project. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, File jsonCredentialsFile) { - return createEntityManager(projectId, jsonCredentialsFile, null); - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsFile + * the JSON formatted credentials file for the target Cloud project. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, File jsonCredentialsFile) { + return createEntityManager(projectId, jsonCredentialsFile, null); + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsStream - * the JSON formatted credentials for the target Cloud project. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, InputStream jsonCredentialsStream) { - return createEntityManager(projectId, jsonCredentialsStream, null); - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsStream + * the JSON formatted credentials for the target Cloud project. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, InputStream jsonCredentialsStream) { + return createEntityManager(projectId, jsonCredentialsStream, null); + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsFile - * the JSON formatted credentials file for the target Cloud - * project. - * @param namespace - * the namespace (for multi-tenant datastore) to use. If - * null, default namespace is used. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, String jsonCredentialsFile, String namespace) { - return createEntityManager(projectId, new File(jsonCredentialsFile), namespace); - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsFile + * the JSON formatted credentials file for the target Cloud project. + * @param namespace + * the namespace (for multi-tenant datastore) to use. If null, default + * namespace is used. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, String jsonCredentialsFile, + String namespace) { + return createEntityManager(projectId, new File(jsonCredentialsFile), namespace); + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsFile - * the JSON formatted credentials file for the target Cloud - * project. - * @param namespace - * the namespace (for multi-tenant datastore) to use. If - * null, default namespace is used. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, File jsonCredentialsFile, String namespace) { - try { - return createEntityManager(projectId, new FileInputStream(jsonCredentialsFile), namespace); - } catch (Exception exp) { - throw new EntityManagerFactoryException(exp); - } - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsFile + * the JSON formatted credentials file for the target Cloud project. + * @param namespace + * the namespace (for multi-tenant datastore) to use. If null, default + * namespace is used. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, File jsonCredentialsFile, + String namespace) { + try { + return createEntityManager(projectId, new FileInputStream(jsonCredentialsFile), namespace); + } catch (Exception exp) { + throw new EntityManagerFactoryException(exp); + } + } - /** - * Creates and return a new {@link EntityManager} using the provided JSON - * formatted credentials. - * - * @param projectId - * the project ID - * - * @param jsonCredentialsStream - * the JSON formatted credentials for the target Cloud project. - * @param namespace - * the namespace (for multi-tenant datastore) to use. If - * null, default namespace is used. - * @return a new {@link EntityManager} - */ - public EntityManager createEntityManager(String projectId, InputStream jsonCredentialsStream, String namespace) { - ConnectionParameters parameters = new ConnectionParameters(); - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - parameters.setJsonCredentialsStream(jsonCredentialsStream); - return createEntityManager(parameters); - } + /** + * Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. + * + * @param projectId + * the project ID + * + * @param jsonCredentialsStream + * the JSON formatted credentials for the target Cloud project. + * @param namespace + * the namespace (for multi-tenant datastore) to use. If null, default + * namespace is used. + * @return a new {@link EntityManager} + */ + public EntityManager createEntityManager(String projectId, InputStream jsonCredentialsStream, + String namespace) { + ConnectionParameters parameters = new ConnectionParameters(); + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + parameters.setJsonCredentialsStream(jsonCredentialsStream); + return createEntityManager(parameters); + } - /** - * Creates and returns an {@link EntityManager} that allows working with the - * local Datastore (a.k.a Datastore Emulator). The underlying API will - * attempt to use the default project ID, if one exists. - * - * @param serviceURL - * Service URL for the Datastore Emulator. (e.g. - * http://localhost:9999) - * @return an {@link EntityManager} that allows working with the local - * Datastore (a.k.a Datastore Emulator). - */ - public EntityManager createLocalEntityManager(String serviceURL) { - return createLocalEntityManager(serviceURL, null, null); - } + /** + * Creates and returns an {@link EntityManager} using the specified connection parameters. + * + * @param parameters + * the connection parameters + * @return a new {@link EntityManager} created using the specified connection parameters. + * @throws EntityManagerException + * if any error occurs while creating the EntityManager. + */ + public EntityManager createEntityManager(ConnectionParameters parameters) { + try { + DatastoreOptions.Builder datastoreOptionsBuilder = DatastoreOptions.newBuilder(); + datastoreOptionsBuilder.setHost(parameters.getServiceURL()); + datastoreOptionsBuilder.setTransportOptions(getHttpTransportOptions(parameters)); + String projectId = parameters.getProjectId(); + if (!Utility.isNullOrEmpty(projectId)) { + datastoreOptionsBuilder.setProjectId(projectId); + } + String namespace = parameters.getNamespace(); + if (namespace != null) { + datastoreOptionsBuilder.setNamespace(namespace); + } + datastoreOptionsBuilder.setCredentials(getCredentials(parameters)); + Datastore datastore = datastoreOptionsBuilder.build().getService(); + return new DefaultEntityManager(datastore); + } catch (Exception exp) { + throw new EntityManagerFactoryException(exp); + } + } - /** - * Creates and returns an {@link EntityManager} that allows working with the - * local Datastore (a.k.a Datastore Emulator). Specified project ID will be - * used. - * - * @param serviceURL - * Service URL for the Datastore Emulator. (e.g. - * http://localhost:9999) - * @param projectId - * the project ID. The specified project need not exist in Google - * Cloud. - * @return an {@link EntityManager} that allows working with the local - * Datastore (a.k.a Datastore Emulator). - */ - public EntityManager createLocalEntityManager(String serviceURL, String projectId) { - return createLocalEntityManager(serviceURL, projectId, null); - } + /** + * Creates and returns an {@link EntityManager} that allows working with the local Datastore + * (a.k.a Datastore Emulator). The underlying API will attempt to use the default project ID, if + * one exists. + * + * @param serviceURL + * Service URL for the Datastore Emulator. (e.g. http://localhost:9999) + * @return an {@link EntityManager} that allows working with the local Datastore (a.k.a Datastore + * Emulator). + */ + public EntityManager createLocalEntityManager(String serviceURL) { + return createLocalEntityManager(serviceURL, null, null); + } - /** - * Creates and returns an {@link EntityManager} that allows working with the - * local Datastore (a.k.a Datastore Emulator). Specified project ID will be - * used. - * - * @param serviceURL - * Service URL for the Datastore Emulator. (e.g. - * http://localhost:9999) - * @param projectId - * the project ID. The specified project need not exist in Google - * Cloud. If null, default project ID is used, if it - * can be determined. - * @param namespace - * the namespace (for multi-tenant datastore) to use. - * @return an {@link EntityManager} that allows working with the local - * Datastore (a.k.a Datastore Emulator). If null, - * default namespace is used. - */ - public EntityManager createLocalEntityManager(String serviceURL, String projectId, String namespace) { - ConnectionParameters parameters = new ConnectionParameters(); - parameters.setServiceURL(serviceURL); - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - return createEntityManager(parameters); - } + /** + * Creates and returns an {@link EntityManager} that allows working with the local Datastore + * (a.k.a Datastore Emulator). Specified project ID will be used. + * + * @param serviceURL + * Service URL for the Datastore Emulator. (e.g. http://localhost:9999) + * @param projectId + * the project ID. The specified project need not exist in Google Cloud. + * @return an {@link EntityManager} that allows working with the local Datastore (a.k.a Datastore + * Emulator). + */ + public EntityManager createLocalEntityManager(String serviceURL, String projectId) { + return createLocalEntityManager(serviceURL, projectId, null); + } - /** - * Creates and returns an {@link EntityManager} using the specified - * connection parameters. - * - * @param parameters - * the connection parameters - * @return a new {@link EntityManager} created using the specified - * connection parameters. - * @throws EntityManagerException - * if any error occurs while creating the EntityManager. - */ - public EntityManager createEntityManager(ConnectionParameters parameters) { - try { - DatastoreOptions.Builder datastoreOptionsBuilder = DatastoreOptions.newBuilder(); - datastoreOptionsBuilder.setHost(parameters.getServiceURL()); - datastoreOptionsBuilder.setTransportOptions(getHttpTransportOptions(parameters)); - String projectId = parameters.getProjectId(); - if (!Utility.isNullOrEmpty(projectId)) { - datastoreOptionsBuilder.setProjectId(projectId); - } - String namespace = parameters.getNamespace(); - if (namespace != null) { - datastoreOptionsBuilder.setNamespace(namespace); - } - datastoreOptionsBuilder.setCredentials(getCredentials(parameters)); - Datastore datastore = datastoreOptionsBuilder.build().getService(); - return new DefaultEntityManager(datastore); - } catch (Exception exp) { - throw new EntityManagerFactoryException(exp); - } - } + /** + * Creates and returns an {@link EntityManager} that allows working with the local Datastore + * (a.k.a Datastore Emulator). Specified project ID will be used. + * + * @param serviceURL + * Service URL for the Datastore Emulator. (e.g. http://localhost:9999) + * @param projectId + * the project ID. The specified project need not exist in Google Cloud. If + * null, default project ID is used, if it can be determined. + * @param namespace + * the namespace (for multi-tenant datastore) to use. + * @return an {@link EntityManager} that allows working with the local Datastore (a.k.a Datastore + * Emulator). If null, default namespace is used. + */ + public EntityManager createLocalEntityManager(String serviceURL, String projectId, + String namespace) { + ConnectionParameters parameters = new ConnectionParameters(); + parameters.setServiceURL(serviceURL); + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + return createEntityManager(parameters); + } - /** - * Creates and returns the credentials from the given connection parameters. - * - * @param parameters - * the connection parameters - * @return the credentials for authenticating with the Datastore service. - * @throws IOException - * if any error occurs such as not able to read the credentials - * file. - */ - private static Credentials getCredentials(ConnectionParameters parameters) throws IOException { - if (parameters.isEmulator()) { - return NoCredentials.getInstance(); - } - InputStream jsonCredentialsStream = parameters.getJsonCredentialsStream(); - if (jsonCredentialsStream != null) { - return ServiceAccountCredentials.fromStream(jsonCredentialsStream); - } - File jsonCredentialsFile = parameters.getJsonCredentialsFile(); - if (jsonCredentialsFile != null) { - return ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialsFile)); - } - return ServiceAccountCredentials.getApplicationDefault(); - } + /** + * Creates and returns the credentials from the given connection parameters. + * + * @param parameters + * the connection parameters + * @return the credentials for authenticating with the Datastore service. + * @throws IOException + * if any error occurs such as not able to read the credentials file. + */ + private static Credentials getCredentials(ConnectionParameters parameters) throws IOException { + if (parameters.isEmulator()) { + return NoCredentials.getInstance(); + } + InputStream jsonCredentialsStream = parameters.getJsonCredentialsStream(); + if (jsonCredentialsStream != null) { + return ServiceAccountCredentials.fromStream(jsonCredentialsStream); + } + File jsonCredentialsFile = parameters.getJsonCredentialsFile(); + if (jsonCredentialsFile != null) { + return ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialsFile)); + } + return ServiceAccountCredentials.getApplicationDefault(); + } - /** - * Creates and returns HttpTransportOptions from the given connection - * parameters. - * - * @param parameters - * the connection parameters - * @return the HttpTransportOptions - */ - private static HttpTransportOptions getHttpTransportOptions(ConnectionParameters parameters) { - HttpTransportOptions.Builder httpOptionsBuilder = HttpTransportOptions.newBuilder(); - httpOptionsBuilder.setConnectTimeout(parameters.getConnectionTimeout()); - httpOptionsBuilder.setReadTimeout(parameters.getReadTimeout()); + /** + * Creates and returns HttpTransportOptions from the given connection parameters. + * + * @param parameters + * the connection parameters + * @return the HttpTransportOptions + */ + private static HttpTransportOptions getHttpTransportOptions(ConnectionParameters parameters) { + HttpTransportOptions.Builder httpOptionsBuilder = HttpTransportOptions.newBuilder(); + httpOptionsBuilder.setConnectTimeout(parameters.getConnectionTimeout()); + httpOptionsBuilder.setReadTimeout(parameters.getReadTimeout()); - HttpTransportFactory httpTransportFactory = parameters.getHttpTransportFactory(); - if (httpTransportFactory != null) { - httpOptionsBuilder.setHttpTransportFactory(httpTransportFactory); - } - return httpOptionsBuilder.build(); - } + HttpTransportFactory httpTransportFactory = parameters.getHttpTransportFactory(); + if (httpTransportFactory != null) { + httpOptionsBuilder.setHttpTransportFactory(httpTransportFactory); + } + return httpOptionsBuilder.build(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/EntityManagerFactoryException.java b/src/main/java/com/jmethods/catatumbo/EntityManagerFactoryException.java index 5aae5a0..64d03f5 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityManagerFactoryException.java +++ b/src/main/java/com/jmethods/catatumbo/EntityManagerFactoryException.java @@ -17,56 +17,56 @@ package com.jmethods.catatumbo; /** - * An exception thrown by {@link EntityManagerFactory} when it fails to create - * an {@link EntityManager}. + * An exception thrown by {@link EntityManagerFactory} when it fails to create an + * {@link EntityManager}. * * @author Sai Pullabhotla * */ public class EntityManagerFactoryException extends RuntimeException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 8903535956977463773L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 8903535956977463773L; - /** - * Creates a new instance of EntityManagerFactoryException. - */ - public EntityManagerFactoryException() { - super(); - } + /** + * Creates a new instance of EntityManagerFactoryException. + */ + public EntityManagerFactoryException() { + super(); + } - /** - * Creates a new instance of EntityManagerFactoryException. - * - * @param message - * the message - * @param cause - * the cause - */ - public EntityManagerFactoryException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of EntityManagerFactoryException. + * + * @param message + * the message + * @param cause + * the cause + */ + public EntityManagerFactoryException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of EntityManagerFactoryException. - * - * @param message - * the message - */ - public EntityManagerFactoryException(String message) { - super(message); - } + /** + * Creates a new instance of EntityManagerFactoryException. + * + * @param message + * the message + */ + public EntityManagerFactoryException(String message) { + super(message); + } - /** - * Creates a new instance of EntityManagerFactoryException. - * - * @param cause - * the cause - */ - public EntityManagerFactoryException(Throwable cause) { - super(cause.getMessage(), cause); - } + /** + * Creates a new instance of EntityManagerFactoryException. + * + * @param cause + * the cause + */ + public EntityManagerFactoryException(Throwable cause) { + super(cause.getMessage(), cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/EntityNotFoundException.java b/src/main/java/com/jmethods/catatumbo/EntityNotFoundException.java index c43f53e..574b24b 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityNotFoundException.java +++ b/src/main/java/com/jmethods/catatumbo/EntityNotFoundException.java @@ -13,64 +13,60 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; /** - * Exception thrown by EntityManager to indicate that an update operation failed - * because the entity with the specified key does not exist. This exception may - * be thrown from variations of UPDATE methods of {@link EntityManager}, - * {@link DatastoreTransaction} and {@link DatastoreBatch}. + * Exception thrown by EntityManager to indicate that an update operation failed because the entity + * with the specified key does not exist. This exception may be thrown from variations of UPDATE + * methods of {@link EntityManager}, {@link DatastoreTransaction} and {@link DatastoreBatch}. * * @author Sai Pullabhotla */ public class EntityNotFoundException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -2594975589977183143L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -2594975589977183143L; - /** - * Creates a new instance of {@code EntityNotFoundException} without detail - * message. - */ - public EntityNotFoundException() { - super(); - } + /** + * Creates a new instance of {@code EntityNotFoundException} without detail message. + */ + public EntityNotFoundException() { + super(); + } - /** - * Constructs an instance of {@code EntityNotFoundException} with the - * specified detail message. - * - * @param msg - * the detail message. - */ - public EntityNotFoundException(String msg) { - super(msg); - } + /** + * Constructs an instance of {@code EntityNotFoundException} with the specified detail message. + * + * @param msg + * the detail message. + */ + public EntityNotFoundException(String msg) { + super(msg); + } - /** - * Creates an instance of {@code EntityNotFoundException} with the given - * message and cause. - * - * @param message - * the message - * @param cause - * the cause - */ - public EntityNotFoundException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates an instance of {@code EntityNotFoundException} with the given message and cause. + * + * @param message + * the message + * @param cause + * the cause + */ + public EntityNotFoundException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of {@code EntityNotFoundException} with the given - * cause. - * - * @param cause - * the cause. - */ - public EntityNotFoundException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of {@code EntityNotFoundException} with the given cause. + * + * @param cause + * the cause. + */ + public EntityNotFoundException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/EntityQueryRequest.java b/src/main/java/com/jmethods/catatumbo/EntityQueryRequest.java index 66b81ae..3945b95 100644 --- a/src/main/java/com/jmethods/catatumbo/EntityQueryRequest.java +++ b/src/main/java/com/jmethods/catatumbo/EntityQueryRequest.java @@ -24,14 +24,14 @@ */ public class EntityQueryRequest extends BaseQueryRequest { - /** - * Creates a new instance of EntityQueryRequest. - * - * @param query - * the GQL query string - */ - public EntityQueryRequest(String query) { - super(query); - } + /** + * Creates a new instance of EntityQueryRequest. + * + * @param query + * the GQL query string + */ + public EntityQueryRequest(String query) { + super(query); + } } diff --git a/src/main/java/com/jmethods/catatumbo/ExcludeDefaultListeners.java b/src/main/java/com/jmethods/catatumbo/ExcludeDefaultListeners.java index 15458ea..5da3db6 100644 --- a/src/main/java/com/jmethods/catatumbo/ExcludeDefaultListeners.java +++ b/src/main/java/com/jmethods/catatumbo/ExcludeDefaultListeners.java @@ -16,22 +16,20 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Specifies that any default listeners registered with the - * {@link EntityManager} should be excluded. This annotation can be specified on - * an {@link Entity} or a {@link MappedSuperClass}. + * Specifies that any default listeners registered with the {@link EntityManager} should be + * excluded. This annotation can be specified on an {@link Entity} or a {@link MappedSuperClass}. * *

- * If this annotation is defined on an {@link Entity}, default listeners are - * skipped for various life cycle events of that entity. If this annotation is - * defined on a {@link MappedSuperClass}, default listeners are skipped for all - * entities extending that {@link MappedSuperClass}. + * If this annotation is defined on an {@link Entity}, default listeners are skipped for various + * life cycle events of that entity. If this annotation is defined on a {@link MappedSuperClass}, + * default listeners are skipped for all entities extending that {@link MappedSuperClass}. *

* * @author Sai Pullabhotla @@ -40,5 +38,5 @@ @Retention(RUNTIME) @Target(TYPE) public @interface ExcludeDefaultListeners { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/ExcludeSuperclassListeners.java b/src/main/java/com/jmethods/catatumbo/ExcludeSuperclassListeners.java index 74bf630..1782024 100644 --- a/src/main/java/com/jmethods/catatumbo/ExcludeSuperclassListeners.java +++ b/src/main/java/com/jmethods/catatumbo/ExcludeSuperclassListeners.java @@ -16,16 +16,15 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Specifies that the execution of listeners defined in the super class should - * be excluded. This annotation can be specified on an {@link Entity} or - * {@link MappedSuperClass}. + * Specifies that the execution of listeners defined in the super class should be excluded. This + * annotation can be specified on an {@link Entity} or {@link MappedSuperClass}. * * @author Sai Pullabhotla * @@ -33,5 +32,5 @@ @Retention(RUNTIME) @Target(TYPE) public @interface ExcludeSuperclassListeners { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/Exploded.java b/src/main/java/com/jmethods/catatumbo/Exploded.java index 1244c42..ac2724f 100644 --- a/src/main/java/com/jmethods/catatumbo/Exploded.java +++ b/src/main/java/com/jmethods/catatumbo/Exploded.java @@ -16,20 +16,19 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Indicates that the {@link Embedded} object of an entity should be stored - * using the Exploded strategy. With Exploded strategy, the {@link Embedded} - * object, and nested embedded objects, if any, are exploded into separate - * properties when stored into the Datastore. This annotation can exist on any - * {@link Embedded} field of an {@link Entity} or {@link MappedSuperClass}. - * Annotating a nested Embedded field with this annotation will not have any - * effect as the storage strategy is enforced at the Entity level. + * Indicates that the {@link Embedded} object of an entity should be stored using the Exploded + * strategy. With Exploded strategy, the {@link Embedded} object, and nested embedded objects, if + * any, are exploded into separate properties when stored into the Datastore. This annotation can + * exist on any {@link Embedded} field of an {@link Entity} or {@link MappedSuperClass}. Annotating + * a nested Embedded field with this annotation will not have any effect as the storage strategy is + * enforced at the Entity level. * * @author Sai Pullabhotla * @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(FIELD) public @interface Exploded { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/GeoLocation.java b/src/main/java/com/jmethods/catatumbo/GeoLocation.java index 772bc1f..61cfe0d 100644 --- a/src/main/java/com/jmethods/catatumbo/GeoLocation.java +++ b/src/main/java/com/jmethods/catatumbo/GeoLocation.java @@ -20,107 +20,107 @@ import java.util.Objects; /** - * Geographical Location data type to store longitude and latitude information - * in a single property of Cloud Datastore. + * Geographical Location data type to store longitude and latitude information in a single property + * of Cloud Datastore. * * @author Sai Pullabhotla * */ public class GeoLocation implements Serializable { - /** - * Serial Version UID - */ - private static final long serialVersionUID = -7448392415206659989L; + /** + * Serial Version UID + */ + private static final long serialVersionUID = -7448392415206659989L; - /** - * Latitude - */ - private double latitude; + /** + * Latitude + */ + private double latitude; - /** - * Longitude - */ - private double longitude; + /** + * Longitude + */ + private double longitude; - /** - * Creates a new instance of GeoLocation. - */ - public GeoLocation() { - this(0.0, 0.0); - } + /** + * Creates a new instance of GeoLocation. + */ + public GeoLocation() { + this(0.0, 0.0); + } - /** - * Creates a new instance of GeoLocation. - * - * @param latitude - * the latitude - * @param longitude - * the longitude - */ - public GeoLocation(double latitude, double longitude) { - // Validate the values?? - this.latitude = latitude; - this.longitude = longitude; - } + /** + * Creates a new instance of GeoLocation. + * + * @param latitude + * the latitude + * @param longitude + * the longitude + */ + public GeoLocation(double latitude, double longitude) { + // Validate the values?? + this.latitude = latitude; + this.longitude = longitude; + } - /** - * Returns the latitude. - * - * @return the latitude - */ - public double getLatitude() { - return latitude; - } + /** + * Returns the latitude. + * + * @return the latitude + */ + public double getLatitude() { + return latitude; + } - /** - * Sets the latitude to the given value. - * - * @param latitude - * the latitude - */ - public void setLatitude(double latitude) { - this.latitude = latitude; - } + /** + * Sets the latitude to the given value. + * + * @param latitude + * the latitude + */ + public void setLatitude(double latitude) { + this.latitude = latitude; + } - /** - * Returns the longitude. - * - * @return the longitude - */ - public double getLongitude() { - return longitude; - } + /** + * Returns the longitude. + * + * @return the longitude + */ + public double getLongitude() { + return longitude; + } - /** - * Sets the longitude to the given value. - * - * @param longitude - * the longitude - */ - public void setLongitude(double longitude) { - this.longitude = longitude; - } + /** + * Sets the longitude to the given value. + * + * @param longitude + * the longitude + */ + public void setLongitude(double longitude) { + this.longitude = longitude; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof GeoLocation)) { - return false; - } - GeoLocation that = (GeoLocation) obj; - return this.latitude == that.latitude && this.longitude == that.longitude; - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof GeoLocation)) { + return false; + } + GeoLocation that = (GeoLocation) obj; + return this.latitude == that.latitude && this.longitude == that.longitude; + } - @Override - public int hashCode() { - return Objects.hash(latitude, longitude); - } + @Override + public int hashCode() { + return Objects.hash(latitude, longitude); + } - @Override - public String toString() { - return latitude + ", " + longitude; - } + @Override + public String toString() { + return latitude + ", " + longitude; + } } diff --git a/src/main/java/com/jmethods/catatumbo/Identifier.java b/src/main/java/com/jmethods/catatumbo/Identifier.java index b37e003..24f5249 100644 --- a/src/main/java/com/jmethods/catatumbo/Identifier.java +++ b/src/main/java/com/jmethods/catatumbo/Identifier.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,28 +22,26 @@ import java.lang.annotation.Target; /** - * Specifies the ID of an entity. Identifiers uniquely identify a given entity - * within the Cloud Datastore. Cloud Datastore supports Integer (64-bit) and - * String types for identifiers, therefore this annotation is only valid for the - * following field types: + * Specifies the ID of an entity. Identifiers uniquely identify a given entity within the Cloud + * Datastore. Cloud Datastore supports Integer (64-bit) and String types for identifiers, therefore + * this annotation is only valid for the following field types: *
    *
  • Primitive long (long)
  • *
  • Long Wrapper (java.lang.Long)
  • *
  • String (java.lang.String)
  • *
  • Any other type that satisfies the following criteria: *
      - *
    • Has a public getValue method with no parameters and a return - * type of long, Long or String
    • - *
    • Has a public constructor with a single parameter whose type is same as - * the return type of getValue method.
    • + *
    • Has a public getValue method with no parameters and a return type of long, Long + * or String
    • + *
    • Has a public constructor with a single parameter whose type is same as the return type of + * getValue method.
    • *
    *
  • *
* *

- * Note that Identifier fields cannot have a custom name in the Cloud Datastore. - * The Datastore names them wither Id or Name depending on the data type long or - * String. + * Note that Identifier fields cannot have a custom name in the Cloud Datastore. The Datastore names + * them wither Id or Name depending on the data type long or String. *

* * @author Sai Pullabhotla @@ -51,21 +50,19 @@ @Target(ElementType.FIELD) public @interface Identifier { - /** - * Specifies if identifiers should be generated automatically when inserting - * new entities into the Cloud Datastore. When autoGenerated is - * set to true - - *
    - *
  • If the data type is long or Long - the Identifier generation is - * delegated to the Cloud Datastore. In other words, the Cloud Datastore - * allocates the identifiers.
  • - *
  • If the data type is String - the framework generates the identifier - * using a random UUID.
  • - *
- * When autoGenerated is set to false, the - * application is responsible for managing the identifiers. - * - * @return whether or not to auto generate identifiers - */ - boolean autoGenerated() default true; + /** + * Specifies if identifiers should be generated automatically when inserting new entities into the + * Cloud Datastore. When autoGenerated is set to true - + *
    + *
  • If the data type is long or Long - the Identifier generation is delegated to the Cloud + * Datastore. In other words, the Cloud Datastore allocates the identifiers.
  • + *
  • If the data type is String - the framework generates the identifier using a random + * UUID.
  • + *
+ * When autoGenerated is set to false, the application is responsible + * for managing the identifiers. + * + * @return whether or not to auto generate identifiers + */ + boolean autoGenerated() default true; } diff --git a/src/main/java/com/jmethods/catatumbo/Ignore.java b/src/main/java/com/jmethods/catatumbo/Ignore.java index 2b42774..e4293a9 100644 --- a/src/main/java/com/jmethods/catatumbo/Ignore.java +++ b/src/main/java/com/jmethods/catatumbo/Ignore.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,13 +22,13 @@ import java.lang.annotation.Target; /** - * Specifies that an entity field should be ignored by the EntityManager when - * saving or loading the entities. + * Specifies that an entity field should be ignored by the EntityManager when saving or loading the + * entities. * * @author Sai Pullabhotla */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Ignore { - // Simple marker. + // Simple marker. } diff --git a/src/main/java/com/jmethods/catatumbo/Imploded.java b/src/main/java/com/jmethods/catatumbo/Imploded.java index 2f8489c..0001ebf 100644 --- a/src/main/java/com/jmethods/catatumbo/Imploded.java +++ b/src/main/java/com/jmethods/catatumbo/Imploded.java @@ -16,20 +16,19 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Specifies that the {@link Embedded} object of an {@link Entity} should be - * stored using the Imploded strategy. With Imploded strategy, the - * {@link Embedded} object of an entity is stored in a single field as an - * Embedded Entity in the Datastore. This annotation can be added to any - * {@link Embedded} field of an {@link Entity} or {@link MappedSuperClass}. - * Having this annotation on a nested Embedded object will not have any effect - * as the storage strategy is enforced at the entity level. + * Specifies that the {@link Embedded} object of an {@link Entity} should be stored using the + * Imploded strategy. With Imploded strategy, the {@link Embedded} object of an entity is stored in + * a single field as an Embedded Entity in the Datastore. This annotation can be added to any + * {@link Embedded} field of an {@link Entity} or {@link MappedSuperClass}. Having this annotation + * on a nested Embedded object will not have any effect as the storage strategy is enforced at the + * entity level. * * @author Sai Pullabhotla * @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(FIELD) public @interface Imploded { - + // Markers } diff --git a/src/main/java/com/jmethods/catatumbo/Indexer.java b/src/main/java/com/jmethods/catatumbo/Indexer.java index 7684dda..40de022 100644 --- a/src/main/java/com/jmethods/catatumbo/Indexer.java +++ b/src/main/java/com/jmethods/catatumbo/Indexer.java @@ -19,23 +19,22 @@ import com.google.cloud.datastore.Value; /** - * Contract for building secondary indexes for entity properties. An - * implementation of Indexer must have a public default (a.k.a no-argument) - * constructor. + * Contract for building secondary indexes for entity properties. An implementation of Indexer must + * have a public default (a.k.a no-argument) constructor. * * @author Sai Pullabhotla * */ public interface Indexer { - /** - * Returns indexed value for the given input. - * - * @param input - * the input, this is the output from the {@link Mapper} that is - * associated with the entity's field. - * @return the indexed value - */ - Value index(Value input); + /** + * Returns indexed value for the given input. + * + * @param input + * the input, this is the output from the {@link Mapper} that is associated with the + * entity's field. + * @return the indexed value + */ + Value index(Value input); } diff --git a/src/main/java/com/jmethods/catatumbo/IndexerFactory.java b/src/main/java/com/jmethods/catatumbo/IndexerFactory.java index 569c6bd..f7f1c98 100644 --- a/src/main/java/com/jmethods/catatumbo/IndexerFactory.java +++ b/src/main/java/com/jmethods/catatumbo/IndexerFactory.java @@ -28,118 +28,117 @@ import com.jmethods.catatumbo.indexers.LowerCaseStringListIndexer; /** - * A factory for producing indexers. This factory ensures there is at most one - * instance of a given Indexer implementation. + * A factory for producing indexers. This factory ensures there is at most one instance of a given + * Indexer implementation. * * @author Sai Pullabhotla * */ public class IndexerFactory { - /** - * Singleton instance - */ - private static final IndexerFactory INSTANCE = new IndexerFactory(); + /** + * Singleton instance + */ + private static final IndexerFactory INSTANCE = new IndexerFactory(); - /** - * Cache of previously produced indexers - */ - private Cache, Indexer> cache = null; + /** + * Cache of previously produced indexers + */ + private Cache, Indexer> cache = null; - /** - * Creates a new instance of IndexerFactory. - */ - private IndexerFactory() { - cache = new Cache<>(); - } + /** + * Creates a new instance of IndexerFactory. + */ + private IndexerFactory() { + cache = new Cache<>(); + } - /** - * Returns the singleton instance of this class. - * - * @return the singleton instance of this class. - */ - public static IndexerFactory getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of this class. + * + * @return the singleton instance of this class. + */ + public static IndexerFactory getInstance() { + return INSTANCE; + } - /** - * Gets the {@link Indexer} for the given field. If the field has a - * {@link PropertyIndexer} annotation, the specified indexer will be - * returned. Otherwise, a default indexer will be returned based on the - * field's type. - * - * @param field - * the field - * @return the indexer for the specified field. - */ - public Indexer getIndexer(Field field) { - PropertyIndexer indexerAnnotation = field.getAnnotation(PropertyIndexer.class); - if (indexerAnnotation != null) { - Class indexerClass = indexerAnnotation.value(); - return getIndexer(indexerClass); - } - return getDefaultIndexer(field); - } + /** + * Gets the {@link Indexer} for the given field. If the field has a {@link PropertyIndexer} + * annotation, the specified indexer will be returned. Otherwise, a default indexer will be + * returned based on the field's type. + * + * @param field + * the field + * @return the indexer for the specified field. + */ + public Indexer getIndexer(Field field) { + PropertyIndexer indexerAnnotation = field.getAnnotation(PropertyIndexer.class); + if (indexerAnnotation != null) { + Class indexerClass = indexerAnnotation.value(); + return getIndexer(indexerClass); + } + return getDefaultIndexer(field); + } - /** - * Returns the {@link Indexer} of the given implementation class. - * - * @param indexerClass - * the implementation class of the Indexer interface - * @return the Indexer - */ - @SuppressWarnings("unchecked") - public T getIndexer(Class indexerClass) { - Indexer indexer = cache.get(indexerClass); - if (indexer == null) { - indexer = createIndexer(indexerClass); - } - return (T) indexer; - } + /** + * Returns the {@link Indexer} of the given implementation class. + * + * @param indexerClass + * the implementation class of the Indexer interface + * @return the Indexer + */ + @SuppressWarnings("unchecked") + public T getIndexer(Class indexerClass) { + Indexer indexer = cache.get(indexerClass); + if (indexer == null) { + indexer = createIndexer(indexerClass); + } + return (T) indexer; + } - /** - * Creates the Indexer of the given class. - * - * @param indexerClass - * the indexer implementation class - * @return the Indexer. - */ - @SuppressWarnings("unchecked") - private T createIndexer(Class indexerClass) { - synchronized (indexerClass) { - Indexer indexer = cache.get(indexerClass); - if (indexer == null) { - indexer = (Indexer) IntrospectionUtils.instantiateObject(indexerClass); - cache.put(indexerClass, indexer); - } - return (T) indexer; - } - } + /** + * Creates the Indexer of the given class. + * + * @param indexerClass + * the indexer implementation class + * @return the Indexer. + */ + @SuppressWarnings("unchecked") + private T createIndexer(Class indexerClass) { + synchronized (indexerClass) { + Indexer indexer = cache.get(indexerClass); + if (indexer == null) { + indexer = (Indexer) IntrospectionUtils.instantiateObject(indexerClass); + cache.put(indexerClass, indexer); + } + return (T) indexer; + } + } - /** - * Returns the default indexer for the given field. - * - * @param field - * the field. - * @return the default indexer. - */ - private Indexer getDefaultIndexer(Field field) { - Type type = field.getGenericType(); - if (type instanceof Class && type.equals(String.class)) { - return getIndexer(LowerCaseStringIndexer.class); - } else if (type instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) type; - Class rawType = (Class) pType.getRawType(); - if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType)) { - Class[] collectionType = IntrospectionUtils.resolveCollectionType(type); - if (String.class.equals(collectionType[1])) { - return getIndexer(LowerCaseStringListIndexer.class); - } - } - } - String message = String.format("No default indexer found for field %s in class %s", field.getName(), - field.getDeclaringClass().getName()); - throw new NoSuitableIndexerException(message); - } + /** + * Returns the default indexer for the given field. + * + * @param field + * the field. + * @return the default indexer. + */ + private Indexer getDefaultIndexer(Field field) { + Type type = field.getGenericType(); + if (type instanceof Class && type.equals(String.class)) { + return getIndexer(LowerCaseStringIndexer.class); + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Class rawType = (Class) parameterizedType.getRawType(); + if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType)) { + Class[] collectionType = IntrospectionUtils.resolveCollectionType(type); + if (String.class.equals(collectionType[1])) { + return getIndexer(LowerCaseStringListIndexer.class); + } + } + } + String message = String.format("No default indexer found for field %s in class %s", + field.getName(), field.getDeclaringClass().getName()); + throw new NoSuitableIndexerException(message); + } } diff --git a/src/main/java/com/jmethods/catatumbo/IndexingException.java b/src/main/java/com/jmethods/catatumbo/IndexingException.java index 7fb525c..8688451 100644 --- a/src/main/java/com/jmethods/catatumbo/IndexingException.java +++ b/src/main/java/com/jmethods/catatumbo/IndexingException.java @@ -17,56 +17,55 @@ package com.jmethods.catatumbo; /** - * An exception thrown by {@link Indexer} to indicate any errors during data - * indexing. + * An exception thrown by {@link Indexer} to indicate any errors during data indexing. * * @author Sai Pullabhotla * */ public class IndexingException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 998960795045630795L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 998960795045630795L; - /** - * Creates a new instance of IndexingException. - */ - public IndexingException() { - super(); - } + /** + * Creates a new instance of IndexingException. + */ + public IndexingException() { + super(); + } - /** - * Creates a new instance of IndexingException. - * - * @param message - * the message - * @param cause - * the cause - */ - public IndexingException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of IndexingException. + * + * @param message + * the message + * @param cause + * the cause + */ + public IndexingException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of IndexingException. - * - * @param message - * the message - */ - public IndexingException(String message) { - super(message); - } + /** + * Creates a new instance of IndexingException. + * + * @param message + * the message + */ + public IndexingException(String message) { + super(message); + } - /** - * Creates a new instance of IndexingException. - * - * @param cause - * the cause - */ - public IndexingException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of IndexingException. + * + * @param cause + * the cause + */ + public IndexingException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/Key.java b/src/main/java/com/jmethods/catatumbo/Key.java index 9ab1fce..3e5f2b6 100644 --- a/src/main/java/com/jmethods/catatumbo/Key.java +++ b/src/main/java/com/jmethods/catatumbo/Key.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,15 +22,14 @@ import java.lang.annotation.Target; /** - * Fields annotated with this annotation in an Entity hold the full key of the - * entity. Full key includes the ancestor paths and the key of the entity. Only - * one field can be annotated as Key in a given entity. The type of field must - * be {@link DatastoreKey}. + * Fields annotated with this annotation in an Entity hold the full key of the entity. Full key + * includes the ancestor paths and the key of the entity. Only one field can be annotated as Key in + * a given entity. The type of field must be {@link DatastoreKey}. * * @author Sai Pullabhotla */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Key { - + // Markers } diff --git a/src/main/java/com/jmethods/catatumbo/KeyQueryRequest.java b/src/main/java/com/jmethods/catatumbo/KeyQueryRequest.java index 124d98f..4bf91ba 100644 --- a/src/main/java/com/jmethods/catatumbo/KeyQueryRequest.java +++ b/src/main/java/com/jmethods/catatumbo/KeyQueryRequest.java @@ -17,23 +17,23 @@ package com.jmethods.catatumbo; /** - * An implementation of {@link QueryRequest} for executing key-only queries. - * Key-only queries must only have __key__ in the SELECT list of - * fields, with optional WHERE or ORDER BY clauses. + * An implementation of {@link QueryRequest} for executing key-only queries. Key-only queries must + * only have __key__ in the SELECT list of fields, with optional WHERE or ORDER BY + * clauses. * * @author Sai Pullabhotla * */ public class KeyQueryRequest extends BaseQueryRequest { - /** - * Creates a new instance of KeyQueryRequest. - * - * @param query - * the query - */ - public KeyQueryRequest(String query) { - super(query); - } + /** + * Creates a new instance of KeyQueryRequest. + * + * @param query + * the query + */ + public KeyQueryRequest(String query) { + super(query); + } } diff --git a/src/main/java/com/jmethods/catatumbo/MappedSuperClass.java b/src/main/java/com/jmethods/catatumbo/MappedSuperClass.java index 97c8535..21df998 100644 --- a/src/main/java/com/jmethods/catatumbo/MappedSuperClass.java +++ b/src/main/java/com/jmethods/catatumbo/MappedSuperClass.java @@ -23,25 +23,22 @@ import java.lang.annotation.Target; /** - * Designates a class whose mapping information is applied to the entities that - * inherit from it. A class designated with the MappedSuperclass annotation can - * be mapped in the same way as an entity except that the mappings will apply - * only to its subclasses. This means, a MappedSuperClass may contain fields - * with {@link Identifier}, {@link Key}, {@link ParentKey}, {@link Property}, - * {@link Embedded} and {@link Ignore} annotations. The mapping information - * defined in the MappedSuperClass can be overridden by the Entity using the - * {@link PropertyOverrides} and {@link PropertyOverride} annotations. This - * allows an entity to use a different property name or turn on/off the indexing - * of a property. + * Designates a class whose mapping information is applied to the entities that inherit from it. A + * class designated with the MappedSuperclass annotation can be mapped in the same way as an entity + * except that the mappings will apply only to its subclasses. This means, a MappedSuperClass may + * contain fields with {@link Identifier}, {@link Key}, {@link ParentKey}, {@link Property}, + * {@link Embedded} and {@link Ignore} annotations. The mapping information defined in the + * MappedSuperClass can be overridden by the Entity using the {@link PropertyOverrides} and + * {@link PropertyOverride} annotations. This allows an entity to use a different property name or + * turn on/off the indexing of a property. * *

* It is legal for a MappedSuperClass extend from another MappedSuperClass. *

* *

- * Like {@link Entity entities}, the MappedSuperClass may also use either the - * classic Java Beans pattern or the Builder pattern. Subclasses of - * MappedSuperClass must use the same design pattern. + * Like {@link Entity entities}, the MappedSuperClass may also use either the classic Java Beans + * pattern or the Builder pattern. Subclasses of MappedSuperClass must use the same design pattern. *

* * @author Sai Pullabhotla @@ -50,5 +47,5 @@ @Retention(RUNTIME) @Target(TYPE) public @interface MappedSuperClass { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/Mapper.java b/src/main/java/com/jmethods/catatumbo/Mapper.java index 25df847..2f64666 100644 --- a/src/main/java/com/jmethods/catatumbo/Mapper.java +++ b/src/main/java/com/jmethods/catatumbo/Mapper.java @@ -27,26 +27,26 @@ */ public interface Mapper { - /** - * Maps the given Model object to native Cloud Datastore value. - * - * @param input - * the input to map - * @return the equivalent native value - * @throws MappingException - * if the input is not compatible. - */ - public ValueBuilder toDatastore(Object input); + /** + * Maps the given Model object to native Cloud Datastore value. + * + * @param input + * the input to map + * @return the equivalent native value + * @throws MappingException + * if the input is not compatible. + */ + public ValueBuilder toDatastore(Object input); - /** - * Maps the given native Cloud Datastore value to equivalent model object. - * - * @param input - * the native Cloud Datastore value - * @return the equivalent model object - * @throws MappingException - * if the input is not compatible. - */ - public Object toModel(Value input); + /** + * Maps the given native Cloud Datastore value to equivalent model object. + * + * @param input + * the native Cloud Datastore value + * @return the equivalent model object + * @throws MappingException + * if the input is not compatible. + */ + public Object toModel(Value input); } diff --git a/src/main/java/com/jmethods/catatumbo/MapperFactory.java b/src/main/java/com/jmethods/catatumbo/MapperFactory.java index c314798..0c26878 100644 --- a/src/main/java/com/jmethods/catatumbo/MapperFactory.java +++ b/src/main/java/com/jmethods/catatumbo/MapperFactory.java @@ -63,253 +63,252 @@ import com.jmethods.catatumbo.mappers.ZonedDateTimeMapper; /** - * A factory for producing data mappers that are used for mapping fields of - * model class to/from the Cloud Datastore. + * A factory for producing data mappers that are used for mapping fields of model class to/from the + * Cloud Datastore. * * @author Sai Pullabhotla * */ public class MapperFactory { - /** - * Singleton instance - */ - private static final MapperFactory INSTANCE = new MapperFactory(); + /** + * Singleton instance + */ + private static final MapperFactory INSTANCE = new MapperFactory(); - /** - * Cache of mappers by Type - */ - private Cache cache = null; + /** + * Cache of mappers by Type + */ + private Cache cache = null; - /** - * A lock for preventing multiple threads creating Mappers simultaneously - */ - private Lock lock; + /** + * A lock for preventing multiple threads creating Mappers simultaneously + */ + private Lock lock; - /** - * Creates a new instance of MapperFactory. - */ - private MapperFactory() { - cache = new Cache<>(); - lock = new ReentrantLock(); - createDefaultMappers(); - } + /** + * Creates a new instance of MapperFactory. + */ + private MapperFactory() { + cache = new Cache<>(); + lock = new ReentrantLock(); + createDefaultMappers(); + } - /** - * Returns the singleton instance of this MapperFactory. - * - * @return the singleton instance of this MapperFactory. - */ - public static MapperFactory getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of this MapperFactory. + * + * @return the singleton instance of this MapperFactory. + */ + public static MapperFactory getInstance() { + return INSTANCE; + } - /** - * Returns the mapper for the given field. If the field has a custom mapper, - * a new instance of the specified mapper will be created and returned. - * Otherwise, one of the built-in mappers will be returned based on the - * field type. - * - * @param field - * the field - * @return the mapper for the given field. - */ - public Mapper getMapper(Field field) { - PropertyMapper propertyMapperAnnotation = field.getAnnotation(PropertyMapper.class); - if (propertyMapperAnnotation != null) { - return createCustomMapper(field, propertyMapperAnnotation); - } - Class fieldType = field.getType(); - if (fieldType.equals(BigDecimal.class)) { - Decimal decimalAnnotation = field.getAnnotation(Decimal.class); - if (decimalAnnotation != null) { - return new DecimalMapper(decimalAnnotation.precision(), decimalAnnotation.scale()); - } - } - if (List.class.isAssignableFrom(fieldType) || Set.class.isAssignableFrom(fieldType)) { - return CollectionMapperFactory.getInstance().getMapper(field); - } - return getMapper(field.getGenericType()); - } + /** + * Returns the mapper for the given field. If the field has a custom mapper, a new instance of the + * specified mapper will be created and returned. Otherwise, one of the built-in mappers will be + * returned based on the field type. + * + * @param field + * the field + * @return the mapper for the given field. + */ + public Mapper getMapper(Field field) { + PropertyMapper propertyMapperAnnotation = field.getAnnotation(PropertyMapper.class); + if (propertyMapperAnnotation != null) { + return createCustomMapper(field, propertyMapperAnnotation); + } + Class fieldType = field.getType(); + if (fieldType.equals(BigDecimal.class)) { + Decimal decimalAnnotation = field.getAnnotation(Decimal.class); + if (decimalAnnotation != null) { + return new DecimalMapper(decimalAnnotation.precision(), decimalAnnotation.scale()); + } + } + if (List.class.isAssignableFrom(fieldType) || Set.class.isAssignableFrom(fieldType)) { + return CollectionMapperFactory.getInstance().getMapper(field); + } + return getMapper(field.getGenericType()); + } - /** - * Returns a mapper for the given type. If a mapper that can handle given - * type exists in the cache, it will be returned. Otherwise, a new mapper - * will be created. - * - * @param type - * the type of field in the model class - * @return a {@link Mapper} that is capable of mapping the given type. - */ - public Mapper getMapper(Type type) { - Mapper mapper = cache.get(type); - if (mapper == null) { - mapper = createMapper(type); - } - return mapper; - } + /** + * Returns a mapper for the given type. If a mapper that can handle given type exists in the + * cache, it will be returned. Otherwise, a new mapper will be created. + * + * @param type + * the type of field in the model class + * @return a {@link Mapper} that is capable of mapping the given type. + */ + public Mapper getMapper(Type type) { + Mapper mapper = cache.get(type); + if (mapper == null) { + mapper = createMapper(type); + } + return mapper; + } - /** - * Sets or registers the given mapper for the given type. This method must - * be called before performing any persistence operations, preferably, - * during application startup. Entities that were introspected before - * calling this method will NOT use the new mapper. - * - * @param type - * the type - * @param mapper - * the mapper to use for the given type - */ - public void setDefaultMapper(Type type, Mapper mapper) { - if (mapper == null) { - throw new NullPointerException("mapper cannot be null"); - } - lock.lock(); - try { - cache.put(type, mapper); - } finally { - lock.unlock(); - } - } + /** + * Sets or registers the given mapper for the given type. This method must be called before + * performing any persistence operations, preferably, during application startup. Entities that + * were introspected before calling this method will NOT use the new mapper. + * + * @param type + * the type + * @param mapper + * the mapper to use for the given type + */ + public void setDefaultMapper(Type type, Mapper mapper) { + if (mapper == null) { + throw new NullPointerException("mapper cannot be null"); + } + lock.lock(); + try { + cache.put(type, mapper); + } finally { + lock.unlock(); + } + } - /** - * Creates a new mapper for the given type. - * - * @param type - * the type for which a mapper is to be created - * @return a mapper that can handle the mapping of given type to/from the - * Cloud Datastore. - */ - private Mapper createMapper(Type type) { - lock.lock(); - try { - Mapper mapper = cache.get(type); - if (mapper != null) { - return mapper; - } - if (type instanceof Class) { - mapper = createMapper((Class) type); - } else if (type instanceof ParameterizedType) { - mapper = createMapper((ParameterizedType) type); - } else { - throw new IllegalArgumentException( - String.format("Type %s is neither a Class nor ParameterizedType", type)); - } - cache.put(type, mapper); - return mapper; - } finally { - lock.unlock(); - } - } + /** + * Creates a new mapper for the given type. + * + * @param type + * the type for which a mapper is to be created + * @return a mapper that can handle the mapping of given type to/from the Cloud Datastore. + */ + private Mapper createMapper(Type type) { + lock.lock(); + try { + Mapper mapper = cache.get(type); + if (mapper != null) { + return mapper; + } + if (type instanceof Class) { + mapper = createMapper((Class) type); + } else if (type instanceof ParameterizedType) { + mapper = createMapper((ParameterizedType) type); + } else { + throw new IllegalArgumentException( + String.format("Type %s is neither a Class nor ParameterizedType", type)); + } + cache.put(type, mapper); + return mapper; + } finally { + lock.unlock(); + } + } - /** - * Creates a mapper for the given class. - * - * @param clazz - * the class - * @return the mapper for the given class. - */ - private Mapper createMapper(Class clazz) { - Mapper mapper; - if (Enum.class.isAssignableFrom(clazz)) { - mapper = new EnumMapper(clazz); - } else if (Map.class.isAssignableFrom(clazz)) { - mapper = new MapMapper(clazz); - } else if (clazz.isAnnotationPresent(Embeddable.class)) { - mapper = new EmbeddedObjectMapper(clazz); - } else { - throw new NoSuitableMapperException(String.format("No mapper found for class %s", clazz.getName())); - } - return mapper; - } + /** + * Creates a mapper for the given class. + * + * @param clazz + * the class + * @return the mapper for the given class. + */ + private Mapper createMapper(Class clazz) { + Mapper mapper; + if (Enum.class.isAssignableFrom(clazz)) { + mapper = new EnumMapper(clazz); + } else if (Map.class.isAssignableFrom(clazz)) { + mapper = new MapMapper(clazz); + } else if (clazz.isAnnotationPresent(Embeddable.class)) { + mapper = new EmbeddedObjectMapper(clazz); + } else { + throw new NoSuitableMapperException( + String.format("No mapper found for class %s", clazz.getName())); + } + return mapper; + } - /** - * Creates a {@link Mapper} for the given class/type. - * - * @param type - * the type - * @return a {@link Mapper} for the given class/type. - */ - private Mapper createMapper(ParameterizedType type) { - Type rawType = type.getRawType(); - if (!(rawType instanceof Class)) { - // Don't see how this could ever happen, but just in case... - throw new IllegalArgumentException(String.format("Raw type of ParameterizedType is not a class: %s", type)); - } - Class rawClass = (Class) rawType; - Mapper mapper; - if (Map.class.isAssignableFrom(rawClass)) { - mapper = new MapMapper(type); - } else { - throw new NoSuitableMapperException(String.format("Unsupported type: %s", type)); - } - return mapper; - } + /** + * Creates a {@link Mapper} for the given class/type. + * + * @param type + * the type + * @return a {@link Mapper} for the given class/type. + */ + private Mapper createMapper(ParameterizedType type) { + Type rawType = type.getRawType(); + if (!(rawType instanceof Class)) { + // Don't see how this could ever happen, but just in case... + throw new IllegalArgumentException( + String.format("Raw type of ParameterizedType is not a class: %s", type)); + } + Class rawClass = (Class) rawType; + Mapper mapper; + if (Map.class.isAssignableFrom(rawClass)) { + mapper = new MapMapper(type); + } else { + throw new NoSuitableMapperException(String.format("Unsupported type: %s", type)); + } + return mapper; + } - /** - * Creates and assigns default Mappers various common types. - */ - private void createDefaultMappers() { - BooleanMapper booleanMapper = new BooleanMapper(); - CharMapper charMapper = new CharMapper(); - ShortMapper shortMapper = new ShortMapper(); - IntegerMapper integerMapper = new IntegerMapper(); - LongMapper longMapper = new LongMapper(); - FloatMapper floatMapper = new FloatMapper(); - DoubleMapper doubleMapper = new DoubleMapper(); + /** + * Creates and assigns default Mappers various common types. + */ + private void createDefaultMappers() { + BooleanMapper booleanMapper = new BooleanMapper(); + CharMapper charMapper = new CharMapper(); + ShortMapper shortMapper = new ShortMapper(); + IntegerMapper integerMapper = new IntegerMapper(); + LongMapper longMapper = new LongMapper(); + FloatMapper floatMapper = new FloatMapper(); + DoubleMapper doubleMapper = new DoubleMapper(); - cache.put(boolean.class, booleanMapper); - cache.put(Boolean.class, booleanMapper); - cache.put(char.class, charMapper); - cache.put(Character.class, charMapper); - cache.put(short.class, shortMapper); - cache.put(Short.class, shortMapper); - cache.put(int.class, integerMapper); - cache.put(Integer.class, integerMapper); - cache.put(long.class, longMapper); - cache.put(Long.class, longMapper); - cache.put(float.class, floatMapper); - cache.put(Float.class, floatMapper); - cache.put(double.class, doubleMapper); - cache.put(Double.class, doubleMapper); - cache.put(String.class, new StringMapper()); - cache.put(BigDecimal.class, new BigDecimalMapper()); - cache.put(byte[].class, new ByteArrayMapper()); - cache.put(char[].class, new CharArrayMapper()); - cache.put(Date.class, new DateMapper()); - cache.put(Calendar.class, new CalendarMapper()); - cache.put(GeoLocation.class, new GeoLocationMapper()); - cache.put(DatastoreKey.class, new KeyMapper()); - cache.put(LocalDate.class, new LocalDateMapper()); - cache.put(LocalTime.class, new LocalTimeMapper()); - cache.put(LocalDateTime.class, new LocalDateTimeMapper()); - cache.put(OffsetDateTime.class, new OffsetDateTimeMapper()); - cache.put(ZonedDateTime.class, new ZonedDateTimeMapper()); - } + cache.put(boolean.class, booleanMapper); + cache.put(Boolean.class, booleanMapper); + cache.put(char.class, charMapper); + cache.put(Character.class, charMapper); + cache.put(short.class, shortMapper); + cache.put(Short.class, shortMapper); + cache.put(int.class, integerMapper); + cache.put(Integer.class, integerMapper); + cache.put(long.class, longMapper); + cache.put(Long.class, longMapper); + cache.put(float.class, floatMapper); + cache.put(Float.class, floatMapper); + cache.put(double.class, doubleMapper); + cache.put(Double.class, doubleMapper); + cache.put(String.class, new StringMapper()); + cache.put(BigDecimal.class, new BigDecimalMapper()); + cache.put(byte[].class, new ByteArrayMapper()); + cache.put(char[].class, new CharArrayMapper()); + cache.put(Date.class, new DateMapper()); + cache.put(Calendar.class, new CalendarMapper()); + cache.put(GeoLocation.class, new GeoLocationMapper()); + cache.put(DatastoreKey.class, new KeyMapper()); + cache.put(LocalDate.class, new LocalDateMapper()); + cache.put(LocalTime.class, new LocalTimeMapper()); + cache.put(LocalDateTime.class, new LocalDateTimeMapper()); + cache.put(OffsetDateTime.class, new OffsetDateTimeMapper()); + cache.put(ZonedDateTime.class, new ZonedDateTimeMapper()); + } - /** - * Creates and returns a custom mapper for the given field. - * - * @param field - * the field - * @param propertyMapperAnnotation - * property mapper annotation that specifies the mapper class - * @return custom mapper for the given field - */ - private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) { - Class mapperClass = propertyMapperAnnotation.value(); - Constructor constructor = IntrospectionUtils.getConstructor(mapperClass, Field.class); - if (constructor != null) { - try { - return constructor.newInstance(field); - } catch (Exception exp) { - throw new EntityManagerException(exp); - } - } - throw new EntityManagerException( - String.format("Mapper class %s must have a public constructor with a parameter type of %s", - mapperClass.getName(), Field.class.getName())); + /** + * Creates and returns a custom mapper for the given field. + * + * @param field + * the field + * @param propertyMapperAnnotation + * property mapper annotation that specifies the mapper class + * @return custom mapper for the given field + */ + private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) { + Class mapperClass = propertyMapperAnnotation.value(); + Constructor constructor = IntrospectionUtils.getConstructor(mapperClass, + Field.class); + if (constructor != null) { + try { + return constructor.newInstance(field); + } catch (Exception exp) { + throw new EntityManagerException(exp); + } + } + throw new EntityManagerException( + String.format("Mapper class %s must have a public constructor with a parameter type of %s", + mapperClass.getName(), Field.class.getName())); - } + } } diff --git a/src/main/java/com/jmethods/catatumbo/MappingException.java b/src/main/java/com/jmethods/catatumbo/MappingException.java index dcac638..ca766af 100644 --- a/src/main/java/com/jmethods/catatumbo/MappingException.java +++ b/src/main/java/com/jmethods/catatumbo/MappingException.java @@ -17,56 +17,55 @@ package com.jmethods.catatumbo; /** - * An exception thrown by {@link Mapper} to indicate any errors during data - * mapping. + * An exception thrown by {@link Mapper} to indicate any errors during data mapping. * * @author Sai Pullabhotla * */ public class MappingException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -3940373782421116805L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -3940373782421116805L; - /** - * Creates a new instance of MappingException. - */ - public MappingException() { - super(); - } + /** + * Creates a new instance of MappingException. + */ + public MappingException() { + super(); + } - /** - * Creates a new instance of MappingException. - * - * @param message - * the message - * @param cause - * the cause - */ - public MappingException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of MappingException. + * + * @param message + * the message + * @param cause + * the cause + */ + public MappingException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of MappingException. - * - * @param message - * the message - */ - public MappingException(String message) { - super(message); - } + /** + * Creates a new instance of MappingException. + * + * @param message + * the message + */ + public MappingException(String message) { + super(message); + } - /** - * Creates a new instance of MappingException. - * - * @param cause - * the cause - */ - public MappingException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of MappingException. + * + * @param cause + * the cause + */ + public MappingException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/NoAccessorMethodException.java b/src/main/java/com/jmethods/catatumbo/NoAccessorMethodException.java index f269b18..ca5a404 100644 --- a/src/main/java/com/jmethods/catatumbo/NoAccessorMethodException.java +++ b/src/main/java/com/jmethods/catatumbo/NoAccessorMethodException.java @@ -17,55 +17,55 @@ package com.jmethods.catatumbo; /** - * An Exception to indicate that a model class (e.g. Entity, Embeddable, etc.) - * is missing a required public accessor method. + * An Exception to indicate that a model class (e.g. Entity, Embeddable, etc.) is missing a required + * public accessor method. * * @author Sai Pullabhotla * */ public class NoAccessorMethodException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 5714470702079334554L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 5714470702079334554L; - /** - * Creates a new instance of NoAccessorMethodException. - */ - public NoAccessorMethodException() { - } + /** + * Creates a new instance of NoAccessorMethodException. + */ + public NoAccessorMethodException() { + } - /** - * Creates a new instance of NoAccessorMethodException. - * - * @param msg - * the detailed message. - */ - public NoAccessorMethodException(String msg) { - super(msg); - } + /** + * Creates a new instance of NoAccessorMethodException. + * + * @param msg + * the detailed message. + */ + public NoAccessorMethodException(String msg) { + super(msg); + } - /** - * Creates a new instance of NoAccessorMethodException. - * - * @param message - * the detailed message - * @param cause - * the cause - */ - public NoAccessorMethodException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of NoAccessorMethodException. + * + * @param message + * the detailed message + * @param cause + * the cause + */ + public NoAccessorMethodException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of NoAccessorMethodException. - * - * @param cause - * the cause. - */ - public NoAccessorMethodException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of NoAccessorMethodException. + * + * @param cause + * the cause. + */ + public NoAccessorMethodException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/NoDefaultConstructorException.java b/src/main/java/com/jmethods/catatumbo/NoDefaultConstructorException.java index 8c6f9da..30c0fc5 100644 --- a/src/main/java/com/jmethods/catatumbo/NoDefaultConstructorException.java +++ b/src/main/java/com/jmethods/catatumbo/NoDefaultConstructorException.java @@ -17,56 +17,56 @@ package com.jmethods.catatumbo; /** - * An exception to indicate a model class (Entity, Embeddable, etc.) does not - * have the required public no-argument constructor. + * An exception to indicate a model class (Entity, Embeddable, etc.) does not have the required + * public no-argument constructor. * * @author Sai Pullabhotla * */ public class NoDefaultConstructorException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -8627001926046445483L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -8627001926046445483L; - /** - * Creates a new instance of NoDefaultConstructorException. - */ - public NoDefaultConstructorException() { - super(); - } + /** + * Creates a new instance of NoDefaultConstructorException. + */ + public NoDefaultConstructorException() { + super(); + } - /** - * Creates a new instance of NoDefaultConstructorException. - * - * @param msg - * the detailed message - */ - public NoDefaultConstructorException(String msg) { - super(msg); - } + /** + * Creates a new instance of NoDefaultConstructorException. + * + * @param msg + * the detailed message + */ + public NoDefaultConstructorException(String msg) { + super(msg); + } - /** - * Creates a new instance of NoDefaultConstructorException. - * - * @param message - * the detailed message - * @param cause - * the cause - */ - public NoDefaultConstructorException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of NoDefaultConstructorException. + * + * @param message + * the detailed message + * @param cause + * the cause + */ + public NoDefaultConstructorException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of NoDefaultConstructorException. - * - * @param cause - * the cause - */ - public NoDefaultConstructorException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of NoDefaultConstructorException. + * + * @param cause + * the cause + */ + public NoDefaultConstructorException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/NoMutatorMethodException.java b/src/main/java/com/jmethods/catatumbo/NoMutatorMethodException.java index e733b0b..a7e9400 100644 --- a/src/main/java/com/jmethods/catatumbo/NoMutatorMethodException.java +++ b/src/main/java/com/jmethods/catatumbo/NoMutatorMethodException.java @@ -17,55 +17,55 @@ package com.jmethods.catatumbo; /** - * An Exception to indicate that a model class (e.g. Entity, Embeddable, etc.) - * is missing a required public mutator method. + * An Exception to indicate that a model class (e.g. Entity, Embeddable, etc.) is missing a required + * public mutator method. * * @author Sai Pullabhotla * */ public class NoMutatorMethodException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 7547518972406162160L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 7547518972406162160L; - /** - * Creates a new instance of {@code NoMutatorMethodException}. - */ - public NoMutatorMethodException() { - } + /** + * Creates a new instance of {@code NoMutatorMethodException}. + */ + public NoMutatorMethodException() { + } - /** - * Creates a new instance of {@code NoMutatorMethodException}. - * - * @param msg - * the detailed message. - */ - public NoMutatorMethodException(String msg) { - super(msg); - } + /** + * Creates a new instance of {@code NoMutatorMethodException}. + * + * @param msg + * the detailed message. + */ + public NoMutatorMethodException(String msg) { + super(msg); + } - /** - * Creates a new instance of {@code NoMutatorMethodException}. - * - * @param message - * the detailed message - * @param cause - * the cause - */ - public NoMutatorMethodException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of {@code NoMutatorMethodException}. + * + * @param message + * the detailed message + * @param cause + * the cause + */ + public NoMutatorMethodException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of {@code NoMutatorMethodException}. - * - * @param cause - * the cause. - */ - public NoMutatorMethodException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of {@code NoMutatorMethodException}. + * + * @param cause + * the cause. + */ + public NoMutatorMethodException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/NoSuitableIndexerException.java b/src/main/java/com/jmethods/catatumbo/NoSuitableIndexerException.java index 4ce9f46..cfceadb 100644 --- a/src/main/java/com/jmethods/catatumbo/NoSuitableIndexerException.java +++ b/src/main/java/com/jmethods/catatumbo/NoSuitableIndexerException.java @@ -17,56 +17,56 @@ package com.jmethods.catatumbo; /** - * An exception to indicate that there is no {@link Indexer} to handle the - * indexing of a specific type. + * An exception to indicate that there is no {@link Indexer} to handle the indexing of a specific + * type. * * @author Sai Pullabhotla * */ public class NoSuitableIndexerException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 6166844206650805406L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 6166844206650805406L; - /** - * Creates a new instance of NoSuitableIndexerException. - */ - public NoSuitableIndexerException() { - super(); - } + /** + * Creates a new instance of NoSuitableIndexerException. + */ + public NoSuitableIndexerException() { + super(); + } - /** - * Creates a new instance of NoSuitableIndexerException. - * - * @param message - * the detailed message - * @param cause - * the cause - */ - public NoSuitableIndexerException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of NoSuitableIndexerException. + * + * @param message + * the detailed message + * @param cause + * the cause + */ + public NoSuitableIndexerException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of NoSuitableIndexerException. - * - * @param message - * the detailed message - */ - public NoSuitableIndexerException(String message) { - super(message); - } + /** + * Creates a new instance of NoSuitableIndexerException. + * + * @param message + * the detailed message + */ + public NoSuitableIndexerException(String message) { + super(message); + } - /** - * Creates a new instance of NoSuitableIndexerException. - * - * @param cause - * the cause - */ - public NoSuitableIndexerException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of NoSuitableIndexerException. + * + * @param cause + * the cause + */ + public NoSuitableIndexerException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/NoSuitableMapperException.java b/src/main/java/com/jmethods/catatumbo/NoSuitableMapperException.java index 87681a8..1b79c03 100644 --- a/src/main/java/com/jmethods/catatumbo/NoSuitableMapperException.java +++ b/src/main/java/com/jmethods/catatumbo/NoSuitableMapperException.java @@ -17,56 +17,55 @@ package com.jmethods.catatumbo; /** - * An exception to indicate there is no {@link Mapper} to handle the mapping of - * a specific type. + * An exception to indicate there is no {@link Mapper} to handle the mapping of a specific type. * * @author Sai Pullabhotla * */ public class NoSuitableMapperException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = -2512232420451752974L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -2512232420451752974L; - /** - * Creates a new instance of NoSuitableMapperException. - */ - public NoSuitableMapperException() { - super(); - } + /** + * Creates a new instance of NoSuitableMapperException. + */ + public NoSuitableMapperException() { + super(); + } - /** - * Creates a new instance of NoSuitableMapperException. - * - * @param message - * the detailed message - * @param cause - * the cause - */ - public NoSuitableMapperException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of NoSuitableMapperException. + * + * @param message + * the detailed message + * @param cause + * the cause + */ + public NoSuitableMapperException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of NoSuitableMapperException. - * - * @param message - * the detailed message - */ - public NoSuitableMapperException(String message) { - super(message); - } + /** + * Creates a new instance of NoSuitableMapperException. + * + * @param message + * the detailed message + */ + public NoSuitableMapperException(String message) { + super(message); + } - /** - * Creates a new instance of NoSuitableMapperException. - * - * @param cause - * the cause - */ - public NoSuitableMapperException(Throwable cause) { - super(cause); - } + /** + * Creates a new instance of NoSuitableMapperException. + * + * @param cause + * the cause + */ + public NoSuitableMapperException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/OptimisticLockException.java b/src/main/java/com/jmethods/catatumbo/OptimisticLockException.java index 4738c85..01dfede 100644 --- a/src/main/java/com/jmethods/catatumbo/OptimisticLockException.java +++ b/src/main/java/com/jmethods/catatumbo/OptimisticLockException.java @@ -17,58 +17,57 @@ package com.jmethods.catatumbo; /** - * An exception thrown by the {@link EntityManager} to report a conflict with - * optimistic locks. This exception is thrown when the entity being updated does - * not exist the in the Datastore or the version property of the entity does not - * match with the entity being updated. + * An exception thrown by the {@link EntityManager} to report a conflict with optimistic locks. This + * exception is thrown when the entity being updated does not exist the in the Datastore or the + * version property of the entity does not match with the entity being updated. * * @author Sai Pullabhotla * */ public class OptimisticLockException extends EntityManagerException { - /** - * Serial version UID - */ - private static final long serialVersionUID = 1879640702345246635L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 1879640702345246635L; - /** - * Creates a new instance of OptimisticLockException. - */ - public OptimisticLockException() { - super(); - } + /** + * Creates a new instance of OptimisticLockException. + */ + public OptimisticLockException() { + super(); + } - /** - * Creates a new instance of OptimisticLockException. - * - * @param message - * the message - * @param cause - * the cause - */ - public OptimisticLockException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new instance of OptimisticLockException. + * + * @param message + * the message + * @param cause + * the cause + */ + public OptimisticLockException(String message, Throwable cause) { + super(message, cause); + } - /** - * Creates a new instance of OptimisticLockException. - * - * @param message - * the message - */ - public OptimisticLockException(String message) { - super(message); - } + /** + * Creates a new instance of OptimisticLockException. + * + * @param message + * the message + */ + public OptimisticLockException(String message) { + super(message); + } - /** - * Creates a new instance of OptimisticLockException. - * - * @param cause - * the cause - */ - public OptimisticLockException(Throwable cause) { - super(cause.getMessage(), cause); - } + /** + * Creates a new instance of OptimisticLockException. + * + * @param cause + * the cause + */ + public OptimisticLockException(Throwable cause) { + super(cause.getMessage(), cause); + } } diff --git a/src/main/java/com/jmethods/catatumbo/ParentKey.java b/src/main/java/com/jmethods/catatumbo/ParentKey.java index 5678b43..2dc6670 100644 --- a/src/main/java/com/jmethods/catatumbo/ParentKey.java +++ b/src/main/java/com/jmethods/catatumbo/ParentKey.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,14 +22,13 @@ import java.lang.annotation.Target; /** - * Fields annotated as ParentKey hold the parent key information, - * if any. Only one field can be annotated with this annotation in a given - * Entity. + * Fields annotated as ParentKey hold the parent key information, if any. Only one + * field can be annotated with this annotation in a given Entity. * * @author Sai Pullabhotla */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ParentKey { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PostDelete.java b/src/main/java/com/jmethods/catatumbo/PostDelete.java index 0154b58..c2ebf37 100644 --- a/src/main/java/com/jmethods/catatumbo/PostDelete.java +++ b/src/main/java/com/jmethods/catatumbo/PostDelete.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked after deleting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * after deleting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PostDelete { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PostInsert.java b/src/main/java/com/jmethods/catatumbo/PostInsert.java index d1efb19..53b3758 100644 --- a/src/main/java/com/jmethods/catatumbo/PostInsert.java +++ b/src/main/java/com/jmethods/catatumbo/PostInsert.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked after inserting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * after inserting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PostInsert { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PostLoad.java b/src/main/java/com/jmethods/catatumbo/PostLoad.java index 412d7f9..1acf705 100644 --- a/src/main/java/com/jmethods/catatumbo/PostLoad.java +++ b/src/main/java/com/jmethods/catatumbo/PostLoad.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked after loading an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * after loading an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * *

* Note that PostLoad callback is NOT invoked for projection queries. @@ -41,5 +40,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PostLoad { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PostUpdate.java b/src/main/java/com/jmethods/catatumbo/PostUpdate.java index 060d0f0..433f70c 100644 --- a/src/main/java/com/jmethods/catatumbo/PostUpdate.java +++ b/src/main/java/com/jmethods/catatumbo/PostUpdate.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked after updating an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * after updating an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PostUpdate { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PostUpsert.java b/src/main/java/com/jmethods/catatumbo/PostUpsert.java index 91c3a43..370b36d 100644 --- a/src/main/java/com/jmethods/catatumbo/PostUpsert.java +++ b/src/main/java/com/jmethods/catatumbo/PostUpsert.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked after upserting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * after upserting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PostUpsert { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PreDelete.java b/src/main/java/com/jmethods/catatumbo/PreDelete.java index ce8dda8..c81ac28 100644 --- a/src/main/java/com/jmethods/catatumbo/PreDelete.java +++ b/src/main/java/com/jmethods/catatumbo/PreDelete.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked before deleting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * before deleting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PreDelete { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PreInsert.java b/src/main/java/com/jmethods/catatumbo/PreInsert.java index bf890f7..037222b 100644 --- a/src/main/java/com/jmethods/catatumbo/PreInsert.java +++ b/src/main/java/com/jmethods/catatumbo/PreInsert.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked before inserting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * before inserting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PreInsert { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PreUpdate.java b/src/main/java/com/jmethods/catatumbo/PreUpdate.java index 2450c14..1826a96 100644 --- a/src/main/java/com/jmethods/catatumbo/PreUpdate.java +++ b/src/main/java/com/jmethods/catatumbo/PreUpdate.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked before updating an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * before updating an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PreUpdate { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/PreUpsert.java b/src/main/java/com/jmethods/catatumbo/PreUpsert.java index 11e4b80..1233feb 100644 --- a/src/main/java/com/jmethods/catatumbo/PreUpsert.java +++ b/src/main/java/com/jmethods/catatumbo/PreUpsert.java @@ -16,17 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used for annotating a method as an entity listener method. The annotated - * method will be invoked before upserting an entity. This annotation can be - * applied to a method within an {@link Entity}, {@link MappedSuperClass} or an - * {@link EntityListener}. + * Used for annotating a method as an entity listener method. The annotated method will be invoked + * before upserting an entity. This annotation can be applied to a method within an {@link Entity}, + * {@link MappedSuperClass} or an {@link EntityListener}. * * @see EntityListeners * @see EntityListener @@ -37,5 +36,5 @@ @Retention(RUNTIME) @Target(METHOD) public @interface PreUpsert { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/ProjectedEntity.java b/src/main/java/com/jmethods/catatumbo/ProjectedEntity.java index a0e185c..a13060f 100644 --- a/src/main/java/com/jmethods/catatumbo/ProjectedEntity.java +++ b/src/main/java/com/jmethods/catatumbo/ProjectedEntity.java @@ -23,16 +23,14 @@ import java.lang.annotation.Target; /** - * Specifies that a class is a Projected Entity. ProjectedEntity is similar to a - * regular {@link Entity}, but typically contains a subset of fields of an - * entity. Projected Entities are useful for mapping the results of a projection - * query. + * Specifies that a class is a Projected Entity. ProjectedEntity is similar to a regular + * {@link Entity}, but typically contains a subset of fields of an entity. Projected Entities are + * useful for mapping the results of a projection query. *

- * Note that results of a projection query can be mapped to an {@link Entity}, - * but having a {@link ProjectedEntity} helps accidental data loss (e.g. - * persisting an entity mapped from a projection query). The EntityManager - * restricts persistence of ProjectedEntities. To clarify this further, INSERT, - * UPDATE and UPSERT operations are not allowed on ProjectedEntities. DELETE + * Note that results of a projection query can be mapped to an {@link Entity}, but having a + * {@link ProjectedEntity} helps accidental data loss (e.g. persisting an entity mapped from a + * projection query). The EntityManager restricts persistence of ProjectedEntities. To clarify this + * further, INSERT, UPDATE and UPSERT operations are not allowed on ProjectedEntities. DELETE * operations are still valid on Projected Entities. *

* @@ -43,11 +41,11 @@ @Target(ElementType.TYPE) public @interface ProjectedEntity { - /** - * The entity Kind. - * - * @return the entity Kind. - */ - String kind(); + /** + * The entity Kind. + * + * @return the entity Kind. + */ + String kind(); } diff --git a/src/main/java/com/jmethods/catatumbo/ProjectionQueryRequest.java b/src/main/java/com/jmethods/catatumbo/ProjectionQueryRequest.java index acdf561..f04dd79 100644 --- a/src/main/java/com/jmethods/catatumbo/ProjectionQueryRequest.java +++ b/src/main/java/com/jmethods/catatumbo/ProjectionQueryRequest.java @@ -17,23 +17,22 @@ package com.jmethods.catatumbo; /** - * An implementation of {@link QueryRequest} to execute projection queries. - * Projection queries are used for retrieving a subset of entity's properties - * instead of retrieving all of them. + * An implementation of {@link QueryRequest} to execute projection queries. Projection queries are + * used for retrieving a subset of entity's properties instead of retrieving all of them. * * @author Sai Pullabhotla * */ public class ProjectionQueryRequest extends BaseQueryRequest { - /** - * Creates a new instance of ProjectionQueryRequest. - * - * @param query - * the GQL projection query - */ - public ProjectionQueryRequest(String query) { - super(query); - } + /** + * Creates a new instance of ProjectionQueryRequest. + * + * @param query + * the GQL projection query + */ + public ProjectionQueryRequest(String query) { + super(query); + } } diff --git a/src/main/java/com/jmethods/catatumbo/Property.java b/src/main/java/com/jmethods/catatumbo/Property.java index 157a353..3da2cf4 100644 --- a/src/main/java/com/jmethods/catatumbo/Property.java +++ b/src/main/java/com/jmethods/catatumbo/Property.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo; import java.lang.annotation.ElementType; @@ -21,10 +22,9 @@ import java.lang.annotation.Target; /** - * Specifies the mapped property for a persistable field. It is not necessary to - * have this annotation on every field of the entity. By default, all field - * declared in the entity are treated as persistable, unless they are marked - * with {@link Ignore} annotation. + * Specifies the mapped property for a persistable field. It is not necessary to have this + * annotation on every field of the entity. By default, all field declared in the entity are treated + * as persistable, unless they are marked with {@link Ignore} annotation. * * @author Sai Pullabhotla */ @@ -32,44 +32,42 @@ @Target(ElementType.FIELD) public @interface Property { - /** - * Specifies the name of the property in the Cloud Datastore. If not - * specified, the field name is used as the property name. - * - * @return the property name - */ - String name() default ""; + /** + * Specifies the name of the property in the Cloud Datastore. If not specified, the field name is + * used as the property name. + * + * @return the property name + */ + String name() default ""; - /** - * Specifies if the property should be indexed or not. - * - * @return if the property should be indexed or not. - */ - boolean indexed() default true; + /** + * Specifies if the property should be indexed or not. + * + * @return if the property should be indexed or not. + */ + boolean indexed() default true; - /** - * Specifies whether or not the property is optional. When optional is set - * to true on a field of an {@link Entity}, - * {@link MappedSuperClass} or {@link Embeddable}, and if the field is - * null, the property will be completely omitted when saving - * the Entity to the Datastore. Setting optional to true will - * not have any effect in the following cases: - *
    - *
  • if the type of field is primitive
  • - *
  • the field has annotation of {@link Version}
  • - *
  • the field has annotation of {@link CreatedTimestamp}
  • - *
  • the field has annotation of {@link UpdatedTimestamp}
  • - *
- * - *

- * If the field has a {@link SecondaryIndex} defined, the corresponding - * secondary property will also be omitted when the primary property is - * omitted. - *

- * - * @return Whether or not the property is optional, and hence it should not - * be persisted when the corresponding field is null. - */ - boolean optional() default false; + /** + * Specifies whether or not the property is optional. When optional is set to true on + * a field of an {@link Entity}, {@link MappedSuperClass} or {@link Embeddable}, and if the field + * is null, the property will be completely omitted when saving the Entity to the + * Datastore. Setting optional to true will not have any effect in the following + * cases: + *
    + *
  • if the type of field is primitive
  • + *
  • the field has annotation of {@link Version}
  • + *
  • the field has annotation of {@link CreatedTimestamp}
  • + *
  • the field has annotation of {@link UpdatedTimestamp}
  • + *
+ * + *

+ * If the field has a {@link SecondaryIndex} defined, the corresponding secondary property will + * also be omitted when the primary property is omitted. + *

+ * + * @return Whether or not the property is optional, and hence it should not be persisted when the + * corresponding field is null. + */ + boolean optional() default false; } diff --git a/src/main/java/com/jmethods/catatumbo/PropertyIndexer.java b/src/main/java/com/jmethods/catatumbo/PropertyIndexer.java index a348bef..9eac0d1 100644 --- a/src/main/java/com/jmethods/catatumbo/PropertyIndexer.java +++ b/src/main/java/com/jmethods/catatumbo/PropertyIndexer.java @@ -23,10 +23,10 @@ import java.lang.annotation.Target; /** - * Used to specify the Indexer to use for a given property/field of an entity. - * This annotation can be applied to any field of an {@link Entity}, - * {@link MappedSuperClass} or {@link Embeddable}. The specified indexer must be - * able to handle the indexing of value returned by the field's {@link Mapper}. + * Used to specify the Indexer to use for a given property/field of an entity. This annotation can + * be applied to any field of an {@link Entity}, {@link MappedSuperClass} or {@link Embeddable}. The + * specified indexer must be able to handle the indexing of value returned by the field's + * {@link Mapper}. * * @author Sai Pullabhotla * @@ -34,12 +34,12 @@ @Retention(RUNTIME) @Target(FIELD) public @interface PropertyIndexer { - /** - * Returns the indexer class. The specified class must have a public default - * (or no-argument constructor). - * - * @return the indexer class. - */ - Class value(); + /** + * Returns the indexer class. The specified class must have a public default (or no-argument + * constructor). + * + * @return the indexer class. + */ + Class value(); } diff --git a/src/main/java/com/jmethods/catatumbo/PropertyMapper.java b/src/main/java/com/jmethods/catatumbo/PropertyMapper.java index 9e5269d..45a8c8e 100644 --- a/src/main/java/com/jmethods/catatumbo/PropertyMapper.java +++ b/src/main/java/com/jmethods/catatumbo/PropertyMapper.java @@ -25,26 +25,24 @@ import com.jmethods.catatumbo.mappers.IntegerMapper; /** - * Specifies a custom {@link Mapper} for a field in the model class (Entity, - * Embedded or MappedSuperClass). Presence of this annotation on a field - * overrides the default {@link Mapper} used for the field type. + * Specifies a custom {@link Mapper} for a field in the model class (Entity, Embedded or + * MappedSuperClass). Presence of this annotation on a field overrides the default {@link Mapper} + * used for the field type. * *

* Customer Mappers must conform to the following specifications: *

*
    - *
  • The Customer Mapper class must implement the {@link Mapper} - * interface
  • + *
  • The Customer Mapper class must implement the {@link Mapper} interface
  • *
  • Custom Mappers must have a public constructor with a parameter of * {@link java.lang.reflect.Field}.
  • *
* *

- * Note that, unlike the built-in mappers where {@link Mapper} instances are - * reused where possible, custom mappers are created once for each field. To - * clarify this further, there is only one instance of {@link IntegerMapper} in - * the JVM that handles mapping of int/Integer fields in all entities, but - * that's not the same case with custom mappers. + * Note that, unlike the built-in mappers where {@link Mapper} instances are reused where possible, + * custom mappers are created once for each field. To clarify this further, there is only one + * instance of {@link IntegerMapper} in the JVM that handles mapping of int/Integer fields in all + * entities, but that's not the same case with custom mappers. *

* * @author Sai Pullabhotla @@ -54,11 +52,11 @@ @Target(FIELD) public @interface PropertyMapper { - /** - * The class that implements the {@link Mapper} interface. - * - * @return the class that implements the {@link Mapper} interface. - */ - Class value(); + /** + * The class that implements the {@link Mapper} interface. + * + * @return the class that implements the {@link Mapper} interface. + */ + Class value(); } diff --git a/src/main/java/com/jmethods/catatumbo/PropertyOverride.java b/src/main/java/com/jmethods/catatumbo/PropertyOverride.java index ddee31d..5218308 100644 --- a/src/main/java/com/jmethods/catatumbo/PropertyOverride.java +++ b/src/main/java/com/jmethods/catatumbo/PropertyOverride.java @@ -16,16 +16,15 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used to override mapping of a property. This annotation must be specified on - * the top-level entity to override any properties of {@link Embedded} objects - * or a {@link MappedSuperClass}. + * Used to override mapping of a property. This annotation must be specified on the top-level entity + * to override any properties of {@link Embedded} objects or a {@link MappedSuperClass}. * * @author Sai Pullabhotla * @@ -34,18 +33,18 @@ @Target(TYPE) public @interface PropertyOverride { - /** - * The name of the property whose mapping is to be overridden. - * - * @return name of the property whose mapping is to be overridden. - */ - String name(); + /** + * The name of the property whose mapping is to be overridden. + * + * @return name of the property whose mapping is to be overridden. + */ + String name(); - /** - * The override mapping information. - * - * @return override mapping information. - */ - Property property(); + /** + * The override mapping information. + * + * @return override mapping information. + */ + Property property(); } diff --git a/src/main/java/com/jmethods/catatumbo/PropertyOverrides.java b/src/main/java/com/jmethods/catatumbo/PropertyOverrides.java index 7555dfa..6ec27fa 100644 --- a/src/main/java/com/jmethods/catatumbo/PropertyOverrides.java +++ b/src/main/java/com/jmethods/catatumbo/PropertyOverrides.java @@ -16,16 +16,16 @@ package com.jmethods.catatumbo; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Used to override mappings of properties. Typically used if the entity - * contains {@link Embedded} objects or inherits a {@link MappedSuperClass}. - * This annotation must be applied to an {@link Entity} only. + * Used to override mappings of properties. Typically used if the entity contains {@link Embedded} + * objects or inherits a {@link MappedSuperClass}. This annotation must be applied to an + * {@link Entity} only. * * @author Sai Pullabhotla * @@ -34,11 +34,11 @@ @Target(TYPE) public @interface PropertyOverrides { - /** - * One or more property overrides. - * - * @return the property overrides - */ - PropertyOverride[] value(); + /** + * One or more property overrides. + * + * @return the property overrides + */ + PropertyOverride[] value(); } diff --git a/src/main/java/com/jmethods/catatumbo/QueryRequest.java b/src/main/java/com/jmethods/catatumbo/QueryRequest.java index d95bdb7..4b69460 100644 --- a/src/main/java/com/jmethods/catatumbo/QueryRequest.java +++ b/src/main/java/com/jmethods/catatumbo/QueryRequest.java @@ -20,45 +20,43 @@ import java.util.Map; /** - * QueryRequest objects hold the necessary information about a query to execute. - * The {@link EntityManager} executes the QueryRquest and returns the - * {@link QueryResponse}. + * QueryRequest objects hold the necessary information about a query to execute. The + * {@link EntityManager} executes the QueryRquest and returns the {@link QueryResponse}. * * @author Sai Pullabhotla * */ public interface QueryRequest { - /** - * Returns the GQL query - * - * @return the GQL query - */ - public String getQuery(); - - /** - * Returns the named bindings for this QueryRequest, if any. Implementations - * should never return null. - * - * @return the named bindings - */ - public Map getNamedBindings(); - - /** - * Returns the positional bindings of this QueryRequest, if any, - * Implementations should never return a null. - * - * @return the positional bindings - */ - public List getPositionalBindings(); - - /** - * Tells whether or not to allow literals (constant values or synthetic - * literals) in the query. - * - * @return true, if literals are to be allowed in the query; - * false, otherwise. - */ - public boolean isAllowLiterals(); + /** + * Returns the GQL query + * + * @return the GQL query + */ + public String getQuery(); + + /** + * Returns the named bindings for this QueryRequest, if any. Implementations should never return + * null. + * + * @return the named bindings + */ + public Map getNamedBindings(); + + /** + * Returns the positional bindings of this QueryRequest, if any, Implementations should never + * return a null. + * + * @return the positional bindings + */ + public List getPositionalBindings(); + + /** + * Tells whether or not to allow literals (constant values or synthetic literals) in the query. + * + * @return true, if literals are to be allowed in the query; false, + * otherwise. + */ + public boolean isAllowLiterals(); } diff --git a/src/main/java/com/jmethods/catatumbo/QueryResponse.java b/src/main/java/com/jmethods/catatumbo/QueryResponse.java index 343fa2f..db0f178 100644 --- a/src/main/java/com/jmethods/catatumbo/QueryResponse.java +++ b/src/main/java/com/jmethods/catatumbo/QueryResponse.java @@ -19,37 +19,36 @@ import java.util.List; /** - * Response to a query execution. When the {@link EntityManager} executes a - * {@link QueryRequest}, it returns the {@link QueryResponse}. + * Response to a query execution. When the {@link EntityManager} executes a {@link QueryRequest}, it + * returns the {@link QueryResponse}. * * @param - * the expected type of results + * the expected type of results * @author Sai Pullabhotla * */ public interface QueryResponse { - /** - * Returns the results from the query execution. - * - * @return the results from the query execution. - */ - List getResults(); + /** + * Returns the results from the query execution. + * + * @return the results from the query execution. + */ + List getResults(); - /** - * Returns the start cursor of the results. - * - * @return the start cursor of the results. - */ - DatastoreCursor getStartCursor(); + /** + * Returns the start cursor of the results. + * + * @return the start cursor of the results. + */ + DatastoreCursor getStartCursor(); - /** - * Returns the end cursor of the results. This can be used to navigate to - * the next page of results by setting this as the OFFSET for the next query - * request. - * - * @return the end cursor of the results. - */ - DatastoreCursor getEndCursor(); + /** + * Returns the end cursor of the results. This can be used to navigate to the next page of results + * by setting this as the OFFSET for the next query request. + * + * @return the end cursor of the results. + */ + DatastoreCursor getEndCursor(); } diff --git a/src/main/java/com/jmethods/catatumbo/SecondaryIndex.java b/src/main/java/com/jmethods/catatumbo/SecondaryIndex.java index ef182e2..1fc86b4 100644 --- a/src/main/java/com/jmethods/catatumbo/SecondaryIndex.java +++ b/src/main/java/com/jmethods/catatumbo/SecondaryIndex.java @@ -23,17 +23,16 @@ /** * This annotation can be specified on any simple field of an {@link Entity}, - * {@link MappedSuperClass} or {@link Embeddable}. The framework creates an - * additional property in the Datastore to index the annotated field/property. - * This is useful to create indexes on String types with a consistent case - * (UPPER or lower). The framework provides indexers for String types to create - * indexes in either lower case or upper case. Custom Indexers can be specified - * using the {@link PropertyIndexer} annotation. + * {@link MappedSuperClass} or {@link Embeddable}. The framework creates an additional property in + * the Datastore to index the annotated field/property. This is useful to create indexes on String + * types with a consistent case (UPPER or lower). The framework provides indexers for String types + * to create indexes in either lower case or upper case. Custom Indexers can be specified using the + * {@link PropertyIndexer} annotation. * *

- * Note: The indexing happens after a field is mapped to the - * Datastore using the {@link Mapper} associated to the field. The output - * produced by the {@link Mapper} is then fed to the {@link Indexer}. + * Note: The indexing happens after a field is mapped to the Datastore using the + * {@link Mapper} associated to the field. The output produced by the {@link Mapper} is then fed to + * the {@link Indexer}. *

* * @author Sai Pullabhotla @@ -43,30 +42,28 @@ @Target(ElementType.FIELD) public @interface SecondaryIndex { - /** - * Name of the secondary index. If not specified, the framework assigns a - * name by prefixing the original property name with a $ symbol. For example - * - - * - *
-	 * @SecondaryIndex
-	 * private String lastName;
-	 * 
- * - * This will create two properties in the Cloud Datastore - lastName and - * $lastName. The $lastName will have the last names in lower case to - * support case insensitive searching/sorting. - * - *
-	 * @SecondaryIndex
-	 * @Property(name = "lname")
-	 * private String lastName;
-	 * 
- * - * The above code will create two properties - lname and $lname. - * - * @return the name for the secondary index. - */ - String name() default ""; + /** + * Name of the secondary index. If not specified, the framework assigns a name by prefixing the + * original property name with a $ symbol. For example - + * + *
+   * @SecondaryIndex
+   * private String lastName;
+   * 
+ * + * This will create two properties in the Cloud Datastore - lastName and $lastName. The $lastName + * will have the last names in lower case to support case insensitive searching/sorting. + * + *
+   * @SecondaryIndex
+   * @Property(name = "lname")
+   * private String lastName;
+   * 
+ * + * The above code will create two properties - lname and $lname. + * + * @return the name for the secondary index. + */ + String name() default ""; } diff --git a/src/main/java/com/jmethods/catatumbo/Tenant.java b/src/main/java/com/jmethods/catatumbo/Tenant.java index f3a08d0..38e47e8 100644 --- a/src/main/java/com/jmethods/catatumbo/Tenant.java +++ b/src/main/java/com/jmethods/catatumbo/Tenant.java @@ -17,14 +17,14 @@ package com.jmethods.catatumbo; /** - * Used for setting/getting the namespace of current thread. This class - * maintains a {@link ThreadLocal} to store the current namespace. By default, - * the namespace is null. - * - * A typical use of this class in a web application involves creation of a - * ServletFilter that sets the namespace on each request processing thread. - * Below is an example filter that sets the namespace to the logged in user's - * name: + * Used for setting/getting the namespace of current thread. This class maintains a + * {@link ThreadLocal} to store the current namespace. By default, the namespace is + * null. + *

+ * A typical use of this class in a web application involves creation of a ServletFilter that sets + * the namespace on each request processing thread. Below is an example filter that sets the + * namespace to the logged in user's name: + *

* *
  * import java.io.IOException;
@@ -44,32 +44,32 @@
  * @WebFilter("/*")
  * public class NamespaceFilter implements Filter {
  * 
- * 	@Override
- * 	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- * 			throws IOException, ServletException {
- * 		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
- * 		String namespace = getCurrentUser(httpServletRequest);
- * 		Tenant.setNamespace(namespace);
- * 		chain.doFilter(request, response);
- * 	}
+ *   @Override
+ *   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ *       throws IOException, ServletException {
+ *     HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+ *     String namespace = getCurrentUser(httpServletRequest);
+ *     Tenant.setNamespace(namespace);
+ *     chain.doFilter(request, response);
+ *   }
  * 
- * 	// Replace the contents of this method to return the appropriate
- * 	// namespace. For example, you could use a domain based namespace.
- * 	private static String getCurrentUser(HttpServletRequest request) {
- * 		Principal principal = request.getUserPrincipal();
- * 		if (principal != null) {
- * 			return principal.getName();
- * 		}
- * 		return null;
- * 	}
+ *   // Replace the contents of this method to return the appropriate
+ *   // namespace. For example, you could use a domain based namespace.
+ *   private static String getCurrentUser(HttpServletRequest request) {
+ *     Principal principal = request.getUserPrincipal();
+ *     if (principal != null) {
+ *       return principal.getName();
+ *     }
+ *     return null;
+ *   }
  * 
- * 	@Override
- * 	public void destroy() {
- * 	}
+ *   @Override
+ *   public void destroy() {
+ *   }
  * 
- * 	@Override
- * 	public void init(FilterConfig fConfig) throws ServletException {
- * 	}
+ *   @Override
+ *   public void init(FilterConfig fConfig) throws ServletException {
+ *   }
  * 
  * }
  * 
@@ -80,30 +80,30 @@
  */
 public class Tenant {
 
-	/**
-	 * ThreadLocal for storing the namespace
-	 */
-	private static ThreadLocal threadNamespace = new ThreadLocal<>();
+  /**
+   * ThreadLocal for storing the namespace
+   */
+  private static ThreadLocal threadNamespace = new ThreadLocal<>();
 
-	/**
-	 * Returns the namespace.
-	 * 
-	 * @return the namespace. May return null.
-	 */
-	public static String getNamespace() {
-		return threadNamespace.get();
-	}
+  /**
+   * Returns the namespace.
+   * 
+   * @return the namespace. May return null.
+   */
+  public static String getNamespace() {
+    return threadNamespace.get();
+  }
 
-	/**
-	 * Sets the namespace to the given value. Set to null to use
-	 * the namespace with which the {@link EntityManager} was created. An empty
-	 * string sets the namespace to the default namespace.
-	 * 
-	 * @param namespace
-	 *            the namespace to set.
-	 */
-	public static void setNamespace(String namespace) {
-		threadNamespace.set(namespace);
-	}
+  /**
+   * Sets the namespace to the given value. Set to null to use the namespace with which
+   * the {@link EntityManager} was created. An empty string sets the namespace to the default
+   * namespace.
+   * 
+   * @param namespace
+   *          the namespace to set.
+   */
+  public static void setNamespace(String namespace) {
+    threadNamespace.set(namespace);
+  }
 
 }
diff --git a/src/main/java/com/jmethods/catatumbo/TransactionalTask.java b/src/main/java/com/jmethods/catatumbo/TransactionalTask.java
index 0d9a9ab..df51f5c 100644
--- a/src/main/java/com/jmethods/catatumbo/TransactionalTask.java
+++ b/src/main/java/com/jmethods/catatumbo/TransactionalTask.java
@@ -21,20 +21,21 @@
  * 
  * @author Sai Pullabhotla
  * @param 
+ *          the result type of this {@code TransactionalTask}.
  * @see EntityManager#executeInTransaction(TransactionalTask)
  *
  */
 public interface TransactionalTask {
 
-	/**
-	 * Executes the task. After the execute method finishes normally, the
-	 * transaction will be committed by the {@link EntityManager}. If the
-	 * execute method throws any exception, the transaction will be rolled back.
-	 * 
-	 * @param transaction
-	 *            the transaction to read from/write to the Cloud Datastore.
-	 * @return the result of execution
-	 */
-	T execute(DatastoreTransaction transaction);
+  /**
+   * Executes the task. After the execute method finishes normally, the transaction will be
+   * committed by the {@link EntityManager}. If the execute method throws any exception, the
+   * transaction will be rolled back.
+   * 
+   * @param transaction
+   *          the transaction to read from/write to the Cloud Datastore.
+   * @return the result of execution
+   */
+  T execute(DatastoreTransaction transaction);
 
 }
diff --git a/src/main/java/com/jmethods/catatumbo/Unmodeled.java b/src/main/java/com/jmethods/catatumbo/Unmodeled.java
index 261b9b6..91f1bd1 100644
--- a/src/main/java/com/jmethods/catatumbo/Unmodeled.java
+++ b/src/main/java/com/jmethods/catatumbo/Unmodeled.java
@@ -13,6 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package com.jmethods.catatumbo;
 
 import java.lang.annotation.ElementType;
@@ -22,14 +23,13 @@
 import java.util.Map;
 
 /**
- * NOT IMPLEMENTED YET. A {@link Map} field in an entity can be annotated with
- * this annotation to hold all unmodeled (or custom) fields. Only one field can
- * have this annotation in a given entity.
+ * NOT IMPLEMENTED YET. A {@link Map} field in an entity can be annotated with this annotation to
+ * hold all unmodeled (or custom) fields. Only one field can have this annotation in a given entity.
  * 
  * @author Sai Pullabhotla
  */
 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.FIELD)
 public @interface Unmodeled {
-
+  // Marker
 }
diff --git a/src/main/java/com/jmethods/catatumbo/UnsupportedConstructionStrategyException.java b/src/main/java/com/jmethods/catatumbo/UnsupportedConstructionStrategyException.java
index 04cf9f8..2736adb 100644
--- a/src/main/java/com/jmethods/catatumbo/UnsupportedConstructionStrategyException.java
+++ b/src/main/java/com/jmethods/catatumbo/UnsupportedConstructionStrategyException.java
@@ -25,20 +25,19 @@
  */
 public class UnsupportedConstructionStrategyException extends EntityManagerException {
 
-	/**
-	 * Serial version UID
-	 */
-	private static final long serialVersionUID = -1012347475989414105L;
+  /**
+   * Serial version UID
+   */
+  private static final long serialVersionUID = -1012347475989414105L;
 
-	/**
-	 * Creates a new instance of
-	 * {@code UnsupportedConstructionStrategyException}.
-	 * 
-	 * @param message
-	 *            the message
-	 */
-	public UnsupportedConstructionStrategyException(String message) {
-		super(message);
-	}
+  /**
+   * Creates a new instance of {@code UnsupportedConstructionStrategyException}.
+   * 
+   * @param message
+   *          the message
+   */
+  public UnsupportedConstructionStrategyException(String message) {
+    super(message);
+  }
 
 }
diff --git a/src/main/java/com/jmethods/catatumbo/UpdatedTimestamp.java b/src/main/java/com/jmethods/catatumbo/UpdatedTimestamp.java
index 4e7767e..c13481a 100644
--- a/src/main/java/com/jmethods/catatumbo/UpdatedTimestamp.java
+++ b/src/main/java/com/jmethods/catatumbo/UpdatedTimestamp.java
@@ -26,10 +26,9 @@
 import java.util.Date;
 
 /**
- * Annotation for automatically setting the entity's modification timestamp.
- * This annotation can be applied to a field of an {@link Entity} or
- * {@link MappedSuperClass}. Only one field can have this annotation in a given
- * Entity hierarchy.
+ * Annotation for automatically setting the entity's modification timestamp. This annotation can be
+ * applied to a field of an {@link Entity} or {@link MappedSuperClass}. Only one field can have this
+ * annotation in a given Entity hierarchy.
  * 
  * 

* Valid data types for the field include - @@ -44,29 +43,26 @@ * * *

- * The framework sets the field with this annotation during the following - * operations: + * The framework sets the field with this annotation during the following operations: *

* *
    - *
  • INSERT - Any variation of the insert methods automatically set the field - * with this annotation to the current JVM's timestamp. Furthermore, if the - * entity also has a field with {@link CreatedTimestamp} annotation, the - * framework ensures that both creation and modification timestamp are exactly - * equal.
  • - *
  • UPDATE - Any variation of the update methods set this field to the - * current timestamp of the JVM.
  • - *
  • UPSERT - Any variation of the upsert methods set this field to the - * current timestamp of the JVM.
  • + *
  • INSERT - Any variation of the insert methods automatically set the field with this annotation + * to the current JVM's timestamp. Furthermore, if the entity also has a field with + * {@link CreatedTimestamp} annotation, the framework ensures that both creation and modification + * timestamp are exactly equal.
  • + *
  • UPDATE - Any variation of the update methods set this field to the current timestamp of the + * JVM.
  • + *
  • UPSERT - Any variation of the upsert methods set this field to the current timestamp of the + * JVM.
  • *
* *

- * The field with this annotation is no different than any other property of the - * entity. This means, this field could also have the {@link Property} - * annotation and specify the property name to use in the Datastore as well as - * whether or not the property should be indexed. The field will be mapped using - * the specified {@link Mapper}, if a {@link PropertyMapper} is specified, - * otherwise a default mapper for the data type is used. + * The field with this annotation is no different than any other property of the entity. This means, + * this field could also have the {@link Property} annotation and specify the property name to use + * in the Datastore as well as whether or not the property should be indexed. The field will be + * mapped using the specified {@link Mapper}, if a {@link PropertyMapper} is specified, otherwise a + * default mapper for the data type is used. *

* * @author Sai Pullabhotla @@ -75,5 +71,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UpdatedTimestamp { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/Utility.java b/src/main/java/com/jmethods/catatumbo/Utility.java index 7964a82..8e872b8 100644 --- a/src/main/java/com/jmethods/catatumbo/Utility.java +++ b/src/main/java/com/jmethods/catatumbo/Utility.java @@ -27,68 +27,65 @@ */ public class Utility { - /** - * Creates a new instance of Utility. This exists to hide the - * implicit public constructor. - */ - private Utility() { - // Do nothing - } + /** + * Creates a new instance of Utility. This exists to hide the implicit public + * constructor. + */ + private Utility() { + // Do nothing + } - /** - * Closes the given Closeable. - * - * @param closeable - * the Closeable (e.g. InputStream, OutputStream, etc.) to close. - */ - public static void close(Closeable closeable) { - if (closeable != null) { - try { - closeable.close(); - } catch (IOException exp) { - // Ignore - } - } - } + /** + * Closes the given Closeable. + * + * @param closeable + * the Closeable (e.g. InputStream, OutputStream, etc.) to close. + */ + public static void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException exp) { + // Ignore + } + } + } - /** - * Tells whether or not the given input String is null or empty. - * - * @param input - * the input string to check - * @return true, if the given input is null or empty; - * otherwise, false. - */ - public static boolean isNullOrEmpty(String input) { - return input == null || input.trim().length() == 0; - } + /** + * Tells whether or not the given input String is null or empty. + * + * @param input + * the input string to check + * @return true, if the given input is null or empty; otherwise, false. + */ + public static boolean isNullOrEmpty(String input) { + return input == null || input.trim().length() == 0; + } - /** - * Throws a {@link NullPointerException} if the given input is - * null. - * - * @param input - * the input to check - */ - public static void ensureNotNull(Object input) { - if (input == null) { - throw new NullPointerException(); - } - } + /** + * Throws a {@link NullPointerException} if the given input is null. + * + * @param input + * the input to check + */ + public static void ensureNotNull(Object input) { + if (input == null) { + throw new NullPointerException(); + } + } - /** - * Throws a {@link NullPointerException} if the input is null. If the input - * is empty )input.trim().length() == 0, an - * {@link IllegalArgumentException} is thrown. - * - * @param input - * the input String to validate - */ - public static void ensureNotEmpty(String input) { - ensureNotNull(input); - if (input.trim().length() == 0) { - throw new IllegalArgumentException(); - } - } + /** + * Throws a {@link NullPointerException} if the input is null. If the input is empty + * )input.trim().length() == 0, an {@link IllegalArgumentException} is thrown. + * + * @param input + * the input String to validate + */ + public static void ensureNotEmpty(String input) { + ensureNotNull(input); + if (input.trim().length() == 0) { + throw new IllegalArgumentException(); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/Version.java b/src/main/java/com/jmethods/catatumbo/Version.java index 2111b00..84923ef 100644 --- a/src/main/java/com/jmethods/catatumbo/Version.java +++ b/src/main/java/com/jmethods/catatumbo/Version.java @@ -23,41 +23,35 @@ import java.lang.annotation.Target; /** - * Used to implement optimistic locking to prevent updates on a stale entity. - * This annotation can be applied to a single field in an entity hierarchy - * (Entity class and any MappedSuperClasses). The field type must be primitive - * long. Each time the entity is updated, the version property will - * be incremented by 1. When an entity containing a property with this - * annotation is updated, the EntityManager first starts a new transaction, - * fetches the current entity from the Datastore, makes sure the version is same - * as the one being updated. If they defer, {@link OptimisticLockException} will - * be thrown. Otherwise, the the entity will be updated by incrementing the - * version and the transaction is committed. + * Used to implement optimistic locking to prevent updates on a stale entity. This annotation can be + * applied to a single field in an entity hierarchy (Entity class and any MappedSuperClasses). The + * field type must be primitive long. Each time the entity is updated, the version + * property will be incremented by 1. When an entity containing a property with this annotation is + * updated, the EntityManager first starts a new transaction, fetches the current entity from the + * Datastore, makes sure the version is same as the one being updated. If they defer, + * {@link OptimisticLockException} will be thrown. Otherwise, the the entity will be updated by + * incrementing the version and the transaction is committed. * *

- * Entities that have a field with {@link Version} annotation must have a - * corresponding getter and setter method for the field. However, applications - * should never call the setter method. The field may also have {@link Property} - * annotation to specify the property name in the Cloud Datastore and whether or - * not the property should be indexed. + * Entities that have a field with {@link Version} annotation must have a corresponding getter and + * setter method for the field. However, applications should never call the setter method. The field + * may also have {@link Property} annotation to specify the property name in the Cloud Datastore and + * whether or not the property should be indexed. *

* *

- * When an entity containing this annotation is inserted into the Datastore, the - * initialized value is used as the initial version. For example, if you declare - * private long version; in your model class, when this entity is - * inserted, the version property is set to zero in the Datastore. If you need a - * different starting version, initialize the version field accordingly. For - * example, private long version=10L;. This will set the version - * property to 10 when inserting an entity. Subsequent updates to the entity - * increment the version by 1. + * When an entity containing this annotation is inserted into the Datastore, the initialized value + * is used as the initial version. For example, if you declare private long version; in + * your model class, when this entity is inserted, the version property is set to zero in the + * Datastore. If you need a different starting version, initialize the version field accordingly. + * For example, private long version=10L;. This will set the version property to 10 + * when inserting an entity. Subsequent updates to the entity increment the version by 1. *

* *

- * Note that the optimistic lock check and version increment only - * happens when the {@link DatastoreAccess#update(Object)} and - * {@link DatastoreAccess#update(java.util.List)} is called. Other methods that - * may potentially update the entities (e.g. UPSERT) will NOT perform the + * Note that the optimistic lock check and version increment only happens when the + * {@link DatastoreAccess#update(Object)} and {@link DatastoreAccess#update(java.util.List)} is + * called. Other methods that may potentially update the entities (e.g. UPSERT) will NOT perform the * optimistic lock check or increment the version. *

* @@ -67,5 +61,5 @@ @Retention(RUNTIME) @Target(FIELD) public @interface Version { - + // Marker } diff --git a/src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java index 2349b7e..0847e07 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java @@ -26,69 +26,66 @@ import com.jmethods.catatumbo.MappedSuperClass; /** - * Base class for holding the metadata of listeners defined in an - * {@link Entity}, {@link MappedSuperClass} or {@link EntityListener}. + * Base class for holding the metadata of listeners defined in an {@link Entity}, + * {@link MappedSuperClass} or {@link EntityListener}. * * @author Sai Pullabhotla * */ public class AbstractListenerMetadata { - /** - * The listener class to which this metadata belongs - */ - private Class listenerClass; + /** + * The listener class to which this metadata belongs + */ + private Class listenerClass; - /** - * Mapping of callback type to its callback method. Created lazily, if - * needed. - */ - private Map callbacks; + /** + * Mapping of callback type to its callback method. Created lazily, if needed. + */ + private Map callbacks; - /** - * Creates a new instance of AbstractListenerMetadata. - * - * @param listenerClass - * the listener class to which this metadata belongs. - */ - public AbstractListenerMetadata(Class listenerClass) { - this.listenerClass = listenerClass; - } + /** + * Creates a new instance of AbstractListenerMetadata. + * + * @param listenerClass + * the listener class to which this metadata belongs. + */ + public AbstractListenerMetadata(Class listenerClass) { + this.listenerClass = listenerClass; + } - /** - * Registers the given method as the callback method for the given event - * type. - * - * @param callbackType - * the callback type - * @param method - * the callback method - * @throws EntityManagerException - * if there was already a callback method for the given event - * type. - */ - public void putListener(CallbackType callbackType, Method method) { - if (callbacks == null) { - callbacks = new EnumMap<>(CallbackType.class); - } - Method oldMethod = callbacks.put(callbackType, method); - if (oldMethod != null) { - String format = "Class %s has at least two methods, %s and %s, with annotation of %s. " - + "At most one method is allowed for a given callback type. "; - String message = String.format(format, listenerClass.getName(), oldMethod.getName(), method.getName(), - callbackType.getAnnotationClass().getName()); - throw new EntityManagerException(message); - } - } + /** + * Registers the given method as the callback method for the given event type. + * + * @param callbackType + * the callback type + * @param method + * the callback method + * @throws EntityManagerException + * if there was already a callback method for the given event type. + */ + public void putListener(CallbackType callbackType, Method method) { + if (callbacks == null) { + callbacks = new EnumMap<>(CallbackType.class); + } + Method oldMethod = callbacks.put(callbackType, method); + if (oldMethod != null) { + String format = "Class %s has at least two methods, %s and %s, with annotation of %s. " + + "At most one method is allowed for a given callback type. "; + String message = String.format(format, listenerClass.getName(), oldMethod.getName(), + method.getName(), callbackType.getAnnotationClass().getName()); + throw new EntityManagerException(message); + } + } - /** - * Returns all defined callbacks. - * - * @return all defined callbacks. Returns null, if there are no - * callback methods defined in the listener class. - */ - public Map getCallbacks() { - return callbacks; - } + /** + * Returns all defined callbacks. + * + * @return all defined callbacks. Returns null, if there are no callback methods + * defined in the listener class. + */ + public Map getCallbacks() { + return callbacks; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/Cache.java b/src/main/java/com/jmethods/catatumbo/impl/Cache.java index 07e55a0..bf7ae6d 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/Cache.java +++ b/src/main/java/com/jmethods/catatumbo/impl/Cache.java @@ -24,91 +24,90 @@ * * @author Sai Pullabhotla * @param - * Type of keys in the cache + * Type of keys in the cache * @param - * Type of values in the cache + * Type of values in the cache * */ public class Cache { - /** - * A map to store the entries in the cache - */ - private Map map; + /** + * A map to store the entries in the cache + */ + private Map map; - /** - * Creates a new instance of Cache. - */ - public Cache() { - this(16, 0.75f); - } + /** + * Creates a new instance of Cache. + */ + public Cache() { + this(16, 0.75f); + } - /** - * Creates a new instance of Cache. - * - * @param initialSize - * initial size - */ - public Cache(int initialSize) { - this(initialSize, 0.75f); - } + /** + * Creates a new instance of Cache. + * + * @param initialSize + * initial size + */ + public Cache(int initialSize) { + this(initialSize, 0.75f); + } - /** - * Creates a new instance of Cache. - * - * @param initialSize - * initial size - * @param loadFactor - * load factor - */ - public Cache(int initialSize, float loadFactor) { - map = new ConcurrentHashMap<>(initialSize, loadFactor); - } + /** + * Creates a new instance of Cache. + * + * @param initialSize + * initial size + * @param loadFactor + * load factor + */ + public Cache(int initialSize, float loadFactor) { + map = new ConcurrentHashMap<>(initialSize, loadFactor); + } - /** - * Returns the cached value for the given key. - * - * @param key - * the key - * @return the cached value of the given key. Returns null, if - * the given key does not exist in this cache. - */ - public V get(K key) { - return map.get(key); - } + /** + * Returns the cached value for the given key. + * + * @param key + * the key + * @return the cached value of the given key. Returns null, if the given key does not + * exist in this cache. + */ + public V get(K key) { + return map.get(key); + } - /** - * Puts the given entry into this cache. - * - * @param key - * the key - * @param value - * the value - * @return previous value, if any, for the given key. - */ - public V put(K key, V value) { - return map.put(key, value); - } + /** + * Puts the given entry into this cache. + * + * @param key + * the key + * @param value + * the value + * @return previous value, if any, for the given key. + */ + public V put(K key, V value) { + return map.put(key, value); + } - /** - * Checks if the give key is in this cache. - * - * @param key - * the key - * @return true, if the given key exists in the cache; - * false, otherwise. - */ - public boolean containsKey(K key) { - return map.containsKey(key); - } + /** + * Checks if the give key is in this cache. + * + * @param key + * the key + * @return true, if the given key exists in the cache; false, otherwise. + */ + public boolean containsKey(K key) { + return map.containsKey(key); + } - /** - * Returns the size of this cache. - * - * @return the size of this cache. - */ - public int size() { - return map.size(); - } + /** + * Returns the size of this cache. + * + * @return the size of this cache. + */ + public int size() { + return map.size(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/CallbackMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/CallbackMetadata.java index 1027b87..67344ea 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/CallbackMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/CallbackMetadata.java @@ -20,109 +20,109 @@ import java.util.Objects; /** - * Objects of this class contain the metadata of a callback event (e.g. - * PreInsert). + * Objects of this class contain the metadata of a callback event (e.g. PreInsert). * * @author Sai Pullabhotla * */ public class CallbackMetadata { - /** - * Listener type - */ - private final EntityListenerType listenerType; - - /** - * Callback type - */ - private final CallbackType callbackType; - - /** - * Callback method - */ - private final Method callbackMethod; - - /** - * Listener class - */ - private final Class listenerClass; - - /** - * Creates a new instance of CallbackMetadata. - * - * @param listenerType - * the listener type - * @param callbackType - * the callback type - * @param callbackMethod - * the callback method - * - */ - public CallbackMetadata(EntityListenerType listenerType, CallbackType callbackType, Method callbackMethod) { - this.listenerType = listenerType; - this.callbackType = callbackType; - this.callbackMethod = callbackMethod; - this.listenerClass = callbackMethod.getDeclaringClass(); - } - - /** - * Returns the listener type. - * - * @return the listener type. - */ - public EntityListenerType getListenerType() { - return listenerType; - } - - /** - * Returns the callback type. - * - * @return the callback type. - */ - public CallbackType getCallbackType() { - return callbackType; - } - - /** - * Returns the callback method. - * - * @return the callback method. - */ - public Method getCallbackMethod() { - return callbackMethod; - } - - /** - * Returns the listener class. - * - * @return the listener class. - */ - public Class getListenerClass() { - return listenerClass; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !(obj instanceof CallbackMetadata)) { - return false; - } - CallbackMetadata that = (CallbackMetadata) obj; - return this.listenerType == that.listenerType && this.callbackType == that.callbackType - && this.callbackMethod.equals(that.callbackMethod); - } - - @Override - public int hashCode() { - return Objects.hash(listenerType, callbackType, callbackMethod); - } - - @Override - public String toString() { - return callbackType + "->" + callbackMethod; - } + /** + * Listener type + */ + private final EntityListenerType listenerType; + + /** + * Callback type + */ + private final CallbackType callbackType; + + /** + * Callback method + */ + private final Method callbackMethod; + + /** + * Listener class + */ + private final Class listenerClass; + + /** + * Creates a new instance of CallbackMetadata. + * + * @param listenerType + * the listener type + * @param callbackType + * the callback type + * @param callbackMethod + * the callback method + * + */ + public CallbackMetadata(EntityListenerType listenerType, CallbackType callbackType, + Method callbackMethod) { + this.listenerType = listenerType; + this.callbackType = callbackType; + this.callbackMethod = callbackMethod; + this.listenerClass = callbackMethod.getDeclaringClass(); + } + + /** + * Returns the listener type. + * + * @return the listener type. + */ + public EntityListenerType getListenerType() { + return listenerType; + } + + /** + * Returns the callback type. + * + * @return the callback type. + */ + public CallbackType getCallbackType() { + return callbackType; + } + + /** + * Returns the callback method. + * + * @return the callback method. + */ + public Method getCallbackMethod() { + return callbackMethod; + } + + /** + * Returns the listener class. + * + * @return the listener class. + */ + public Class getListenerClass() { + return listenerClass; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !(obj instanceof CallbackMetadata)) { + return false; + } + CallbackMetadata that = (CallbackMetadata) obj; + return this.listenerType == that.listenerType && this.callbackType == that.callbackType + && this.callbackMethod.equals(that.callbackMethod); + } + + @Override + public int hashCode() { + return Objects.hash(listenerType, callbackType, callbackMethod); + } + + @Override + public String toString() { + return callbackType + "->" + callbackMethod; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/CallbackType.java b/src/main/java/com/jmethods/catatumbo/impl/CallbackType.java index ebae50e..acc396f 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/CallbackType.java +++ b/src/main/java/com/jmethods/catatumbo/impl/CallbackType.java @@ -36,73 +36,73 @@ */ public enum CallbackType { - /** - * Pre insert - */ - PRE_INSERT(PreInsert.class), - - /** - * Pre update - */ - PRE_UPDATE(PreUpdate.class), - - /** - * Pre upsert - */ - PRE_UPSERT(PreUpsert.class), - - /** - * Pre delete - */ - PRE_DELETE(PreDelete.class), - - /** - * Post load - */ - POST_LOAD(PostLoad.class), - - /** - * Post insert - */ - POST_INSERT(PostInsert.class), - - /** - * Post update - */ - POST_UPDATE(PostUpdate.class), - - /** - * Post upsert - */ - POST_UPSERT(PostUpsert.class), - - /** - * Post delete - */ - POST_DELETE(PostDelete.class); - - /** - * Annotation class for this callback type - */ - private final Class annotationClass; - - /** - * Creates a new instance of CallbackEventType. - * - * @param annotationClass - * the annotation for this callback type - */ - private CallbackType(Class annotationClass) { - this.annotationClass = annotationClass; - } - - /** - * Returns the annotation class for this callback type. - * - * @return the annotation class for this callback type. - */ - public Class getAnnotationClass() { - return annotationClass; - } + /** + * Pre insert + */ + PRE_INSERT(PreInsert.class), + + /** + * Pre update + */ + PRE_UPDATE(PreUpdate.class), + + /** + * Pre upsert + */ + PRE_UPSERT(PreUpsert.class), + + /** + * Pre delete + */ + PRE_DELETE(PreDelete.class), + + /** + * Post load + */ + POST_LOAD(PostLoad.class), + + /** + * Post insert + */ + POST_INSERT(PostInsert.class), + + /** + * Post update + */ + POST_UPDATE(PostUpdate.class), + + /** + * Post upsert + */ + POST_UPSERT(PostUpsert.class), + + /** + * Post delete + */ + POST_DELETE(PostDelete.class); + + /** + * Annotation class for this callback type + */ + private final Class annotationClass; + + /** + * Creates a new instance of CallbackEventType. + * + * @param annotationClass + * the annotation for this callback type + */ + private CallbackType(Class annotationClass) { + this.annotationClass = annotationClass; + } + + /** + * Returns the annotation class for this callback type. + * + * @return the annotation class for this callback type. + */ + public Class getAnnotationClass() { + return annotationClass; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ConstructorIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/ConstructorIntrospector.java index df8734a..e6513ec 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ConstructorIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ConstructorIntrospector.java @@ -22,146 +22,148 @@ import com.jmethods.catatumbo.UnsupportedConstructionStrategyException; /** - * Introspector for persistence class construction/instantiation/building - * mechanism. Metadata of the introspected classes will be cached for future - * use. + * Introspector for persistence class construction/instantiation/building mechanism. Metadata of the + * introspected classes will be cached for future use. * * @author Sai Pullabhotla * */ public class ConstructorIntrospector { - /** - * Cache of previously introspected classes - */ - private static final Cache, ConstructorMetadata> cache = new Cache<>(64); - - /** - * Method name for producing an instance of Persistence class from the - * corresponding Builder - */ - public static final String METHOD_NAME_BUILD = "build"; - - /** - * First of the supported method names to produce a new Builder for a - * persistence class - */ - public static final String METHOD_NAME_NEW_BUILDER = "newBuilder"; - - /** - * Second/Last of the supported method names to produce a new Builder for a - * persistence class - */ - public static final String METHOD_NAME_BUILDER = "builder"; - - /** - * Valid/supported method names for getting a new Builder for a Persistence - * class - */ - private static final String[] NEW_BUILDER_METHOD_NAMES = { METHOD_NAME_NEW_BUILDER, METHOD_NAME_BUILDER }; - - /** - * Builder for the {@code ConstructorMetadata} - */ - private ConstructorMetadata.Builder metadataBuilder; - - /** - * Class being introspected - */ - private Class clazz; - - /** - * Creates a new instance of {@code ConstructorIntrospector}. - */ - private ConstructorIntrospector(Class clazz) { - this.clazz = clazz; - } - - /** - * Introspects the given Persistence class and returns the - * {@link ConstructorMetadata}. - * - * @param clazz - * the class to introspect - * @return the {@link ConstructorMetadata}. - */ - public static ConstructorMetadata introspect(Class clazz) { - ConstructorMetadata metadata = cache.get(clazz); - if (metadata != null) { - return metadata; - } - return loadMetadata(clazz); - } - - /** - * Loads the metadata, if it does not already exist in the cache. - * - * @param clazz - * the class to introspect - * @return the metadata - */ - private static ConstructorMetadata loadMetadata(Class clazz) { - synchronized (clazz) { - ConstructorMetadata metadata = cache.get(clazz); - if (metadata == null) { - ConstructorIntrospector introspector = new ConstructorIntrospector(clazz); - introspector.process(); - metadata = introspector.metadataBuilder.build(); - cache.put(clazz, metadata); - } - return metadata; - } - } - - /** - * Introspects the class and builds the metadata. - */ - private void process() { - metadataBuilder = ConstructorMetadata.newBuilder().setClazz(clazz); - MethodHandle mh = IntrospectionUtils.findDefaultConstructor(clazz); - if (mh != null) { - metadataBuilder.setConstructionStrategy(ConstructorMetadata.ConstructionStrategy.CLASSIC) - .setConstructorMethodHandle(mh); - // We have everything we need for the classic pattern with a default - // constructor and accessor/mutator methods, more validations will - // follow. - return; - } - // Now we check for Builder pattern usage - mh = findNewBuilderMethod(clazz); - if (mh == null) { - final String pattern = "Class %s requires a public no-arg constructor or a public static method that " - + "returns a corresponding Builder instance. The name of the static method can either be %s or %s"; - String error = String.format(pattern, clazz.getName(), METHOD_NAME_NEW_BUILDER, METHOD_NAME_BUILDER); - throw new UnsupportedConstructionStrategyException(error); - } - Class builderClass = mh.type().returnType(); - metadataBuilder.setConstructionStrategy(ConstructorMetadata.ConstructionStrategy.BUILDER) - .setConstructorMethodHandle(mh).setBuilderClass(builderClass); - MethodHandle buildMethodHandle = IntrospectionUtils.findInstanceMethod(builderClass, METHOD_NAME_BUILD, clazz); - if (buildMethodHandle == null) { - String pattern = "Class %s requires a public instance method, %s, with a return type of %s"; - throw new EntityManagerException(String.format(pattern, builderClass.getName(), METHOD_NAME_BUILD, clazz)); - } - metadataBuilder.setBuildMethodHandle(buildMethodHandle); - } - - /** - * Finds and returns a method handle for new instance of a Builder class. - * - * @param clazz - * the persistence class - * @return the method handle for the newBuilder/builder method - */ - public static MethodHandle findNewBuilderMethod(Class clazz) { - MethodHandle mh = null; - for (String methodName : NEW_BUILDER_METHOD_NAMES) { - mh = IntrospectionUtils.findStaticMethod(clazz, methodName, Object.class); - if (mh != null) { - break; - } - } - return mh; - } + /** + * Cache of previously introspected classes + */ + private static final Cache, ConstructorMetadata> cache = new Cache<>(64); + + /** + * Method name for producing an instance of Persistence class from the corresponding Builder + */ + public static final String METHOD_NAME_BUILD = "build"; + + /** + * First of the supported method names to produce a new Builder for a persistence class + */ + public static final String METHOD_NAME_NEW_BUILDER = "newBuilder"; + + /** + * Second/Last of the supported method names to produce a new Builder for a persistence class + */ + public static final String METHOD_NAME_BUILDER = "builder"; + + /** + * Valid/supported method names for getting a new Builder for a Persistence class + */ + private static final String[] NEW_BUILDER_METHOD_NAMES = { METHOD_NAME_NEW_BUILDER, + METHOD_NAME_BUILDER }; + + /** + * Builder for the {@code ConstructorMetadata} + */ + private ConstructorMetadata.Builder metadataBuilder; + + /** + * Class being introspected + */ + private Class clazz; + + /** + * Creates a new instance of {@code ConstructorIntrospector}. + * + * @param clazz + * the class to introspect + */ + private ConstructorIntrospector(Class clazz) { + this.clazz = clazz; + } + + /** + * Introspects the given Persistence class and returns the {@link ConstructorMetadata}. + * + * @param clazz + * the class to introspect + * @return the {@link ConstructorMetadata}. + */ + public static ConstructorMetadata introspect(Class clazz) { + ConstructorMetadata metadata = cache.get(clazz); + if (metadata != null) { + return metadata; + } + return loadMetadata(clazz); + } + + /** + * Loads the metadata, if it does not already exist in the cache. + * + * @param clazz + * the class to introspect + * @return the metadata + */ + private static ConstructorMetadata loadMetadata(Class clazz) { + synchronized (clazz) { + ConstructorMetadata metadata = cache.get(clazz); + if (metadata == null) { + ConstructorIntrospector introspector = new ConstructorIntrospector(clazz); + introspector.process(); + metadata = introspector.metadataBuilder.build(); + cache.put(clazz, metadata); + } + return metadata; + } + } + + /** + * Introspects the class and builds the metadata. + */ + private void process() { + metadataBuilder = ConstructorMetadata.newBuilder().setClazz(clazz); + MethodHandle mh = IntrospectionUtils.findDefaultConstructor(clazz); + if (mh != null) { + metadataBuilder.setConstructionStrategy(ConstructorMetadata.ConstructionStrategy.CLASSIC) + .setConstructorMethodHandle(mh); + // We have everything we need for the classic pattern with a default + // constructor and accessor/mutator methods, more validations will + // follow. + return; + } + // Now we check for Builder pattern usage + mh = findNewBuilderMethod(clazz); + if (mh == null) { + final String pattern = "Class %s requires a public no-arg constructor or a public static " + + "method that returns a corresponding Builder instance. The name of the static method " + + "can either be %s or %s"; + String error = String.format(pattern, clazz.getName(), METHOD_NAME_NEW_BUILDER, + METHOD_NAME_BUILDER); + throw new UnsupportedConstructionStrategyException(error); + } + Class builderClass = mh.type().returnType(); + metadataBuilder.setConstructionStrategy(ConstructorMetadata.ConstructionStrategy.BUILDER) + .setConstructorMethodHandle(mh).setBuilderClass(builderClass); + MethodHandle buildMethodHandle = IntrospectionUtils.findInstanceMethod(builderClass, + METHOD_NAME_BUILD, clazz); + if (buildMethodHandle == null) { + String pattern = "Class %s requires a public instance method, %s, with a return type of %s"; + throw new EntityManagerException( + String.format(pattern, builderClass.getName(), METHOD_NAME_BUILD, clazz)); + } + metadataBuilder.setBuildMethodHandle(buildMethodHandle); + } + + /** + * Finds and returns a method handle for new instance of a Builder class. + * + * @param clazz + * the persistence class + * @return the method handle for the newBuilder/builder method + */ + public static MethodHandle findNewBuilderMethod(Class clazz) { + MethodHandle mh = null; + for (String methodName : NEW_BUILDER_METHOD_NAMES) { + mh = IntrospectionUtils.findStaticMethod(clazz, methodName, Object.class); + if (mh != null) { + break; + } + } + return mh; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ConstructorMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/ConstructorMetadata.java index 3cb5b29..c562427 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ConstructorMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ConstructorMetadata.java @@ -26,272 +26,255 @@ */ public class ConstructorMetadata { - /** - * The strategy to use for constructing/instantiating/building a persistence - * object - * - * @author Sai Pullabhotla - * - */ - public enum ConstructionStrategy { - /** - * Classic design pattern - using the default constructor and - * accessor/mutator methods per standard Java Beans convention. - */ - CLASSIC, - - /** - * Builder design pattern - if the persistence class does not have a - * public no-arg constructor, but has a static newBuilder/builder - * method. - */ - BUILDER; - } - - /** - * The class to which this metadata belongs - */ - private final Class clazz; - - /** - * The construction strategy to use for creating/building instances of this - * persistence class - */ - private final ConstructionStrategy constructionStrategy; - - /** - * A method handle for getting an instance of the persistence class. This - * method handle may be a handle to the default constructor or to the static - * newBuilder method. - */ - private final MethodHandle constructorMethodHandle; - - /** - * Builder class, if construction strategy is BUILDER - */ - private final Class builderClass; - - /** - * A method handle for building the final persistence object when using the - * BUILDER strategy. - */ - private final MethodHandle buildMethodHandle; - - /** - * Creates a new instance of {@code ConstructionMetadata}. - * - * @param builder - * the {@code Builder} from which to create this metadata - */ - private ConstructorMetadata(Builder builder) { - this.clazz = builder.clazz; - this.constructionStrategy = builder.constructionStrategy; - this.constructorMethodHandle = builder.constructorMethodHandle; - this.builderClass = builder.builderClass; - this.buildMethodHandle = builder.buildMethodHandle; - } - - /** - * Returns the class to which this metadata belongs. - * - * @return the class to which this metadata belongs. - */ - public Class getClazz() { - return clazz; - } - - /** - * Returns the strategy used for constructing/building instances of the - * model class to which this metadata belongs. - * - * @return the strategy used for constructing/building instances of the - * model class to which this metadata belongs. - */ - public ConstructionStrategy getConstructionStrategy() { - return constructionStrategy; - } - - /** - * Returns the method handle for constructing a new instance of model class - * or its Builder class. - * - * @return the methodHandle the method handle for constructing a new - * instance of model class or its Builder class. - */ - public MethodHandle getConstructorMethodHandle() { - return constructorMethodHandle; - } - - /** - * Returns the Builder class for the class to which this metadata belongs. - * - * @return the Builder class for the class to which this metadata belongs. - * May be {@code null}, if not using the BUILDER strategy. - */ - public Class getBuilderClass() { - return builderClass; - } - - /** - * Returns the method handle for building the final persistence object from - * its Builder. - * - * @return the method handle for building the final persistence object from - * its Builder. May be {@code null}, if not using the Builder - * strategy. - */ - public MethodHandle getBuildMethodHandle() { - return buildMethodHandle; - } - - /** - * Tells whether or not the persistence class represented by this metadata - * using the {@link ConstructionStrategy#CLASSIC} strategy. - * - * @return {@code true} if the persistence class using the - * {@link ConstructionStrategy#CLASSIC} strategy; {@code false}, - * otherwise. - */ - public final boolean isClassicConstructionStrategy() { - return constructionStrategy == ConstructionStrategy.CLASSIC; - } - - /** - * Tells whether or not the persistence class represented by this metadata - * using the {@link ConstructionStrategy#BUILDER} strategy. - * - * @return {@code true} if the persistence class using the - * {@link ConstructionStrategy#BUILDER} strategy; {@code false}, - * otherwise. - */ - public final boolean isBuilderConstructionStrategy() { - return constructionStrategy == ConstructionStrategy.BUILDER; - } - - /** - * Creates and returns a new {@link Builder} for building a - * {@link ConstructorMetadata}. - * - * @return a new {@link Builder} for building a {@link ConstructorMetadata}. - */ - public static Builder newBuilder() { - return new Builder(); - } - - /** - * Builder for creating {@link ConstructorMetadata}. - * - * @author Sai Pullabhotla - * - */ - public static class Builder { - /** - * @see ConstructorMetadata#clazz - */ - private Class clazz; - - /** - * @see ConstructorMetadata#constructionStrategy - */ - private ConstructionStrategy constructionStrategy; - - /** - * @see ConstructorMetadata#constructorMethodHandle - */ - private MethodHandle constructorMethodHandle; - - /** - * @see ConstructorMetadata#builderClass - */ - private Class builderClass; - - /** - * @see ConstructorMetadata#buildMethodHandle - */ - private MethodHandle buildMethodHandle; - - /** - * Creates a new instance of {@code Builder}. - */ - private Builder() { - // Do nothing - } - - /** - * Sets the persistence class. - * - * @param clazz - * the persistence class. - * @return this {@link Builder} - */ - public Builder setClazz(Class clazz) { - this.clazz = clazz; - return this; - } - - /** - * Sets the constructor strategy. - * - * @param constructionStrategy - * the construction strategy. - * @return this {@code Builder} instance - */ - public Builder setConstructionStrategy(ConstructionStrategy constructionStrategy) { - this.constructionStrategy = constructionStrategy; - return this; - } - - /** - * Sets the method handle for constructing the persistence object or its - * builder object. - * - * @param constructorMethodHandle - * the method handle for constructing the persistence object - * or its builder object. - * @return this {@code Builder} instance - */ - public Builder setConstructorMethodHandle(MethodHandle constructorMethodHandle) { - this.constructorMethodHandle = constructorMethodHandle; - return this; - } - - /** - * Sets the builder class. - * - * @param builderClass - * the builder class. - * @return this {@code Builder} instance - */ - public Builder setBuilderClass(Class builderClass) { - this.builderClass = builderClass; - return this; - } - - /** - * Sets the method handle for building the persistence object from its - * builder. - * - * @param buildMethodHandle - * the method handle for building the persistence object from - * its builder. - * @return this {@code Builder} instance - */ - public Builder setBuildMethodHandle(MethodHandle buildMethodHandle) { - this.buildMethodHandle = buildMethodHandle; - return this; - } - - /** - * Creates and returns a new {@link ConstructorMetadata} from this - * {@code Builder}'s state. - * - * @return a new {@link ConstructorMetadata} from this {@code Builder}'s - * state. - */ - public ConstructorMetadata build() { - return new ConstructorMetadata(this); - } - - } + /** + * The strategy to use for constructing/instantiating/building a persistence object + * + * @author Sai Pullabhotla + * + */ + public enum ConstructionStrategy { + /** + * Classic design pattern - using the default constructor and accessor/mutator methods per + * standard Java Beans convention. + */ + CLASSIC, + + /** + * Builder design pattern - if the persistence class does not have a public no-arg constructor, + * but has a static newBuilder/builder method. + */ + BUILDER; + } + + /** + * The class to which this metadata belongs + */ + private final Class clazz; + + /** + * The construction strategy to use for creating/building instances of this persistence class + */ + private final ConstructionStrategy constructionStrategy; + + /** + * A method handle for getting an instance of the persistence class. This method handle may be a + * handle to the default constructor or to the static newBuilder method. + */ + private final MethodHandle constructorMethodHandle; + + /** + * Builder class, if construction strategy is BUILDER + */ + private final Class builderClass; + + /** + * A method handle for building the final persistence object when using the BUILDER strategy. + */ + private final MethodHandle buildMethodHandle; + + /** + * Creates a new instance of {@code ConstructionMetadata}. + * + * @param builder + * the {@code Builder} from which to create this metadata + */ + private ConstructorMetadata(Builder builder) { + this.clazz = builder.clazz; + this.constructionStrategy = builder.constructionStrategy; + this.constructorMethodHandle = builder.constructorMethodHandle; + this.builderClass = builder.builderClass; + this.buildMethodHandle = builder.buildMethodHandle; + } + + /** + * Returns the class to which this metadata belongs. + * + * @return the class to which this metadata belongs. + */ + public Class getClazz() { + return clazz; + } + + /** + * Returns the strategy used for constructing/building instances of the model class to which this + * metadata belongs. + * + * @return the strategy used for constructing/building instances of the model class to which this + * metadata belongs. + */ + public ConstructionStrategy getConstructionStrategy() { + return constructionStrategy; + } + + /** + * Returns the method handle for constructing a new instance of model class or its Builder class. + * + * @return the methodHandle the method handle for constructing a new instance of model class or + * its Builder class. + */ + public MethodHandle getConstructorMethodHandle() { + return constructorMethodHandle; + } + + /** + * Returns the Builder class for the class to which this metadata belongs. + * + * @return the Builder class for the class to which this metadata belongs. May be {@code null}, if + * not using the BUILDER strategy. + */ + public Class getBuilderClass() { + return builderClass; + } + + /** + * Returns the method handle for building the final persistence object from its Builder. + * + * @return the method handle for building the final persistence object from its Builder. May be + * {@code null}, if not using the Builder strategy. + */ + public MethodHandle getBuildMethodHandle() { + return buildMethodHandle; + } + + /** + * Tells whether or not the persistence class represented by this metadata using the + * {@link ConstructionStrategy#CLASSIC} strategy. + * + * @return {@code true} if the persistence class using the {@link ConstructionStrategy#CLASSIC} + * strategy; {@code false}, otherwise. + */ + public final boolean isClassicConstructionStrategy() { + return constructionStrategy == ConstructionStrategy.CLASSIC; + } + + /** + * Tells whether or not the persistence class represented by this metadata using the + * {@link ConstructionStrategy#BUILDER} strategy. + * + * @return {@code true} if the persistence class using the {@link ConstructionStrategy#BUILDER} + * strategy; {@code false}, otherwise. + */ + public final boolean isBuilderConstructionStrategy() { + return constructionStrategy == ConstructionStrategy.BUILDER; + } + + /** + * Creates and returns a new {@link Builder} for building a {@link ConstructorMetadata}. + * + * @return a new {@link Builder} for building a {@link ConstructorMetadata}. + */ + public static Builder newBuilder() { + return new Builder(); + } + + /** + * Builder for creating {@link ConstructorMetadata}. + * + * @author Sai Pullabhotla + * + */ + public static class Builder { + /** + * @see ConstructorMetadata#clazz + */ + private Class clazz; + + /** + * @see ConstructorMetadata#constructionStrategy + */ + private ConstructionStrategy constructionStrategy; + + /** + * @see ConstructorMetadata#constructorMethodHandle + */ + private MethodHandle constructorMethodHandle; + + /** + * @see ConstructorMetadata#builderClass + */ + private Class builderClass; + + /** + * @see ConstructorMetadata#buildMethodHandle + */ + private MethodHandle buildMethodHandle; + + /** + * Creates a new instance of {@code Builder}. + */ + private Builder() { + // Do nothing + } + + /** + * Sets the persistence class. + * + * @param clazz + * the persistence class. + * @return this {@link Builder} + */ + public Builder setClazz(Class clazz) { + this.clazz = clazz; + return this; + } + + /** + * Sets the constructor strategy. + * + * @param constructionStrategy + * the construction strategy. + * @return this {@code Builder} instance + */ + public Builder setConstructionStrategy(ConstructionStrategy constructionStrategy) { + this.constructionStrategy = constructionStrategy; + return this; + } + + /** + * Sets the method handle for constructing the persistence object or its builder object. + * + * @param constructorMethodHandle + * the method handle for constructing the persistence object or its builder object. + * @return this {@code Builder} instance + */ + public Builder setConstructorMethodHandle(MethodHandle constructorMethodHandle) { + this.constructorMethodHandle = constructorMethodHandle; + return this; + } + + /** + * Sets the builder class. + * + * @param builderClass + * the builder class. + * @return this {@code Builder} instance + */ + public Builder setBuilderClass(Class builderClass) { + this.builderClass = builderClass; + return this; + } + + /** + * Sets the method handle for building the persistence object from its builder. + * + * @param buildMethodHandle + * the method handle for building the persistence object from its builder. + * @return this {@code Builder} instance + */ + public Builder setBuildMethodHandle(MethodHandle buildMethodHandle) { + this.buildMethodHandle = buildMethodHandle; + return this; + } + + /** + * Creates and returns a new {@link ConstructorMetadata} from this {@code Builder}'s state. + * + * @return a new {@link ConstructorMetadata} from this {@code Builder}'s state. + */ + public ConstructorMetadata build() { + return new ConstructorMetadata(this); + } + + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DatastoreUtils.java b/src/main/java/com/jmethods/catatumbo/impl/DatastoreUtils.java index 1788c5e..3a58c8c 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DatastoreUtils.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DatastoreUtils.java @@ -40,207 +40,206 @@ */ class DatastoreUtils { - /** - * Error code from the Datastore when an update operation fails because - * entity with the specified key does not exist. - */ - private static final int ERROR_CODE_ENTITY_NOT_FOUND = 5; - - /** - * Error code from the Datastore when an insert or put operation fails - * because another entity with the same key already exists. - */ - private static final int ERROR_CODE_ENTITY_ALREADY_EXISTS = 6; - - /** - * Hide the implicit constructor - */ - private DatastoreUtils() { - // Do nothing. - } - - /** - * Converts the given list of native entities to a list of model objects of - * given type, entityClass. - * - * @param entityClass - * the entity class - * @param nativeEntities - * native entities to convert - * @return the list of model objects - */ - static List toEntities(Class entityClass, List nativeEntities) { - if (nativeEntities == null || nativeEntities.isEmpty()) { - return new ArrayList<>(); - } - List entities = new ArrayList<>(nativeEntities.size()); - for (Entity nativeEntity : nativeEntities) { - E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); - entities.add(entity); - } - return entities; - } - - /** - * Converts the given array of native entities to a list of model objects of - * given type, entityClass. - * - * @param entityClass - * the entity class - * @param nativeEntities - * native entities to convert - * @return the list of model objects - */ - static List toEntities(Class entityClass, Entity[] nativeEntities) { - if (nativeEntities == null || nativeEntities.length == 0) { - return new ArrayList<>(); - } - return toEntities(entityClass, Arrays.asList(nativeEntities)); - } - - /** - * Converts the given list of model objects to an array of FullEntity - * objects. - * - * @param entities - * the model objects to convert. - * @param entityManager - * the entity manager - * @param intent - * the intent of marshalling - * @return the equivalent FullEntity array - */ - static FullEntity[] toNativeFullEntities(List entities, DefaultEntityManager entityManager, - Marshaller.Intent intent) { - FullEntity[] nativeEntities = new FullEntity[entities.size()]; - for (int i = 0; i < entities.size(); i++) { - nativeEntities[i] = (FullEntity) Marshaller.marshal(entityManager, entities.get(i), intent); - } - return nativeEntities; - } - - /** - * Converts the given list of model objects to an array of native Entity - * objects. - * - * @param entities - * the model objects to convert. - * @param entityManager - * the entity manager - * @return the equivalent Entity array - */ - static Entity[] toNativeEntities(List entities, DefaultEntityManager entityManager, Marshaller.Intent intent) { - Entity[] nativeEntities = new Entity[entities.size()]; - for (int i = 0; i < entities.size(); i++) { - nativeEntities[i] = (Entity) Marshaller.marshal(entityManager, entities.get(i), intent); - } - return nativeEntities; - } - - /** - * Increments the version property of the given entity by one. - * - * @param nativeEntity - * the target entity - * @param versionMetadata - * the metadata of the version property - * @return a new entity (copy of the given), but with the incremented - * version. - */ - static Entity incrementVersion(Entity nativeEntity, PropertyMetadata versionMetadata) { - String versionPropertyName = versionMetadata.getMappedName(); - long version = nativeEntity.getLong(versionPropertyName); - return Entity.newBuilder(nativeEntity).set(versionPropertyName, ++version).build(); - } - - /** - * Rolls back the given transaction, if it is still active. - * - * @param transaction - * the transaction to roll back. - */ - static void rollbackIfActive(Transaction transaction) { - try { - if (transaction != null && transaction.isActive()) { - transaction.rollback(); - } - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } - - /** - * Converts/wraps the given native keys into a list of {@link DatastoreKey} - * objects. - * - * @param nativeKeys - * the native keys - * @return a list of {@link DatastoreKey} objects. - */ - static List toDatastoreKeys(List nativeKeys) { - if (nativeKeys == null || nativeKeys.isEmpty()) { - return new ArrayList<>(0); - } - List datastoreKeys = new ArrayList<>(nativeKeys.size()); - for (Key nativeKey : nativeKeys) { - datastoreKeys.add(new DefaultDatastoreKey(nativeKey)); - } - return datastoreKeys; - } - - /** - * Converts/Unwraps the given list of {@link DatastoreKey} objects into an - * array of native {@link Key}s. - * - * @param keys - * the list of {@link DatastoreKey} objects - * @return the native keys - */ - static Key[] toNativeKeys(List keys) { - Key[] nativeKeys = new Key[keys.size()]; - for (int i = 0; i < keys.size(); i++) { - nativeKeys[i] = keys.get(i).nativeKey(); - } - return nativeKeys; - } - - /** - * Validates if the given entity is valid for deferred ID allocation. - * Deferred ID allocation is valid for entities using a numeric ID. - * - * @param entity - * the entity to validate - * @throws EntityManagerException - * if the given entity does not use a numeric ID - */ - static void validateDeferredIdAllocation(Object entity) { - IdentifierMetadata identifierMetadata = EntityIntrospector.getIdentifierMetadata(entity); - if (identifierMetadata.getDataType() == DataType.STRING) { - throw new EntityManagerException( - "Deferred ID allocation is not applicable for entities with String identifiers. "); - } - - } - - /** - * Wraps the given DatastoreException into an {@link EntityManagerException} - * or a subclass of {@link EntityManagerException}. - * - * @param exp - * the DatastoreException - * @return An {@link EntityManagerException} or a subclass of - * {@link EntityManagerException}. - */ - static EntityManagerException wrap(DatastoreException exp) { - switch (exp.getCode()) { - case ERROR_CODE_ENTITY_NOT_FOUND: - return new EntityNotFoundException(exp); - case ERROR_CODE_ENTITY_ALREADY_EXISTS: - return new EntityAlreadyExistsException(exp); - default: - return new EntityManagerException(exp); - - } - } + /** + * Error code from the Datastore when an update operation fails because entity with the specified + * key does not exist. + */ + private static final int ERROR_CODE_ENTITY_NOT_FOUND = 5; + + /** + * Error code from the Datastore when an insert or put operation fails because another entity with + * the same key already exists. + */ + private static final int ERROR_CODE_ENTITY_ALREADY_EXISTS = 6; + + /** + * Hide the implicit constructor + */ + private DatastoreUtils() { + // Do nothing. + } + + /** + * Converts the given list of native entities to a list of model objects of given type, + * entityClass. + * + * @param entityClass + * the entity class + * @param nativeEntities + * native entities to convert + * @return the list of model objects + */ + static List toEntities(Class entityClass, List nativeEntities) { + if (nativeEntities == null || nativeEntities.isEmpty()) { + return new ArrayList<>(); + } + List entities = new ArrayList<>(nativeEntities.size()); + for (Entity nativeEntity : nativeEntities) { + E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); + entities.add(entity); + } + return entities; + } + + /** + * Converts the given array of native entities to a list of model objects of given type, + * entityClass. + * + * @param entityClass + * the entity class + * @param nativeEntities + * native entities to convert + * @return the list of model objects + */ + static List toEntities(Class entityClass, Entity[] nativeEntities) { + if (nativeEntities == null || nativeEntities.length == 0) { + return new ArrayList<>(); + } + return toEntities(entityClass, Arrays.asList(nativeEntities)); + } + + /** + * Converts the given list of model objects to an array of FullEntity objects. + * + * @param entities + * the model objects to convert. + * @param entityManager + * the entity manager + * @param intent + * the intent of marshalling + * @return the equivalent FullEntity array + */ + static FullEntity[] toNativeFullEntities(List entities, DefaultEntityManager entityManager, + Marshaller.Intent intent) { + FullEntity[] nativeEntities = new FullEntity[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + nativeEntities[i] = (FullEntity) Marshaller.marshal(entityManager, entities.get(i), + intent); + } + return nativeEntities; + } + + /** + * Converts the given list of model objects to an array of native Entity objects. + * + * @param entities + * the model objects to convert. + * @param entityManager + * the entity manager + * @param intent + * the intent of marshalling + * @return the equivalent Entity array + */ + static Entity[] toNativeEntities(List entities, DefaultEntityManager entityManager, + Marshaller.Intent intent) { + Entity[] nativeEntities = new Entity[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + nativeEntities[i] = (Entity) Marshaller.marshal(entityManager, entities.get(i), intent); + } + return nativeEntities; + } + + /** + * Increments the version property of the given entity by one. + * + * @param nativeEntity + * the target entity + * @param versionMetadata + * the metadata of the version property + * @return a new entity (copy of the given), but with the incremented version. + */ + static Entity incrementVersion(Entity nativeEntity, PropertyMetadata versionMetadata) { + String versionPropertyName = versionMetadata.getMappedName(); + long version = nativeEntity.getLong(versionPropertyName); + return Entity.newBuilder(nativeEntity).set(versionPropertyName, ++version).build(); + } + + /** + * Rolls back the given transaction, if it is still active. + * + * @param transaction + * the transaction to roll back. + */ + static void rollbackIfActive(Transaction transaction) { + try { + if (transaction != null && transaction.isActive()) { + transaction.rollback(); + } + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } + + /** + * Converts/wraps the given native keys into a list of {@link DatastoreKey} objects. + * + * @param nativeKeys + * the native keys + * @return a list of {@link DatastoreKey} objects. + */ + static List toDatastoreKeys(List nativeKeys) { + if (nativeKeys == null || nativeKeys.isEmpty()) { + return new ArrayList<>(0); + } + List datastoreKeys = new ArrayList<>(nativeKeys.size()); + for (Key nativeKey : nativeKeys) { + datastoreKeys.add(new DefaultDatastoreKey(nativeKey)); + } + return datastoreKeys; + } + + /** + * Converts/Unwraps the given list of {@link DatastoreKey} objects into an array of native + * {@link Key}s. + * + * @param keys + * the list of {@link DatastoreKey} objects + * @return the native keys + */ + static Key[] toNativeKeys(List keys) { + Key[] nativeKeys = new Key[keys.size()]; + for (int i = 0; i < keys.size(); i++) { + nativeKeys[i] = keys.get(i).nativeKey(); + } + return nativeKeys; + } + + /** + * Validates if the given entity is valid for deferred ID allocation. Deferred ID allocation is + * valid for entities using a numeric ID. + * + * @param entity + * the entity to validate + * @throws EntityManagerException + * if the given entity does not use a numeric ID + */ + static void validateDeferredIdAllocation(Object entity) { + IdentifierMetadata identifierMetadata = EntityIntrospector.getIdentifierMetadata(entity); + if (identifierMetadata.getDataType() == DataType.STRING) { + throw new EntityManagerException( + "Deferred ID allocation is not applicable for entities with String identifiers. "); + } + + } + + /** + * Wraps the given DatastoreException into an {@link EntityManagerException} or a subclass of + * {@link EntityManagerException}. + * + * @param exp + * the DatastoreException + * @return An {@link EntityManagerException} or a subclass of {@link EntityManagerException}. + */ + static EntityManagerException wrap(DatastoreException exp) { + switch (exp.getCode()) { + case ERROR_CODE_ENTITY_NOT_FOUND: + return new EntityNotFoundException(exp); + case ERROR_CODE_ENTITY_ALREADY_EXISTS: + return new EntityAlreadyExistsException(exp); + default: + return new EntityManagerException(exp); + + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreBatch.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreBatch.java index 6d38d9b..eefe054 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreBatch.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreBatch.java @@ -34,224 +34,226 @@ */ public class DefaultDatastoreBatch implements DatastoreBatch { - /** - * Reference to the entity manager - */ - private DefaultEntityManager entityManager; - - /** - * Native Batch object - */ - private Batch nativeBatch = null; - - /** - * A reference to the Writer for performing the updates. - */ - private DefaultDatastoreWriter writer = null; - - /** - * A reference to the Datastore - */ - private Datastore datastore = null; - - /** - * Creates a new instance of DefaultDatastoreBatch. - * - * @param entityManager - * a reference to the entity manager - */ - public DefaultDatastoreBatch(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - this.datastore = entityManager.getDatastore(); - this.nativeBatch = datastore.newBatch(); - this.writer = new DefaultDatastoreWriter(this); - } - - /** - * Returns the entity manager from which this batch was created. - * - * @return the entity manager from which this batch was created. - */ - public DefaultEntityManager getEntityManager() { - return entityManager; - } - - /** - * Returns the native batch. - * - * @return the native batch - */ - public Batch getNativeBatch() { - return nativeBatch; - } - - @Override - public E insert(E entity) { - return writer.insert(entity); - } - - @Override - public List insert(List entities) { - return writer.insert(entities); - } - - @Override - public void insertWithDeferredIdAllocation(E entity) { - try { - DatastoreUtils.validateDeferredIdAllocation(entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.INSERT); - nativeBatch.addWithDeferredIdAllocation(nativeEntity); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - @Override - public void insertWithDeferredIdAllocation(List entities) { - if (entities == null || entities.isEmpty()) { - return; - } - try { - DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); - FullEntity[] nativeEntities = DatastoreUtils.toNativeFullEntities(entities, entityManager, - Intent.INSERT); - nativeBatch.addWithDeferredIdAllocation(nativeEntities); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - @Override - public E update(E entity) { - return writer.update(entity); - } - - @Override - public List update(List entities) { - return writer.update(entities); - } - - @Override - public E upsert(E entity) { - return writer.upsert(entity); - } - - @Override - public List upsert(List entities) { - return writer.upsert(entities); - } - - @Override - public void upsertWithDeferredIdAllocation(E entity) { - try { - DatastoreUtils.validateDeferredIdAllocation(entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.UPSERT); - nativeBatch.putWithDeferredIdAllocation(nativeEntity); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - @Override - public void upsertWithDeferredIdAllocation(List entities) { - if (entities == null || entities.isEmpty()) { - return; - } - try { - DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); - FullEntity[] nativeEntities = DatastoreUtils.toNativeFullEntities(entities, entityManager, - Intent.UPSERT); - nativeBatch.putWithDeferredIdAllocation(nativeEntities); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - @Override - public void delete(Object entity) { - writer.delete(entity); - } - - @Override - public void delete(List entities) { - writer.delete(entities); - } - - @Override - public void deleteByKey(DatastoreKey key) { - writer.deleteByKey(key); - } - - @Override - public void deleteByKey(List keys) { - writer.deleteByKey(keys); - } - - @Override - public void delete(Class entityClass, long id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, String id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, long id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, String id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public boolean isActive() { - return nativeBatch.isActive(); - } - - @Override - public Response submit() { - try { - Batch.Response nativeResponse = nativeBatch.submit(); - return new DefaultResponse(nativeResponse); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Implementation of {@link com.jmethods.catatumbo.DatastoreBatch.Response}. - * - * @author Sai Pullabhotla - * - */ - static class DefaultResponse implements Response { - - /** - * Native response - */ - private final Batch.Response nativeResponse; - - /** - * Creates a new instance of DefaultResponse. - * - * @param nativeResponse - * the native response - */ - public DefaultResponse(Batch.Response nativeResponse) { - this.nativeResponse = nativeResponse; - } - - @Override - public List getGeneratedKeys() { - return DatastoreUtils.toDatastoreKeys(nativeResponse.getGeneratedKeys()); - } - } + /** + * Reference to the entity manager + */ + private DefaultEntityManager entityManager; + + /** + * Native Batch object + */ + private Batch nativeBatch = null; + + /** + * A reference to the Writer for performing the updates. + */ + private DefaultDatastoreWriter writer = null; + + /** + * A reference to the Datastore + */ + private Datastore datastore = null; + + /** + * Creates a new instance of DefaultDatastoreBatch. + * + * @param entityManager + * a reference to the entity manager + */ + public DefaultDatastoreBatch(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + this.datastore = entityManager.getDatastore(); + this.nativeBatch = datastore.newBatch(); + this.writer = new DefaultDatastoreWriter(this); + } + + /** + * Returns the entity manager from which this batch was created. + * + * @return the entity manager from which this batch was created. + */ + public DefaultEntityManager getEntityManager() { + return entityManager; + } + + /** + * Returns the native batch. + * + * @return the native batch + */ + public Batch getNativeBatch() { + return nativeBatch; + } + + @Override + public E insert(E entity) { + return writer.insert(entity); + } + + @Override + public List insert(List entities) { + return writer.insert(entities); + } + + @Override + public void insertWithDeferredIdAllocation(E entity) { + try { + DatastoreUtils.validateDeferredIdAllocation(entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.INSERT); + nativeBatch.addWithDeferredIdAllocation(nativeEntity); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + @Override + public void insertWithDeferredIdAllocation(List entities) { + if (entities == null || entities.isEmpty()) { + return; + } + try { + DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); + FullEntity[] nativeEntities = DatastoreUtils.toNativeFullEntities(entities, entityManager, + Intent.INSERT); + nativeBatch.addWithDeferredIdAllocation(nativeEntities); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + @Override + public E update(E entity) { + return writer.update(entity); + } + + @Override + public List update(List entities) { + return writer.update(entities); + } + + @Override + public E upsert(E entity) { + return writer.upsert(entity); + } + + @Override + public List upsert(List entities) { + return writer.upsert(entities); + } + + @Override + public void upsertWithDeferredIdAllocation(E entity) { + try { + DatastoreUtils.validateDeferredIdAllocation(entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.UPSERT); + nativeBatch.putWithDeferredIdAllocation(nativeEntity); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + @Override + public void upsertWithDeferredIdAllocation(List entities) { + if (entities == null || entities.isEmpty()) { + return; + } + try { + DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); + FullEntity[] nativeEntities = DatastoreUtils.toNativeFullEntities(entities, entityManager, + Intent.UPSERT); + nativeBatch.putWithDeferredIdAllocation(nativeEntities); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + @Override + public void delete(Object entity) { + writer.delete(entity); + } + + @Override + public void delete(List entities) { + writer.delete(entities); + } + + @Override + public void delete(Class entityClass, long id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, String id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, long id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, String id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void deleteByKey(DatastoreKey key) { + writer.deleteByKey(key); + } + + @Override + public void deleteByKey(List keys) { + writer.deleteByKey(keys); + } + + @Override + public boolean isActive() { + return nativeBatch.isActive(); + } + + @Override + public Response submit() { + try { + Batch.Response nativeResponse = nativeBatch.submit(); + return new DefaultResponse(nativeResponse); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Implementation of {@link com.jmethods.catatumbo.DatastoreBatch.Response}. + * + * @author Sai Pullabhotla + * + */ + static class DefaultResponse implements Response { + + /** + * Native response + */ + private final Batch.Response nativeResponse; + + /** + * Creates a new instance of DefaultResponse. + * + * @param nativeResponse + * the native response + */ + public DefaultResponse(Batch.Response nativeResponse) { + this.nativeResponse = nativeResponse; + } + + @Override + public List getGeneratedKeys() { + return DatastoreUtils.toDatastoreKeys(nativeResponse.getGeneratedKeys()); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreMetadata.java index c2d6a60..80a4bde 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreMetadata.java @@ -45,121 +45,122 @@ */ public class DefaultDatastoreMetadata implements DatastoreMetadata { - /** - * Name of the System entity that contains the namespaces - */ - private static final String ENTITY_NAMESPACES = "__namespace__"; - - /** - * Name of the System entity that contains the Kinds - */ - private static final String ENTITY_KINDS = "__kind__"; - - /** - * Name of the System entity that contains the Properties of a Kind - */ - private static final String ENTITY_PROPERTIES = "__property__"; - - /** - * Reference to the entity manager that created this object - */ - private DefaultEntityManager entityManager; - - /** - * Creates a new instance of DefaultDatastoreMetadata. - * - * @param entityManager - * the entity manager that created this metadata object. - */ - public DefaultDatastoreMetadata(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - } - - @Override - public List getNamespaces() { - return getNamespaces(0).getResults(); - - } - - @Override - public QueryResponse getNamespaces(int limit) { - return getNamespaces(new DefaultDatastoreCursor(null), limit); - } - - @Override - public QueryResponse getNamespaces(DatastoreCursor fromCursor, int limit) { - try { - Datastore datastore = entityManager.getDatastore(); - String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__"; - if (limit > 0) { - query += " LIMIT @Limit"; - } - query += " OFFSET @Offset"; - GqlQuery.Builder gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query); - if (limit > 0) { - gqlQueryBuilder.setBinding("Limit", limit); - } - gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded())); - GqlQuery gqlQuery = gqlQueryBuilder.build(); - QueryResults results = datastore.run(gqlQuery); - DefaultQueryResponse response = new DefaultQueryResponse<>(); - List namespaces = new ArrayList<>(Math.max(limit, 50)); - response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - while (results.hasNext()) { - Key key = results.next(); - String name = key.getName(); - namespaces.add(name == null ? "" : name); - } - response.setResults(namespaces); - response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - return response; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } - - @Override - public List getKinds() { - return getKinds(false); - } - - @Override - public List getKinds(boolean excludeSystemKinds) { - try { - String query = "SELECT __key__ FROM " + ENTITY_KINDS + " ORDER BY __key__"; - GqlQuery.Builder gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query); - gqlQueryBuilder.setNamespace(entityManager.getEffectiveNamespace()); - GqlQuery gqlQuery = gqlQueryBuilder.build(); - QueryResults results = entityManager.getDatastore().run(gqlQuery); - List kinds = new ArrayList<>(50); - while (results.hasNext()) { - Key key = results.next(); - String kind = key.getName(); - if (excludeSystemKinds && kind.startsWith("__")) { - continue; - } - kinds.add(key.getName()); - } - return kinds; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } - - @Override - public List getProperties(String kind) { - try { - Key nativeKey = entityManager.newNativeKeyFactory().setKind(ENTITY_KINDS).newKey(kind); - DefaultDatastoreKey key = new DefaultDatastoreKey(nativeKey); - String query = "SELECT * FROM " + ENTITY_PROPERTIES + " WHERE __key__ HAS ANCESTOR @1 ORDER BY __key__"; - EntityQueryRequest request = entityManager.createEntityQueryRequest(query); - request.addPositionalBinding(key); - QueryResponse response = entityManager.executeEntityQueryRequest(DatastoreProperty.class, - request); - return response.getResults(); - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Name of the System entity that contains the namespaces + */ + private static final String ENTITY_NAMESPACES = "__namespace__"; + + /** + * Name of the System entity that contains the Kinds + */ + private static final String ENTITY_KINDS = "__kind__"; + + /** + * Name of the System entity that contains the Properties of a Kind + */ + private static final String ENTITY_PROPERTIES = "__property__"; + + /** + * Reference to the entity manager that created this object + */ + private DefaultEntityManager entityManager; + + /** + * Creates a new instance of DefaultDatastoreMetadata. + * + * @param entityManager + * the entity manager that created this metadata object. + */ + public DefaultDatastoreMetadata(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public List getNamespaces() { + return getNamespaces(0).getResults(); + + } + + @Override + public QueryResponse getNamespaces(int limit) { + return getNamespaces(new DefaultDatastoreCursor(null), limit); + } + + @Override + public QueryResponse getNamespaces(DatastoreCursor fromCursor, int limit) { + try { + String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__"; + if (limit > 0) { + query += " LIMIT @Limit"; + } + query += " OFFSET @Offset"; + GqlQuery.Builder gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query); + if (limit > 0) { + gqlQueryBuilder.setBinding("Limit", limit); + } + gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded())); + GqlQuery gqlQuery = gqlQueryBuilder.build(); + Datastore datastore = entityManager.getDatastore(); + QueryResults results = datastore.run(gqlQuery); + DefaultQueryResponse response = new DefaultQueryResponse<>(); + List namespaces = new ArrayList<>(Math.max(limit, 50)); + response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + while (results.hasNext()) { + Key key = results.next(); + String name = key.getName(); + namespaces.add(name == null ? "" : name); + } + response.setResults(namespaces); + response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + return response; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } + + @Override + public List getKinds() { + return getKinds(false); + } + + @Override + public List getKinds(boolean excludeSystemKinds) { + try { + String query = "SELECT __key__ FROM " + ENTITY_KINDS + " ORDER BY __key__"; + GqlQuery.Builder gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query); + gqlQueryBuilder.setNamespace(entityManager.getEffectiveNamespace()); + GqlQuery gqlQuery = gqlQueryBuilder.build(); + QueryResults results = entityManager.getDatastore().run(gqlQuery); + List kinds = new ArrayList<>(50); + while (results.hasNext()) { + Key key = results.next(); + String kind = key.getName(); + if (excludeSystemKinds && kind.startsWith("__")) { + continue; + } + kinds.add(key.getName()); + } + return kinds; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } + + @Override + public List getProperties(String kind) { + try { + Key nativeKey = entityManager.newNativeKeyFactory().setKind(ENTITY_KINDS).newKey(kind); + DefaultDatastoreKey key = new DefaultDatastoreKey(nativeKey); + String query = "SELECT * FROM " + ENTITY_PROPERTIES + + " WHERE __key__ HAS ANCESTOR @1 ORDER BY __key__"; + EntityQueryRequest request = entityManager.createEntityQueryRequest(query); + request.addPositionalBinding(key); + QueryResponse response = entityManager + .executeEntityQueryRequest(DatastoreProperty.class, request); + return response.getResults(); + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java index ccd42eb..8aed460 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java @@ -49,452 +49,440 @@ */ public class DefaultDatastoreReader { - /** - * A reference to the entity manager - */ - private DefaultEntityManager entityManager; + /** + * A reference to the entity manager + */ + private DefaultEntityManager entityManager; - /** - * Native datastore reader. This could either be {@link Datastore} or - * {@link Transaction}. - */ - private DatastoreReader nativeReader = null; + /** + * Native datastore reader. This could either be {@link Datastore} or {@link Transaction}. + */ + private DatastoreReader nativeReader = null; - /** - * A reference to the Datastore. - */ - private Datastore datastore; + /** + * A reference to the Datastore. + */ + private Datastore datastore; - /** - * Creates a new instance of DefaultDatastoreReader. - * - * @param entityManager - * the entity manager that created this reader. - */ - public DefaultDatastoreReader(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - this.datastore = entityManager.getDatastore(); - this.nativeReader = datastore; - } + /** + * Creates a new instance of DefaultDatastoreReader. + * + * @param entityManager + * the entity manager that created this reader. + */ + public DefaultDatastoreReader(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + this.datastore = entityManager.getDatastore(); + this.nativeReader = datastore; + } - /** - * Creates a new instance of DefaultDatastoreReader. - * - * @param transaction - * the transaction that created this reader. - */ - public DefaultDatastoreReader(DefaultDatastoreTransaction transaction) { - this.entityManager = transaction.getEntityManager(); - this.datastore = entityManager.getDatastore(); - this.nativeReader = transaction.getNativeTransaction(); - } + /** + * Creates a new instance of DefaultDatastoreReader. + * + * @param transaction + * the transaction that created this reader. + */ + public DefaultDatastoreReader(DefaultDatastoreTransaction transaction) { + this.entityManager = transaction.getEntityManager(); + this.datastore = entityManager.getDatastore(); + this.nativeReader = transaction.getNativeTransaction(); + } - /** - * Loads and returns the entity with the given ID. The entity is assumed to - * be a root entity (no parent). The entity kind is determined from the - * supplied class. - * - * @param entityClass - * the entity class - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public E load(Class entityClass, long id) { - return load(entityClass, null, id); - } + /** + * Loads and returns the entity with the given ID. The entity is assumed to be a root entity (no + * parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public E load(Class entityClass, long id) { + return load(entityClass, null, id); + } - /** - * Loads and returns the entities with the given numeric IDs. The - * entities are assumed to be a root entities (no parent). The entity kind - * is determined from the supplied class. - * - * @param entityClass - * the entity class - * @param identifiers - * the IDs of the entities - * @return the list of entity objects in the same order as the given list of - * identifiers. If one or more requested IDs do not exist in the - * Cloud Datastore, the corresponding item in the returned list be - * null. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public List loadById(Class entityClass, List identifiers) { - Key[] nativeKeys = longListToNativeKeys(entityClass, identifiers); - return fetch(entityClass, nativeKeys); - } + /** + * Loads and returns the entity with the given ID. The entity kind is determined from the supplied + * class. + * + * @param entityClass + * the entity class + * @param parentKey + * the parent key of the entity. + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public E load(Class entityClass, DatastoreKey parentKey, long id) { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey; + if (parentKey == null) { + nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); + } else { + nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); + } + return fetch(entityClass, nativeKey); + } - /** - * Loads and returns the entity with the given ID. The entity kind is - * determined from the supplied class. - * - * @param entityClass - * the entity class - * @param parentKey - * the parent key of the entity. - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public E load(Class entityClass, DatastoreKey parentKey, long id) { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey; - if (parentKey == null) { - nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); - } else { - nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); - } - return fetch(entityClass, nativeKey); - } + /** + * Loads and returns the entity with the given ID. The entity is assumed to be a root entity (no + * parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public E load(Class entityClass, String id) { + return load(entityClass, null, id); + } - /** - * Loads and returns the entity with the given ID. The entity is assumed to - * be a root entity (no parent). The entity kind is determined from the - * supplied class. - * - * @param entityClass - * the entity class - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public E load(Class entityClass, String id) { - return load(entityClass, null, id); - } + /** + * Loads and returns the entity with the given ID. The entity kind is determined from the supplied + * class. + * + * @param entityClass + * the entity class + * @param parentKey + * the parent key of the entity. + * @param id + * the ID of the entity + * @return the Entity object or null, if the the entity with the given ID does not + * exist in the Cloud Datastore. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public E load(Class entityClass, DatastoreKey parentKey, String id) { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey; + if (parentKey == null) { + nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); + } else { + nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); + } + return fetch(entityClass, nativeKey); + } - /** - * Loads and returns the entities with the given names (a.k.a String - * IDs). The entities are assumed to be root entities (no parent). The - * entity kind is determined from the supplied class. - * - * @param entityClass - * the entity class - * @param identifiers - * the IDs of the entities - * @return the list of entity objects in the same order as the given list of - * identifiers. If one or more requested IDs do not exist in the - * Cloud Datastore, the corresponding item in the returned list be - * null. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public List loadByName(Class entityClass, List identifiers) { - Key[] nativeKeys = stringListToNativeKeys(entityClass, identifiers); - return fetch(entityClass, nativeKeys); - } + /** + * Retrieves and returns the entity with the given key. + * + * @param entityClass + * the expected result type + * @param key + * the entity key + * @return the entity with the given key, or null, if no entity exists with the given + * key. + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + public E load(Class entityClass, DatastoreKey key) { + return fetch(entityClass, key.nativeKey()); + } - /** - * Loads and returns the entity with the given ID. The entity kind is - * determined from the supplied class. - * - * @param entityClass - * the entity class - * @param parentKey - * the parent key of the entity. - * @param id - * the ID of the entity - * @return the Entity object or null, if the the entity with - * the given ID does not exist in the Cloud Datastore. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public E load(Class entityClass, DatastoreKey parentKey, String id) { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey; - if (parentKey == null) { - nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); - } else { - nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); - } - return fetch(entityClass, nativeKey); - } + /** + * Loads and returns the entities with the given numeric IDs. The entities are assumed to + * be a root entities (no parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param identifiers + * the IDs of the entities + * @return the list of entity objects in the same order as the given list of identifiers. If one + * or more requested IDs do not exist in the Cloud Datastore, the corresponding item in + * the returned list be null. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public List loadById(Class entityClass, List identifiers) { + Key[] nativeKeys = longListToNativeKeys(entityClass, identifiers); + return fetch(entityClass, nativeKeys); + } - /** - * Retrieves and returns the entity with the given key. - * - * @param entityClass - * the expected result type - * @param key - * the entity key - * @return the entity with the given key, or null, if no entity - * exists with the given key. - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - public E load(Class entityClass, DatastoreKey key) { - return fetch(entityClass, key.nativeKey()); - } + /** + * Loads and returns the entities with the given names (a.k.a String IDs). The entities are + * assumed to be root entities (no parent). The entity kind is determined from the supplied class. + * + * @param entityClass + * the entity class + * @param identifiers + * the IDs of the entities + * @return the list of entity objects in the same order as the given list of identifiers. If one + * or more requested IDs do not exist in the Cloud Datastore, the corresponding item in + * the returned list be null. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public List loadByName(Class entityClass, List identifiers) { + Key[] nativeKeys = stringListToNativeKeys(entityClass, identifiers); + return fetch(entityClass, nativeKeys); + } - /** - * Retrieves and returns the entities for the given keys. - * - * @param entityClass - * the expected result type - * @param keys - * the entity keys - * @return the entities for the given keys. If one or more requested keys do - * not exist in the Cloud Datastore, the corresponding item in the - * returned list be null. - * - * @throws EntityManagerException - * if any error occurs while accessing the Datastore. - */ - public List loadByKey(Class entityClass, List keys) { - Key[] nativeKeys = DatastoreUtils.toNativeKeys(keys); - return fetch(entityClass, nativeKeys); - } + /** + * Retrieves and returns the entities for the given keys. + * + * @param entityClass + * the expected result type + * @param keys + * the entity keys + * @return the entities for the given keys. If one or more requested keys do not exist in the + * Cloud Datastore, the corresponding item in the returned list be null. + * + * @throws EntityManagerException + * if any error occurs while accessing the Datastore. + */ + public List loadByKey(Class entityClass, List keys) { + Key[] nativeKeys = DatastoreUtils.toNativeKeys(keys); + return fetch(entityClass, nativeKeys); + } - /** - * Fetches the entity given the native key. - * - * @param entityClass - * the expected result type - * @param nativeKey - * the native key - * @return the entity with the given key, or null, if no entity - * exists with the given key. - */ - private E fetch(Class entityClass, Key nativeKey) { - try { - Entity nativeEntity = nativeReader.get(nativeKey); - E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); - entityManager.executeEntityListeners(CallbackType.POST_LOAD, entity); - return entity; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Fetches the entity given the native key. + * + * @param entityClass + * the expected result type + * @param nativeKey + * the native key + * @return the entity with the given key, or null, if no entity exists with the given + * key. + */ + private E fetch(Class entityClass, Key nativeKey) { + try { + Entity nativeEntity = nativeReader.get(nativeKey); + E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); + entityManager.executeEntityListeners(CallbackType.POST_LOAD, entity); + return entity; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } - /** - * Fetches a list of entities for the given native keys. - * - * @param entityClass - * the expected result type - * @param nativeKeys - * the native keys of the entities - * @return the list of entities. If one or more keys do not exist, the - * corresponding item in the returned list will be - * null. - */ - private List fetch(Class entityClass, Key[] nativeKeys) { - try { - List nativeEntities = nativeReader.fetch(nativeKeys); - List entities = DatastoreUtils.toEntities(entityClass, nativeEntities); - entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); - return entities; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Fetches a list of entities for the given native keys. + * + * @param entityClass + * the expected result type + * @param nativeKeys + * the native keys of the entities + * @return the list of entities. If one or more keys do not exist, the corresponding item in the + * returned list will be null. + */ + private List fetch(Class entityClass, Key[] nativeKeys) { + try { + List nativeEntities = nativeReader.fetch(nativeKeys); + List entities = DatastoreUtils.toEntities(entityClass, nativeEntities); + entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); + return entities; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } - /** - * Creates and returns a new {@link EntityQueryRequest} for the given GQL - * query string. The returned {@link EntityQueryRequest} can be further - * customized to set any bindings (positional or named), and then be - * executed by calling the execute or - * executeEntityQuery methods. - * - * @param query - * the GQL query - * @return a new QueryRequest for the given GQL query - */ - public EntityQueryRequest createEntityQueryRequest(String query) { - return new EntityQueryRequest(query); - } + /** + * Creates and returns a new {@link EntityQueryRequest} for the given GQL query string. The + * returned {@link EntityQueryRequest} can be further customized to set any bindings (positional + * or named), and then be executed by calling the execute or + * executeEntityQuery methods. + * + * @param query + * the GQL query + * @return a new QueryRequest for the given GQL query + */ + public EntityQueryRequest createEntityQueryRequest(String query) { + return new EntityQueryRequest(query); + } - /** - * Creates and returns a new {@link ProjectionQueryRequest} for the given - * GQL query string. The returned {@link ProjectionQueryRequest} can further - * be customized to set any positional and/or named bindings, and then be - * executed by calling the execute or - * executeProjectionQuery methods. - * - * @param query - * the GQL projection query - * @return a new ProjectionQueryRequest for the given query - */ - public ProjectionQueryRequest createProjectionQueryRequest(String query) { - return new ProjectionQueryRequest(query); - } + /** + * Creates and returns a new {@link ProjectionQueryRequest} for the given GQL query string. The + * returned {@link ProjectionQueryRequest} can further be customized to set any positional and/or + * named bindings, and then be executed by calling the execute or + * executeProjectionQuery methods. + * + * @param query + * the GQL projection query + * @return a new ProjectionQueryRequest for the given query + */ + public ProjectionQueryRequest createProjectionQueryRequest(String query) { + return new ProjectionQueryRequest(query); + } - /** - * Creates and returns a new {@link KeyQueryRequest} for the given GQL query - * string. Key query requests must only have __key__ in the - * SELECT list of field. The returned {@link KeyQueryRequest} - * can further be customized to set any positional and/or named bindings, - * and then be executed by calling the executeKeyQuery method. - * - * @param query - * the GQL projection query - * @return a new ProjectionQueryRequest for the given query - */ - public KeyQueryRequest createKeyQueryRequest(String query) { - return new KeyQueryRequest(query); - } + /** + * Creates and returns a new {@link KeyQueryRequest} for the given GQL query string. Key query + * requests must only have __key__ in the SELECT list of field. The returned + * {@link KeyQueryRequest} can further be customized to set any positional and/or named bindings, + * and then be executed by calling the executeKeyQuery method. + * + * @param query + * the GQL projection query + * @return a new ProjectionQueryRequest for the given query + */ + public KeyQueryRequest createKeyQueryRequest(String query) { + return new KeyQueryRequest(query); + } - /** - * Executes the given {@link EntityQueryRequest} and returns the response. - * - * @param expectedResultType - * the expected type of results. - * @param request - * the entity query request - * @return the query response - */ - public QueryResponse executeEntityQueryRequest(Class expectedResultType, EntityQueryRequest request) { - try { - GqlQuery.Builder queryBuilder = Query.newGqlQueryBuilder(ResultType.ENTITY, request.getQuery()); - queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); - queryBuilder.setAllowLiteral(request.isAllowLiterals()); - QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); - QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); - GqlQuery gqlQuery = queryBuilder.build(); - QueryResults results = nativeReader.run(gqlQuery); - List entities = new ArrayList<>(); - DefaultQueryResponse response = new DefaultQueryResponse<>(); - response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - while (results.hasNext()) { - Entity result = results.next(); - E entity = Unmarshaller.unmarshal(result, expectedResultType); - entities.add(entity); - } - response.setResults(entities); - response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); - return response; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Executes the given {@link EntityQueryRequest} and returns the response. + * + * @param expectedResultType + * the expected type of results. + * @param request + * the entity query request + * @return the query response + */ + public QueryResponse executeEntityQueryRequest(Class expectedResultType, + EntityQueryRequest request) { + try { + GqlQuery.Builder queryBuilder = Query.newGqlQueryBuilder(ResultType.ENTITY, + request.getQuery()); + queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); + queryBuilder.setAllowLiteral(request.isAllowLiterals()); + QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); + QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); + GqlQuery gqlQuery = queryBuilder.build(); + QueryResults results = nativeReader.run(gqlQuery); + List entities = new ArrayList<>(); + DefaultQueryResponse response = new DefaultQueryResponse<>(); + response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + while (results.hasNext()) { + Entity result = results.next(); + E entity = Unmarshaller.unmarshal(result, expectedResultType); + entities.add(entity); + } + response.setResults(entities); + response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); + return response; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } - /** - * Executes the given {@link ProjectionQueryRequest} and returns the - * response. - * - * @param expectedResultType - * the expected type of results. - * @param request - * the projection query request - * @return the query response - */ - public QueryResponse executeProjectionQueryRequest(Class expectedResultType, - ProjectionQueryRequest request) { - try { - GqlQuery.Builder queryBuilder = Query.newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, - request.getQuery()); - queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); - queryBuilder.setAllowLiteral(request.isAllowLiterals()); - QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); - QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); - GqlQuery gqlQuery = queryBuilder.build(); - QueryResults results = nativeReader.run(gqlQuery); - List entities = new ArrayList<>(); - DefaultQueryResponse response = new DefaultQueryResponse<>(); - response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - while (results.hasNext()) { - ProjectionEntity result = results.next(); - E entity = Unmarshaller.unmarshal(result, expectedResultType); - entities.add(entity); - } - response.setResults(entities); - response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - // TODO should we invoke PostLoad callback for projected entities? - return response; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Executes the given {@link ProjectionQueryRequest} and returns the response. + * + * @param expectedResultType + * the expected type of results. + * @param request + * the projection query request + * @return the query response + */ + public QueryResponse executeProjectionQueryRequest(Class expectedResultType, + ProjectionQueryRequest request) { + try { + GqlQuery.Builder queryBuilder = Query + .newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, request.getQuery()); + queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); + queryBuilder.setAllowLiteral(request.isAllowLiterals()); + QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); + QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); + GqlQuery gqlQuery = queryBuilder.build(); + QueryResults results = nativeReader.run(gqlQuery); + List entities = new ArrayList<>(); + DefaultQueryResponse response = new DefaultQueryResponse<>(); + response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + while (results.hasNext()) { + ProjectionEntity result = results.next(); + E entity = Unmarshaller.unmarshal(result, expectedResultType); + entities.add(entity); + } + response.setResults(entities); + response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + // TODO should we invoke PostLoad callback for projected entities? + return response; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } - /** - * Executes the given {@link KeyQueryRequest} and returns the response. - * - * @param request - * the key query request - * @return the query response - */ - public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { - try { - GqlQuery.Builder queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, request.getQuery()); - queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); - queryBuilder.setAllowLiteral(request.isAllowLiterals()); - QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); - QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); - GqlQuery gqlQuery = queryBuilder.build(); - QueryResults results = nativeReader.run(gqlQuery); - List entities = new ArrayList<>(); - DefaultQueryResponse response = new DefaultQueryResponse<>(); - response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - while (results.hasNext()) { - Key result = results.next(); - DatastoreKey datastoreKey = new DefaultDatastoreKey(result); - entities.add(datastoreKey); - } - response.setResults(entities); - response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); - return response; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } + /** + * Executes the given {@link KeyQueryRequest} and returns the response. + * + * @param request + * the key query request + * @return the query response + */ + public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { + try { + GqlQuery.Builder queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, + request.getQuery()); + queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); + queryBuilder.setAllowLiteral(request.isAllowLiterals()); + QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); + QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); + GqlQuery gqlQuery = queryBuilder.build(); + QueryResults results = nativeReader.run(gqlQuery); + List entities = new ArrayList<>(); + DefaultQueryResponse response = new DefaultQueryResponse<>(); + response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + while (results.hasNext()) { + Key result = results.next(); + DatastoreKey datastoreKey = new DefaultDatastoreKey(result); + entities.add(datastoreKey); + } + response.setResults(entities); + response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); + return response; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } - /** - * Converts the given list of identifiers into an array of native Key - * objects. - * - * @param entityClass - * the entity class to which these identifiers belong to. - * @param identifiers - * the list of identifiers to convert. - * @return an array of Key objects - */ - private Key[] longListToNativeKeys(Class entityClass, List identifiers) { - if (identifiers == null || identifiers.isEmpty()) { - return new Key[0]; - } - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key[] nativeKeys = new Key[identifiers.size()]; - KeyFactory keyFactory = entityManager.newNativeKeyFactory(); - keyFactory.setKind(entityMetadata.getKind()); - for (int i = 0; i < identifiers.size(); i++) { - long id = identifiers.get(i); - nativeKeys[i] = keyFactory.newKey(id); - } - return nativeKeys; - } + /** + * Converts the given list of identifiers into an array of native Key objects. + * + * @param entityClass + * the entity class to which these identifiers belong to. + * @param identifiers + * the list of identifiers to convert. + * @return an array of Key objects + */ + private Key[] longListToNativeKeys(Class entityClass, List identifiers) { + if (identifiers == null || identifiers.isEmpty()) { + return new Key[0]; + } + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key[] nativeKeys = new Key[identifiers.size()]; + KeyFactory keyFactory = entityManager.newNativeKeyFactory(); + keyFactory.setKind(entityMetadata.getKind()); + for (int i = 0; i < identifiers.size(); i++) { + long id = identifiers.get(i); + nativeKeys[i] = keyFactory.newKey(id); + } + return nativeKeys; + } - /** - * Converts the given list of identifiers into an array of native Key - * objects. - * - * @param entityClass - * the entity class to which these identifiers belong to. - * @param identifiers - * the list of identifiers to convert. - * @return an array of Key objects - */ - private Key[] stringListToNativeKeys(Class entityClass, List identifiers) { - if (identifiers == null || identifiers.isEmpty()) { - return new Key[0]; - } - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key[] nativeKeys = new Key[identifiers.size()]; - KeyFactory keyFactory = entityManager.newNativeKeyFactory(); - keyFactory.setKind(entityMetadata.getKind()); - for (int i = 0; i < identifiers.size(); i++) { - String id = identifiers.get(i); - nativeKeys[i] = keyFactory.newKey(id); - } - return nativeKeys; - } + /** + * Converts the given list of identifiers into an array of native Key objects. + * + * @param entityClass + * the entity class to which these identifiers belong to. + * @param identifiers + * the list of identifiers to convert. + * @return an array of Key objects + */ + private Key[] stringListToNativeKeys(Class entityClass, List identifiers) { + if (identifiers == null || identifiers.isEmpty()) { + return new Key[0]; + } + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key[] nativeKeys = new Key[identifiers.size()]; + KeyFactory keyFactory = entityManager.newNativeKeyFactory(); + keyFactory.setKind(entityMetadata.getKind()); + for (int i = 0; i < identifiers.size(); i++) { + String id = identifiers.get(i); + nativeKeys[i] = keyFactory.newKey(id); + } + return nativeKeys; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreStats.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreStats.java index aa825d8..e1243fc 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreStats.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreStats.java @@ -39,154 +39,154 @@ */ public class DefaultDatastoreStats implements DatastoreStats { - /** - * Entity manager - */ - private DefaultEntityManager entityManager; - - /** - * Creates a new instance of DefaultDatastoreStats. - * - * @param entityManager - * the entity manager - */ - DefaultDatastoreStats(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - } - - @Override - public StatTotal getSummary() { - String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(""); - return entityManager.load(StatTotal.class, StatConstants.ID_TOTAL_ENTITY_USAGE); - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public StatTotalNs getSummaryNs() { - return entityManager.load(StatTotalNs.class, StatConstants.ID_TOTAL_ENTITY_USAGE); - } - - @Override - public StatTotalNs getSummaryNs(String namespace) throws EntityManagerException { - String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(namespace); - return entityManager.load(StatTotalNs.class, StatConstants.ID_TOTAL_ENTITY_USAGE); - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public List getKinds() { - String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(""); - final String query = "SELECT * FROM " + StatConstants.STAT_KIND; - EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); - QueryResponse queryResponse = entityManager.executeEntityQueryRequest(StatKind.class, - queryRequest); - return queryResponse.getResults(); - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public StatKind getKind(String kind) { - String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(""); - final String query = "SELECT * FROM " + StatConstants.STAT_KIND + " WHERE " + StatConstants.PROP_KIND_NAME - + "=@1"; - EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); - queryRequest.addPositionalBinding(kind); - QueryResponse queryResponse = entityManager.executeEntityQueryRequest(StatKind.class, - queryRequest); - List entities = queryResponse.getResults(); - if (!entities.isEmpty()) { - return entities.get(0); - } - return null; - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public List getKindsNs() { - final String query = "SELECT * FROM " + StatConstants.STAT_KIND_NS; - EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); - QueryResponse queryResponse = entityManager.executeEntityQueryRequest(StatKindNs.class, - queryRequest); - return queryResponse.getResults(); - } - - @Override - public StatKindNs getKindNs(String kind) { - final String query = "SELECT * FROM " + StatConstants.STAT_KIND_NS + " WHERE " + StatConstants.PROP_KIND_NAME - + "=@1"; - EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); - queryRequest.addPositionalBinding(kind); - QueryResponse queryResponse = entityManager.executeEntityQueryRequest(StatKindNs.class, - queryRequest); - List entities = queryResponse.getResults(); - if (!entities.isEmpty()) { - return entities.get(0); - } - return null; - } - - @Override - public StatKindNs getKindNs(String namespace, String kind) { - String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(namespace); - return getKindNs(kind); - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public List getCompositeIndexes() { - final String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(""); - final String query = "SELECT * FROM " + StatConstants.STAT_COMPOSITE_INDEX; - EntityQueryRequest request = entityManager.createEntityQueryRequest(query); - QueryResponse response = entityManager - .executeEntityQueryRequest(StatCompositeIndex.class, request); - return response.getResults(); - - } finally { - Tenant.setNamespace(currentNamespace); - } - } - - @Override - public List getCompositeIndexesNs() { - final String query = "SELECT * FROM " + StatConstants.STAT_COMPOSITE_INDEX_NS; - EntityQueryRequest request = entityManager.createEntityQueryRequest(query); - QueryResponse response = entityManager - .executeEntityQueryRequest(StatCompositeIndexNs.class, request); - return response.getResults(); - } - - @Override - public List getCompositeIndexesNs(String namespace) { - final String currentNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(namespace); - return getCompositeIndexesNs(); - - } finally { - Tenant.setNamespace(currentNamespace); - } - } + /** + * Entity manager + */ + private DefaultEntityManager entityManager; + + /** + * Creates a new instance of DefaultDatastoreStats. + * + * @param entityManager + * the entity manager + */ + DefaultDatastoreStats(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public StatTotal getSummary() { + String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(""); + return entityManager.load(StatTotal.class, StatConstants.ID_TOTAL_ENTITY_USAGE); + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public StatTotalNs getSummaryNs() { + return entityManager.load(StatTotalNs.class, StatConstants.ID_TOTAL_ENTITY_USAGE); + } + + @Override + public StatTotalNs getSummaryNs(String namespace) throws EntityManagerException { + String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(namespace); + return entityManager.load(StatTotalNs.class, StatConstants.ID_TOTAL_ENTITY_USAGE); + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public List getKinds() { + String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(""); + final String query = "SELECT * FROM " + StatConstants.STAT_KIND; + EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); + QueryResponse queryResponse = entityManager + .executeEntityQueryRequest(StatKind.class, queryRequest); + return queryResponse.getResults(); + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public StatKind getKind(String kind) { + String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(""); + final String query = "SELECT * FROM " + StatConstants.STAT_KIND + " WHERE " + + StatConstants.PROP_KIND_NAME + "=@1"; + EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); + queryRequest.addPositionalBinding(kind); + QueryResponse queryResponse = entityManager + .executeEntityQueryRequest(StatKind.class, queryRequest); + List entities = queryResponse.getResults(); + if (!entities.isEmpty()) { + return entities.get(0); + } + return null; + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public List getKindsNs() { + final String query = "SELECT * FROM " + StatConstants.STAT_KIND_NS; + EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); + QueryResponse queryResponse = entityManager + .executeEntityQueryRequest(StatKindNs.class, queryRequest); + return queryResponse.getResults(); + } + + @Override + public StatKindNs getKindNs(String kind) { + final String query = "SELECT * FROM " + StatConstants.STAT_KIND_NS + " WHERE " + + StatConstants.PROP_KIND_NAME + "=@1"; + EntityQueryRequest queryRequest = entityManager.createEntityQueryRequest(query); + queryRequest.addPositionalBinding(kind); + QueryResponse queryResponse = entityManager + .executeEntityQueryRequest(StatKindNs.class, queryRequest); + List entities = queryResponse.getResults(); + if (!entities.isEmpty()) { + return entities.get(0); + } + return null; + } + + @Override + public StatKindNs getKindNs(String namespace, String kind) { + String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(namespace); + return getKindNs(kind); + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public List getCompositeIndexes() { + final String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(""); + final String query = "SELECT * FROM " + StatConstants.STAT_COMPOSITE_INDEX; + EntityQueryRequest request = entityManager.createEntityQueryRequest(query); + QueryResponse response = entityManager + .executeEntityQueryRequest(StatCompositeIndex.class, request); + return response.getResults(); + + } finally { + Tenant.setNamespace(currentNamespace); + } + } + + @Override + public List getCompositeIndexesNs() { + final String query = "SELECT * FROM " + StatConstants.STAT_COMPOSITE_INDEX_NS; + EntityQueryRequest request = entityManager.createEntityQueryRequest(query); + QueryResponse response = entityManager + .executeEntityQueryRequest(StatCompositeIndexNs.class, request); + return response.getResults(); + } + + @Override + public List getCompositeIndexesNs(String namespace) { + final String currentNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(namespace); + return getCompositeIndexesNs(); + + } finally { + Tenant.setNamespace(currentNamespace); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreTransaction.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreTransaction.java index 54d09c3..38db571 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreTransaction.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreTransaction.java @@ -41,317 +41,320 @@ */ public class DefaultDatastoreTransaction implements DatastoreTransaction { - /** - * Entity manager that created this transaction - */ - private DefaultEntityManager entityManager; - - /** - * Native transaction - */ - private Transaction nativeTransaction; - - /** - * Datastore - */ - private Datastore datastore; - - /** - * Reader - */ - private DefaultDatastoreReader reader; - - /** - * Writer - */ - private DefaultDatastoreWriter writer; - - /** - * Creates a new instance of DatastoreTransaction. - * - * @param entityManager - * the entity manager that created this transaction. - */ - public DefaultDatastoreTransaction(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - this.datastore = entityManager.getDatastore(); - this.nativeTransaction = datastore.newTransaction(); - this.reader = new DefaultDatastoreReader(this); - this.writer = new DefaultDatastoreWriter(this); - } - - /** - * Returns the entity manager that created this transaction. - * - * @return the entity manager that created this transaction. - */ - public DefaultEntityManager getEntityManager() { - return entityManager; - } - - /** - * Returns the native transaction. - * - * @return the native transaction. - */ - public Transaction getNativeTransaction() { - return nativeTransaction; - } - - @Override - public void insertWithDeferredIdAllocation(E entity) { - try { - DatastoreUtils.validateDeferredIdAllocation(entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.INSERT); - nativeTransaction.addWithDeferredIdAllocation(nativeEntity); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - @Override - public void insertWithDeferredIdAllocation(List entities) { - if (entities == null || entities.isEmpty()) { - return; - } - try { - DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); - FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.INSERT); - nativeTransaction.addWithDeferredIdAllocation(nativeEntities); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - @Override - public void upsertWithDeferredIdAllocation(E entity) { - try { - DatastoreUtils.validateDeferredIdAllocation(entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.UPSERT); - nativeTransaction.putWithDeferredIdAllocation(nativeEntity); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - @Override - public void upsertWithDeferredIdAllocation(List entities) { - if (entities == null || entities.isEmpty()) { - return; - } - try { - DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); - FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); - nativeTransaction.putWithDeferredIdAllocation(nativeEntities); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - @Override - public boolean isActive() { - try { - return nativeTransaction.isActive(); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } catch (Exception exp) { - throw new EntityManagerException(exp); - } - } - - @Override - public Response commit() { - try { - Transaction.Response nativeResponse = nativeTransaction.commit(); - return new DefaultResponse(nativeResponse); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } catch (Exception exp) { - throw new EntityManagerException(exp); - } - } - - @Override - public void rollback() { - try { - nativeTransaction.rollback(); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } catch (Exception exp) { - throw new EntityManagerException(exp); - } - } - - /** - * Transaction Response containing the results of a transaction commit. - * - * @author Sai Pullabhotla - * - */ - static class DefaultResponse implements Response { - - /** - * Native response - */ - private final Transaction.Response nativeResponse; - - /** - * Creates a new instance of DefaultResponse. - * - * @param nativeResponse - * the native transaction response - */ - public DefaultResponse(Transaction.Response nativeResponse) { - this.nativeResponse = nativeResponse; - } - - @Override - public List getGeneratedKeys() { - return DatastoreUtils.toDatastoreKeys(nativeResponse.getGeneratedKeys()); - } - } - - @Override - public E insert(E entity) { - return writer.insert(entity); - } - - @Override - public List insert(List entities) { - return writer.insert(entities); - } - - @Override - public E update(E entity) { - return writer.updateWithOptimisticLock(entity); - } - - @Override - public List update(List entities) { - return writer.updateWithOptimisticLock(entities); - } - - @Override - public E upsert(E entity) { - return writer.upsert(entity); - } - - @Override - public List upsert(List entities) { - return writer.upsert(entities); - } - - @Override - public void delete(Object entity) { - writer.delete(entity); - } - - @Override - public void delete(List entities) { - writer.delete(entities); - } - - @Override - public void deleteByKey(DatastoreKey key) { - writer.deleteByKey(key); - } - - @Override - public void deleteByKey(List keys) { - writer.deleteByKey(keys); - } - - @Override - public void delete(Class entityClass, long id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, String id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, long id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, String id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, long id) { - return reader.load(entityClass, id); - } - - @Override - public List loadById(Class entityClass, List identifiers) { - return reader.loadById(entityClass, identifiers); - } - - @Override - public E load(Class entityClass, String id) { - return reader.load(entityClass, id); - } - - @Override - public List loadByName(Class entityClass, List identifiers) { - return reader.loadByName(entityClass, identifiers); - } - - @Override - public E load(Class entityClass, DatastoreKey parentKey, long id) { - return reader.load(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, DatastoreKey parentKey, String id) { - return reader.load(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, DatastoreKey key) { - return reader.load(entityClass, key); - } - - @Override - public List loadByKey(Class entityClass, List keys) { - return reader.loadByKey(entityClass, keys); - } - - @Override - public EntityQueryRequest createEntityQueryRequest(String query) { - return reader.createEntityQueryRequest(query); - } - - @Override - public ProjectionQueryRequest createProjectionQueryRequest(String query) { - return reader.createProjectionQueryRequest(query); - } - - @Override - public KeyQueryRequest createKeyQueryRequest(String query) { - return reader.createKeyQueryRequest(query); - } - - @Override - public QueryResponse executeEntityQueryRequest(Class expectedResultType, EntityQueryRequest request) { - return reader.executeEntityQueryRequest(expectedResultType, request); - } - - @Override - public QueryResponse executeProjectionQueryRequest(Class expectedResultType, - ProjectionQueryRequest request) { - return reader.executeProjectionQueryRequest(expectedResultType, request); - } - - @Override - public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { - return reader.executeKeyQueryRequest(request); - } + /** + * Entity manager that created this transaction + */ + private DefaultEntityManager entityManager; + + /** + * Native transaction + */ + private Transaction nativeTransaction; + + /** + * Datastore + */ + private Datastore datastore; + + /** + * Reader + */ + private DefaultDatastoreReader reader; + + /** + * Writer + */ + private DefaultDatastoreWriter writer; + + /** + * Creates a new instance of DatastoreTransaction. + * + * @param entityManager + * the entity manager that created this transaction. + */ + public DefaultDatastoreTransaction(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + this.datastore = entityManager.getDatastore(); + this.nativeTransaction = datastore.newTransaction(); + this.reader = new DefaultDatastoreReader(this); + this.writer = new DefaultDatastoreWriter(this); + } + + /** + * Returns the entity manager that created this transaction. + * + * @return the entity manager that created this transaction. + */ + public DefaultEntityManager getEntityManager() { + return entityManager; + } + + /** + * Returns the native transaction. + * + * @return the native transaction. + */ + public Transaction getNativeTransaction() { + return nativeTransaction; + } + + @Override + public void insertWithDeferredIdAllocation(E entity) { + try { + DatastoreUtils.validateDeferredIdAllocation(entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.INSERT); + nativeTransaction.addWithDeferredIdAllocation(nativeEntity); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + @Override + public void insertWithDeferredIdAllocation(List entities) { + if (entities == null || entities.isEmpty()) { + return; + } + try { + DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); + FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.INSERT); + nativeTransaction.addWithDeferredIdAllocation(nativeEntities); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + @Override + public void upsertWithDeferredIdAllocation(E entity) { + try { + DatastoreUtils.validateDeferredIdAllocation(entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.UPSERT); + nativeTransaction.putWithDeferredIdAllocation(nativeEntity); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + @Override + public void upsertWithDeferredIdAllocation(List entities) { + if (entities == null || entities.isEmpty()) { + return; + } + try { + DatastoreUtils.validateDeferredIdAllocation(entities.get(0)); + FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); + nativeTransaction.putWithDeferredIdAllocation(nativeEntities); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + @Override + public boolean isActive() { + try { + return nativeTransaction.isActive(); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } catch (Exception exp) { + throw new EntityManagerException(exp); + } + } + + @Override + public Response commit() { + try { + Transaction.Response nativeResponse = nativeTransaction.commit(); + return new DefaultResponse(nativeResponse); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } catch (Exception exp) { + throw new EntityManagerException(exp); + } + } + + @Override + public void rollback() { + try { + nativeTransaction.rollback(); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } catch (Exception exp) { + throw new EntityManagerException(exp); + } + } + + /** + * Transaction Response containing the results of a transaction commit. + * + * @author Sai Pullabhotla + * + */ + static class DefaultResponse implements Response { + + /** + * Native response + */ + private final Transaction.Response nativeResponse; + + /** + * Creates a new instance of DefaultResponse. + * + * @param nativeResponse + * the native transaction response + */ + public DefaultResponse(Transaction.Response nativeResponse) { + this.nativeResponse = nativeResponse; + } + + @Override + public List getGeneratedKeys() { + return DatastoreUtils.toDatastoreKeys(nativeResponse.getGeneratedKeys()); + } + } + + @Override + public E insert(E entity) { + return writer.insert(entity); + } + + @Override + public List insert(List entities) { + return writer.insert(entities); + } + + @Override + public E update(E entity) { + return writer.updateWithOptimisticLock(entity); + } + + @Override + public List update(List entities) { + return writer.updateWithOptimisticLock(entities); + } + + @Override + public E upsert(E entity) { + return writer.upsert(entity); + } + + @Override + public List upsert(List entities) { + return writer.upsert(entities); + } + + @Override + public void delete(Object entity) { + writer.delete(entity); + } + + @Override + public void delete(List entities) { + writer.delete(entities); + } + + @Override + public void delete(Class entityClass, long id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, String id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, long id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, String id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void deleteByKey(DatastoreKey key) { + writer.deleteByKey(key); + } + + @Override + public void deleteByKey(List keys) { + writer.deleteByKey(keys); + } + + @Override + public E load(Class entityClass, long id) { + return reader.load(entityClass, id); + } + + @Override + public E load(Class entityClass, String id) { + return reader.load(entityClass, id); + } + + @Override + public E load(Class entityClass, DatastoreKey parentKey, long id) { + return reader.load(entityClass, parentKey, id); + } + + @Override + public E load(Class entityClass, DatastoreKey parentKey, String id) { + return reader.load(entityClass, parentKey, id); + } + + @Override + public E load(Class entityClass, DatastoreKey key) { + return reader.load(entityClass, key); + } + + @Override + public List loadById(Class entityClass, List identifiers) { + return reader.loadById(entityClass, identifiers); + } + + @Override + public List loadByName(Class entityClass, List identifiers) { + return reader.loadByName(entityClass, identifiers); + } + + @Override + public List loadByKey(Class entityClass, List keys) { + return reader.loadByKey(entityClass, keys); + } + + @Override + public EntityQueryRequest createEntityQueryRequest(String query) { + return reader.createEntityQueryRequest(query); + } + + @Override + public ProjectionQueryRequest createProjectionQueryRequest(String query) { + return reader.createProjectionQueryRequest(query); + } + + @Override + public KeyQueryRequest createKeyQueryRequest(String query) { + return reader.createKeyQueryRequest(query); + } + + @Override + public QueryResponse executeEntityQueryRequest(Class expectedResultType, + EntityQueryRequest request) { + return reader.executeEntityQueryRequest(expectedResultType, request); + } + + @Override + public QueryResponse executeProjectionQueryRequest(Class expectedResultType, + ProjectionQueryRequest request) { + return reader.executeProjectionQueryRequest(expectedResultType, request); + } + + @Override + public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { + return reader.executeKeyQueryRequest(request); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java index 817815d..ff5f51a 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreWriter.java @@ -45,518 +45,515 @@ */ public class DefaultDatastoreWriter { - /** - * A reference to the entity manager - */ - private DefaultEntityManager entityManager; - - /** - * Reference to the native DatastoreWriter for updating the Cloud Datastore. - * This could be the {@link Datastore}, {@link Transaction} or - * {@link Batch}. - */ - private DatastoreWriter nativeWriter; - - /** - * A reference to the Datastore - */ - private Datastore datastore; - - /** - * Creates a new instance of DefaultDatastoreWriter. - * - * @param entityManager - * a reference to the entity manager. - */ - public DefaultDatastoreWriter(DefaultEntityManager entityManager) { - this.entityManager = entityManager; - this.datastore = entityManager.getDatastore(); - this.nativeWriter = datastore; - } - - /** - * Creates a new instance of DefaultDatastoreWriter for - * executing batch updates. - * - * @param batch - * the {@link DefaultDatastoreBatch}. - */ - public DefaultDatastoreWriter(DefaultDatastoreBatch batch) { - this.entityManager = batch.getEntityManager(); - this.datastore = entityManager.getDatastore(); - this.nativeWriter = batch.getNativeBatch(); - } - - /** - * Creates a new instance of DefaultDatastoreWriter for - * transactional updates. - * - * @param transaction - * the {@link DefaultDatastoreTransaction}. - */ - public DefaultDatastoreWriter(DefaultDatastoreTransaction transaction) { - this.entityManager = transaction.getEntityManager(); - this.datastore = entityManager.getDatastore(); - this.nativeWriter = transaction.getNativeTransaction(); - } - - /** - * Inserts the given entity into the Cloud Datastore. - * - * @param entity - * the entity to insert - * @return the inserted entity. The inserted entity will not be same as the - * passed in entity. For example, the inserted entity may contain - * any generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public E insert(E entity) { - try { - entityManager.executeEntityListeners(CallbackType.PRE_INSERT, entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.INSERT); - Entity insertedNativeEntity = nativeWriter.add(nativeEntity); - @SuppressWarnings("unchecked") - E insertedEntity = (E) Unmarshaller.unmarshal(insertedNativeEntity, entity.getClass()); - entityManager.executeEntityListeners(CallbackType.POST_INSERT, insertedEntity); - return insertedEntity; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Inserts the given list of entities into the Cloud Datastore. - * - * @param entities - * the entities to insert. - * @return the inserted entities. The inserted entities will not be same as - * the passed in entities. For example, the inserted entities may - * contain generated ID, key, parent key, etc. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - @SuppressWarnings("unchecked") - public List insert(List entities) { - if (entities == null || entities.isEmpty()) { - return new ArrayList<>(); - } - try { - entityManager.executeEntityListeners(CallbackType.PRE_INSERT, entities); - FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.INSERT); - Class entityClass = entities.get(0).getClass(); - List insertedNativeEntities = nativeWriter.add(nativeEntities); - List insertedEntities = (List) toEntities(entityClass, insertedNativeEntities); - entityManager.executeEntityListeners(CallbackType.POST_INSERT, insertedEntities); - return insertedEntities; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Updates the given entity in the Cloud Datastore. The passed in Entity - * must have its ID set for the update to work. - * - * @param entity - * the entity to update - * @return the updated entity. - * @throws EntityManagerException - * if any error occurs while updating. - */ - @SuppressWarnings("unchecked") - public E update(E entity) { - try { - entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); - Intent intent = (nativeWriter instanceof Batch) ? Intent.BATCH_UPDATE : Intent.UPDATE; - Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, intent); - nativeWriter.update(nativeEntity); - E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); - entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity); - return updatedEntity; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - - } - - /** - * Updates the given entity with optimistic locking, if the entity is set up - * to support optimistic locking. Otherwise, a normal update is performed. - * - * @param entity - * the entity to update - * @return the updated entity which may be different than the given entity. - */ - public E updateWithOptimisticLock(E entity) { - PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entity); - if (versionMetadata == null) { - return update(entity); - } else { - return updateWithOptimisticLockingInternal(entity, versionMetadata); - } - - } - - /** - * Worker method for updating the given entity with optimistic locking. - * - * @param entity - * the entity to update - * @param versionMetadata - * the metadata for optimistic locking - * @return the updated entity - */ - @SuppressWarnings("unchecked") - private E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) { - Transaction transaction = null; - try { - entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); - Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE); - transaction = datastore.newTransaction(); - Entity storedNativeEntity = transaction.get(nativeEntity.getKey()); - if (storedNativeEntity == null) { - throw new OptimisticLockException(String.format("Entity does not exist: %s", nativeEntity.getKey())); - } - String versionPropertyName = versionMetadata.getMappedName(); - long version = nativeEntity.getLong(versionPropertyName) - 1; - long storedVersion = storedNativeEntity.getLong(versionPropertyName); - if (version != storedVersion) { - throw new OptimisticLockException( - String.format("Expecting version %d, but found %d", version, storedVersion)); - } - transaction.update(nativeEntity); - transaction.commit(); - E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); - entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity); - return updatedEntity; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } finally { - rollbackIfActive(transaction); - } - } - - /** - * Updates the given list of entities in the Cloud Datastore. - * - * @param entities - * the entities to update. The passed in entities must have their - * ID set for the update to work. - * @return the updated entities - * @throws EntityManagerException - * if any error occurs while inserting. - */ - @SuppressWarnings("unchecked") - public List update(List entities) { - if (entities == null || entities.isEmpty()) { - return new ArrayList<>(); - } - try { - Class entityClass = (Class) entities.get(0).getClass(); - entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entities); - Intent intent = (nativeWriter instanceof Batch) ? Intent.BATCH_UPDATE : Intent.UPDATE; - Entity[] nativeEntities = toNativeEntities(entities, entityManager, intent); - nativeWriter.update(nativeEntities); - List updatedEntities = toEntities(entityClass, nativeEntities); - entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntities); - return updatedEntities; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Updates the given list of entities using optimistic locking feature, if - * the entities are set up to support optimistic locking. Otherwise, a - * normal update is performed. - * - * @param entities - * the entities to update - * @return the updated entities - */ - public List updateWithOptimisticLock(List entities) { - if (entities == null || entities.isEmpty()) { - return new ArrayList<>(); - } - Class entityClass = entities.get(0).getClass(); - PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entityClass); - if (versionMetadata == null) { - return update(entities); - } else { - return updateWithOptimisticLockInternal(entities, versionMetadata); - } - } - - /** - * Internal worker method for updating the entities using optimistic - * locking. - * - * @param entities - * the entities to update - * @param versionMetadata - * the metadata of the version property - * @return the updated entities - */ - @SuppressWarnings("unchecked") - private List updateWithOptimisticLockInternal(List entities, PropertyMetadata versionMetadata) { - Transaction transaction = null; - try { - entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entities); - Entity[] nativeEntities = toNativeEntities(entities, entityManager, Intent.UPDATE); - // The above native entities already have the version incremented by - // the marshalling process - Key[] nativeKeys = new Key[nativeEntities.length]; - for (int i = 0; i < nativeEntities.length; i++) { - nativeKeys[i] = nativeEntities[i].getKey(); - } - transaction = datastore.newTransaction(); - List storedNativeEntities = transaction.fetch(nativeKeys); - String versionPropertyName = versionMetadata.getMappedName(); - - for (int i = 0; i < nativeEntities.length; i++) { - long version = nativeEntities[i].getLong(versionPropertyName) - 1; - Entity storedNativeEntity = storedNativeEntities.get(i); - if (storedNativeEntity == null) { - throw new OptimisticLockException(String.format("Entity does not exist: %s", nativeKeys[i])); - } - long storedVersion = storedNativeEntities.get(i).getLong(versionPropertyName); - if (version != storedVersion) { - throw new OptimisticLockException( - String.format("Expecting version %d, but found %d", version, storedVersion)); - } - } - transaction.update(nativeEntities); - transaction.commit(); - List updatedEntities = (List) toEntities(entities.get(0).getClass(), nativeEntities); - entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntities); - return updatedEntities; - - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } finally { - rollbackIfActive(transaction); - } - - } - - /** - * Updates or inserts the given entity in the Cloud Datastore. If the entity - * does not have an ID, it may be generated. - * - * @param entity - * the entity to update or insert - * @return the updated/inserted entity. - * @throws EntityManagerException - * if any error occurs while saving. - */ - public E upsert(E entity) { - try { - entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entity); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, Intent.UPSERT); - Entity upsertedNativeEntity = nativeWriter.put(nativeEntity); - @SuppressWarnings("unchecked") - E upsertedEntity = (E) Unmarshaller.unmarshal(upsertedNativeEntity, entity.getClass()); - entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntity); - return upsertedEntity; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Updates or inserts the given list of entities in the Cloud Datastore. If - * the entities do not have a valid ID, IDs may be generated. - * - * @param entities - * the entities to update/or insert. - * @return the updated or inserted entities - * @throws EntityManagerException - * if any error occurs while saving. - */ - @SuppressWarnings("unchecked") - public List upsert(List entities) { - if (entities == null || entities.isEmpty()) { - return new ArrayList<>(); - } - try { - entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entities); - FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); - Class entityClass = entities.get(0).getClass(); - List upsertedNativeEntities = nativeWriter.put(nativeEntities); - List upsertedEntities = (List) toEntities(entityClass, upsertedNativeEntities); - entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntities); - return upsertedEntities; - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the given entity from the Cloud Datastore. - * - * @param entity - * the entity to delete. The entity must have it ID set for the - * deletion to succeed. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - public void delete(Object entity) { - try { - entityManager.executeEntityListeners(CallbackType.PRE_DELETE, entity); - Key nativeKey = Marshaller.marshalKey(entityManager, entity); - nativeWriter.delete(nativeKey); - entityManager.executeEntityListeners(CallbackType.POST_DELETE, entity); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the given entities from the Cloud Datastore. - * - * @param entities - * the entities to delete. The entities must have it ID set for - * the deletion to succeed. - * @throws EntityManagerException - * if any error occurs while deleting. - */ - public void delete(List entities) { - try { - entityManager.executeEntityListeners(CallbackType.PRE_DELETE, entities); - Key[] nativeKeys = new Key[entities.size()]; - for (int i = 0; i < entities.size(); i++) { - nativeKeys[i] = Marshaller.marshalKey(entityManager, entities.get(i)); - } - nativeWriter.delete(nativeKeys); - entityManager.executeEntityListeners(CallbackType.POST_DELETE, entities); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes an entity given its key. - * - * @param key - * the entity's key - * @throws EntityManagerException - * if any error occurs while deleting. - */ - public void deleteByKey(DatastoreKey key) { - try { - nativeWriter.delete(key.nativeKey()); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the entities having the given keys. - * - * @param keys - * the entities' keys - * @throws EntityManagerException - * if any error occurs while deleting. - */ - public void deleteByKey(List keys) { - try { - Key[] nativeKeys = new Key[keys.size()]; - for (int i = 0; i < keys.size(); i++) { - nativeKeys[i] = keys.get(i).nativeKey(); - } - nativeWriter.delete(nativeKeys); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the entity with the given ID. The entity is assumed to be a root - * entity (no parent). The entity kind will be determined from the supplied - * entity class. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public void delete(Class entityClass, long id) { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); - nativeWriter.delete(nativeKey); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the entity with the given ID. The entity is assumed to be a root - * entity (no parent). The entity kind will be determined from the supplied - * entity class. - * - * @param entityClass - * the entity class. - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public void delete(Class entityClass, String id) { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); - nativeWriter.delete(nativeKey); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the entity with the given ID and parent key. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public void delete(Class entityClass, DatastoreKey parentKey, long id) { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); - nativeWriter.delete(nativeKey); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } - - /** - * Deletes the entity with the given ID and parent key. - * - * @param entityClass - * the entity class. - * @param parentKey - * the parent key - * @param id - * the ID of the entity. - * @throws EntityManagerException - * if any error occurs while inserting. - */ - public void delete(Class entityClass, DatastoreKey parentKey, String id) { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); - nativeWriter.delete(nativeKey); - } catch (DatastoreException exp) { - throw DatastoreUtils.wrap(exp); - } - } + /** + * A reference to the entity manager + */ + private DefaultEntityManager entityManager; + + /** + * Reference to the native DatastoreWriter for updating the Cloud Datastore. This could be the + * {@link Datastore}, {@link Transaction} or {@link Batch}. + */ + private DatastoreWriter nativeWriter; + + /** + * A reference to the Datastore + */ + private Datastore datastore; + + /** + * Creates a new instance of DefaultDatastoreWriter. + * + * @param entityManager + * a reference to the entity manager. + */ + public DefaultDatastoreWriter(DefaultEntityManager entityManager) { + this.entityManager = entityManager; + this.datastore = entityManager.getDatastore(); + this.nativeWriter = datastore; + } + + /** + * Creates a new instance of DefaultDatastoreWriter for executing batch updates. + * + * @param batch + * the {@link DefaultDatastoreBatch}. + */ + public DefaultDatastoreWriter(DefaultDatastoreBatch batch) { + this.entityManager = batch.getEntityManager(); + this.datastore = entityManager.getDatastore(); + this.nativeWriter = batch.getNativeBatch(); + } + + /** + * Creates a new instance of DefaultDatastoreWriter for transactional updates. + * + * @param transaction + * the {@link DefaultDatastoreTransaction}. + */ + public DefaultDatastoreWriter(DefaultDatastoreTransaction transaction) { + this.entityManager = transaction.getEntityManager(); + this.datastore = entityManager.getDatastore(); + this.nativeWriter = transaction.getNativeTransaction(); + } + + /** + * Inserts the given entity into the Cloud Datastore. + * + * @param entity + * the entity to insert + * @return the inserted entity. The inserted entity will not be same as the passed in entity. For + * example, the inserted entity may contain any generated ID, key, parent key, etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public E insert(E entity) { + try { + entityManager.executeEntityListeners(CallbackType.PRE_INSERT, entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.INSERT); + Entity insertedNativeEntity = nativeWriter.add(nativeEntity); + @SuppressWarnings("unchecked") + E insertedEntity = (E) Unmarshaller.unmarshal(insertedNativeEntity, entity.getClass()); + entityManager.executeEntityListeners(CallbackType.POST_INSERT, insertedEntity); + return insertedEntity; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Inserts the given list of entities into the Cloud Datastore. + * + * @param entities + * the entities to insert. + * @return the inserted entities. The inserted entities will not be same as the passed in + * entities. For example, the inserted entities may contain generated ID, key, parent key, + * etc. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + @SuppressWarnings("unchecked") + public List insert(List entities) { + if (entities == null || entities.isEmpty()) { + return new ArrayList<>(); + } + try { + entityManager.executeEntityListeners(CallbackType.PRE_INSERT, entities); + FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.INSERT); + Class entityClass = entities.get(0).getClass(); + List insertedNativeEntities = nativeWriter.add(nativeEntities); + List insertedEntities = (List) toEntities(entityClass, insertedNativeEntities); + entityManager.executeEntityListeners(CallbackType.POST_INSERT, insertedEntities); + return insertedEntities; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Updates the given entity in the Cloud Datastore. The passed in Entity must have its ID set for + * the update to work. + * + * @param entity + * the entity to update + * @return the updated entity. + * @throws EntityManagerException + * if any error occurs while updating. + */ + @SuppressWarnings("unchecked") + public E update(E entity) { + try { + entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); + Intent intent = (nativeWriter instanceof Batch) ? Intent.BATCH_UPDATE : Intent.UPDATE; + Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, intent); + nativeWriter.update(nativeEntity); + E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); + entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity); + return updatedEntity; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + + } + + /** + * Updates the given list of entities in the Cloud Datastore. + * + * @param entities + * the entities to update. The passed in entities must have their ID set for the update + * to work. + * @return the updated entities + * @throws EntityManagerException + * if any error occurs while inserting. + */ + @SuppressWarnings("unchecked") + public List update(List entities) { + if (entities == null || entities.isEmpty()) { + return new ArrayList<>(); + } + try { + Class entityClass = (Class) entities.get(0).getClass(); + entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entities); + Intent intent = (nativeWriter instanceof Batch) ? Intent.BATCH_UPDATE : Intent.UPDATE; + Entity[] nativeEntities = toNativeEntities(entities, entityManager, intent); + nativeWriter.update(nativeEntities); + List updatedEntities = toEntities(entityClass, nativeEntities); + entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntities); + return updatedEntities; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Updates the given entity with optimistic locking, if the entity is set up to support optimistic + * locking. Otherwise, a normal update is performed. + * + * @param entity + * the entity to update + * @return the updated entity which may be different than the given entity. + */ + public E updateWithOptimisticLock(E entity) { + PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entity); + if (versionMetadata == null) { + return update(entity); + } else { + return updateWithOptimisticLockingInternal(entity, versionMetadata); + } + + } + + /** + * Updates the given list of entities using optimistic locking feature, if the entities are set up + * to support optimistic locking. Otherwise, a normal update is performed. + * + * @param entities + * the entities to update + * @return the updated entities + */ + public List updateWithOptimisticLock(List entities) { + if (entities == null || entities.isEmpty()) { + return new ArrayList<>(); + } + Class entityClass = entities.get(0).getClass(); + PropertyMetadata versionMetadata = EntityIntrospector.getVersionMetadata(entityClass); + if (versionMetadata == null) { + return update(entities); + } else { + return updateWithOptimisticLockInternal(entities, versionMetadata); + } + } + + /** + * Worker method for updating the given entity with optimistic locking. + * + * @param entity + * the entity to update + * @param versionMetadata + * the metadata for optimistic locking + * @return the updated entity + */ + @SuppressWarnings("unchecked") + private E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) { + Transaction transaction = null; + try { + entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity); + Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE); + transaction = datastore.newTransaction(); + Entity storedNativeEntity = transaction.get(nativeEntity.getKey()); + if (storedNativeEntity == null) { + throw new OptimisticLockException( + String.format("Entity does not exist: %s", nativeEntity.getKey())); + } + String versionPropertyName = versionMetadata.getMappedName(); + long version = nativeEntity.getLong(versionPropertyName) - 1; + long storedVersion = storedNativeEntity.getLong(versionPropertyName); + if (version != storedVersion) { + throw new OptimisticLockException( + String.format("Expecting version %d, but found %d", version, storedVersion)); + } + transaction.update(nativeEntity); + transaction.commit(); + E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass()); + entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity); + return updatedEntity; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } finally { + rollbackIfActive(transaction); + } + } + + /** + * Internal worker method for updating the entities using optimistic locking. + * + * @param entities + * the entities to update + * @param versionMetadata + * the metadata of the version property + * @return the updated entities + */ + @SuppressWarnings("unchecked") + private List updateWithOptimisticLockInternal(List entities, + PropertyMetadata versionMetadata) { + Transaction transaction = null; + try { + entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entities); + Entity[] nativeEntities = toNativeEntities(entities, entityManager, Intent.UPDATE); + // The above native entities already have the version incremented by + // the marshalling process + Key[] nativeKeys = new Key[nativeEntities.length]; + for (int i = 0; i < nativeEntities.length; i++) { + nativeKeys[i] = nativeEntities[i].getKey(); + } + transaction = datastore.newTransaction(); + List storedNativeEntities = transaction.fetch(nativeKeys); + String versionPropertyName = versionMetadata.getMappedName(); + + for (int i = 0; i < nativeEntities.length; i++) { + long version = nativeEntities[i].getLong(versionPropertyName) - 1; + Entity storedNativeEntity = storedNativeEntities.get(i); + if (storedNativeEntity == null) { + throw new OptimisticLockException( + String.format("Entity does not exist: %s", nativeKeys[i])); + } + long storedVersion = storedNativeEntities.get(i).getLong(versionPropertyName); + if (version != storedVersion) { + throw new OptimisticLockException( + String.format("Expecting version %d, but found %d", version, storedVersion)); + } + } + transaction.update(nativeEntities); + transaction.commit(); + List updatedEntities = (List) toEntities(entities.get(0).getClass(), nativeEntities); + entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntities); + return updatedEntities; + + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } finally { + rollbackIfActive(transaction); + } + + } + + /** + * Updates or inserts the given entity in the Cloud Datastore. If the entity does not have an ID, + * it may be generated. + * + * @param entity + * the entity to update or insert + * @return the updated/inserted entity. + * @throws EntityManagerException + * if any error occurs while saving. + */ + public E upsert(E entity) { + try { + entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entity); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(entityManager, entity, + Intent.UPSERT); + Entity upsertedNativeEntity = nativeWriter.put(nativeEntity); + @SuppressWarnings("unchecked") + E upsertedEntity = (E) Unmarshaller.unmarshal(upsertedNativeEntity, entity.getClass()); + entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntity); + return upsertedEntity; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Updates or inserts the given list of entities in the Cloud Datastore. If the entities do not + * have a valid ID, IDs may be generated. + * + * @param entities + * the entities to update/or insert. + * @return the updated or inserted entities + * @throws EntityManagerException + * if any error occurs while saving. + */ + @SuppressWarnings("unchecked") + public List upsert(List entities) { + if (entities == null || entities.isEmpty()) { + return new ArrayList<>(); + } + try { + entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entities); + FullEntity[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); + Class entityClass = entities.get(0).getClass(); + List upsertedNativeEntities = nativeWriter.put(nativeEntities); + List upsertedEntities = (List) toEntities(entityClass, upsertedNativeEntities); + entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntities); + return upsertedEntities; + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the given entity from the Cloud Datastore. + * + * @param entity + * the entity to delete. The entity must have it ID set for the deletion to succeed. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + public void delete(Object entity) { + try { + entityManager.executeEntityListeners(CallbackType.PRE_DELETE, entity); + Key nativeKey = Marshaller.marshalKey(entityManager, entity); + nativeWriter.delete(nativeKey); + entityManager.executeEntityListeners(CallbackType.POST_DELETE, entity); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the given entities from the Cloud Datastore. + * + * @param entities + * the entities to delete. The entities must have it ID set for the deletion to succeed. + * @throws EntityManagerException + * if any error occurs while deleting. + */ + public void delete(List entities) { + try { + entityManager.executeEntityListeners(CallbackType.PRE_DELETE, entities); + Key[] nativeKeys = new Key[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + nativeKeys[i] = Marshaller.marshalKey(entityManager, entities.get(i)); + } + nativeWriter.delete(nativeKeys); + entityManager.executeEntityListeners(CallbackType.POST_DELETE, entities); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the entity with the given ID. The entity is assumed to be a root entity (no parent). + * The entity kind will be determined from the supplied entity class. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public void delete(Class entityClass, long id) { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()) + .newKey(id); + nativeWriter.delete(nativeKey); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the entity with the given ID. The entity is assumed to be a root entity (no parent). + * The entity kind will be determined from the supplied entity class. + * + * @param entityClass + * the entity class. + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public void delete(Class entityClass, String id) { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()) + .newKey(id); + nativeWriter.delete(nativeKey); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the entity with the given ID and parent key. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public void delete(Class entityClass, DatastoreKey parentKey, long id) { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); + nativeWriter.delete(nativeKey); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the entity with the given ID and parent key. + * + * @param entityClass + * the entity class. + * @param parentKey + * the parent key + * @param id + * the ID of the entity. + * @throws EntityManagerException + * if any error occurs while inserting. + */ + public void delete(Class entityClass, DatastoreKey parentKey, String id) { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); + nativeWriter.delete(nativeKey); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes an entity given its key. + * + * @param key + * the entity's key + * @throws EntityManagerException + * if any error occurs while deleting. + */ + public void deleteByKey(DatastoreKey key) { + try { + nativeWriter.delete(key.nativeKey()); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } + + /** + * Deletes the entities having the given keys. + * + * @param keys + * the entities' keys + * @throws EntityManagerException + * if any error occurs while deleting. + */ + public void deleteByKey(List keys) { + try { + Key[] nativeKeys = new Key[keys.size()]; + for (int i = 0; i < keys.size(); i++) { + nativeKeys[i] = keys.get(i).nativeKey(); + } + nativeWriter.delete(nativeKeys); + } catch (DatastoreException exp) { + throw DatastoreUtils.wrap(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java b/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java index 3dc3198..0241f16 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java +++ b/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Method; @@ -47,513 +48,513 @@ import com.jmethods.catatumbo.impl.IdentifierMetadata.DataType; /** - * Default implementation of {@link EntityManager} interface. Manages entities - * in the Cloud Datastore such as inserting entities, updating, deleting, - * retrieving, etc. In addition to the standard CRUD operations, the - * EntityManager allows running GQL queries to retrieve multiple entities that - * match the specified criteria. + * Default implementation of {@link EntityManager} interface. Manages entities in the Cloud + * Datastore such as inserting entities, updating, deleting, retrieving, etc. In addition to the + * standard CRUD operations, the EntityManager allows running GQL queries to retrieve multiple + * entities that match the specified criteria. * * @author Sai Pullabhotla */ public class DefaultEntityManager implements EntityManager { - /** - * Batch size for sending delete requests when using the deleteAll method - */ - private static final int DEFAULT_DELETE_ALL_BATCH_SIZE = 100; - - /** - * Reference to the native Datastore object - */ - private Datastore datastore; - - /** - * Datastore writer - */ - private DefaultDatastoreWriter writer; - - /** - * Datastore reader - */ - private DefaultDatastoreReader reader; - - /** - * Metadata of global callbacks - */ - private Map> globalCallbacks; - - /** - * Creates a new instance of DefaultEntityManager. - * - * @param datastore - * the Datastore object - */ - public DefaultEntityManager(Datastore datastore) { - this.datastore = datastore; - writer = new DefaultDatastoreWriter(this); - reader = new DefaultDatastoreReader(this); - } - - /** - * Returns the underlying Datastore object. - * - * @return the underlying Datastore object. - */ - public Datastore getDatastore() { - return datastore; - } - - @Override - public long deleteAll(Class entityClass) { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); - return deleteAll(entityMetadata.getKind()); - } - - @Override - public long deleteAll(String kind) { - if (Utility.isNullOrEmpty(kind)) { - throw new IllegalArgumentException("kind cannot be null or blank"); - } - String query = "SELECT __key__ FROM " + kind; - try { - GqlQuery gqlQuery = Query.newGqlQueryBuilder(Query.ResultType.KEY, query) - .setNamespace(getEffectiveNamespace()).build(); - QueryResults keys = datastore.run(gqlQuery); - Key[] nativeKeys = new Key[DEFAULT_DELETE_ALL_BATCH_SIZE]; - long deleteCount = 0; - int i = 0; - while (keys.hasNext()) { - nativeKeys[i++] = keys.next(); - if (i % DEFAULT_DELETE_ALL_BATCH_SIZE == 0) { - datastore.delete(nativeKeys); - deleteCount += DEFAULT_DELETE_ALL_BATCH_SIZE; - i = 0; - } - } - if (i > 0) { - datastore.delete(Arrays.copyOfRange(nativeKeys, 0, i)); - deleteCount += i; - } - return deleteCount; - } catch (DatastoreException exp) { - throw new EntityManagerException(exp); - } - } - - @Override - public DefaultDatastoreTransaction newTransaction() { - return new DefaultDatastoreTransaction(this); - } - - @Override - public DatastoreBatch newBatch() { - return new DefaultDatastoreBatch(this); - } - - @Override - public T executeInTransaction(TransactionalTask task) { - DatastoreTransaction transaction = null; - try { - transaction = newTransaction(); - T returnValue = task.execute(transaction); - transaction.commit(); - return returnValue; - } catch (Exception exp) { - if (transaction != null) { - transaction.rollback(); - } - throw new EntityManagerException(exp); - } finally { - if (transaction != null && transaction.isActive()) { - transaction.rollback(); - } - } - } - - @Override - public E insert(E entity) { - return writer.insert(entity); - } - - @Override - public List insert(List entities) { - return writer.insert(entities); - } - - @Override - public E update(E entity) { - return writer.updateWithOptimisticLock(entity); - } - - @Override - public List update(List entities) { - return writer.updateWithOptimisticLock(entities); - } - - @Override - public E upsert(E entity) { - return writer.upsert(entity); - } - - @Override - public List upsert(List entities) { - return writer.upsert(entities); - } - - @Override - public void delete(Object entity) { - writer.delete(entity); - } - - @Override - public void delete(List entities) { - writer.delete(entities); - } - - @Override - public void deleteByKey(DatastoreKey key) { - writer.deleteByKey(key); - } - - @Override - public void deleteByKey(List keys) { - writer.deleteByKey(keys); - } - - @Override - public void delete(Class entityClass, long id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, String id) { - writer.delete(entityClass, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, long id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public void delete(Class entityClass, DatastoreKey parentKey, String id) { - writer.delete(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, long id) { - return reader.load(entityClass, id); - } - - @Override - public List loadById(Class entityClass, List identifiers) { - return reader.loadById(entityClass, identifiers); - } - - @Override - public E load(Class entityClass, String id) { - return reader.load(entityClass, id); - } - - @Override - public List loadByName(Class entityClass, List identifiers) { - return reader.loadByName(entityClass, identifiers); - } - - @Override - public E load(Class entityClass, DatastoreKey parentKey, long id) { - return reader.load(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, DatastoreKey parentKey, String id) { - return reader.load(entityClass, parentKey, id); - } - - @Override - public E load(Class entityClass, DatastoreKey key) { - return reader.load(entityClass, key); - } - - @Override - public List loadByKey(Class entityClass, List keys) { - return reader.loadByKey(entityClass, keys); - } - - @Override - public EntityQueryRequest createEntityQueryRequest(String query) { - return reader.createEntityQueryRequest(query); - } - - @Override - public ProjectionQueryRequest createProjectionQueryRequest(String query) { - return reader.createProjectionQueryRequest(query); - } - - @Override - public KeyQueryRequest createKeyQueryRequest(String query) { - return reader.createKeyQueryRequest(query); - } - - @Override - public QueryResponse executeEntityQueryRequest(Class expectedResultType, EntityQueryRequest request) { - return reader.executeEntityQueryRequest(expectedResultType, request); - } - - @Override - public QueryResponse executeProjectionQueryRequest(Class expectedResultType, - ProjectionQueryRequest request) { - return reader.executeProjectionQueryRequest(expectedResultType, request); - } - - @Override - public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { - return reader.executeKeyQueryRequest(request); - } - - @Override - public DatastoreMetadata getDatastoreMetadata() { - return new DefaultDatastoreMetadata(this); - } - - @Override - public DatastoreStats getDatastoreStats() { - return new DefaultDatastoreStats(this); - } - - @Override - public DatastoreKey allocateId(Object entity) { - List keys = allocateId(Arrays.asList(new Object[] { entity })); - return keys.get(0); - } - - @Override - public List allocateId(List entities) { - for (Object entity : entities) { - IdentifierMetadata identifierMetadata = EntityIntrospector.getIdentifierMetadata(entity); - if (DataType.STRING == identifierMetadata.getDataType()) { - throw new IllegalArgumentException("ID allocation is only valid for entities with numeric identifiers"); - } - Object id = IntrospectionUtils.getFieldValue(identifierMetadata, entity); - if (!(id == null || ((long) id) == 0)) { - throw new IllegalArgumentException("ID allocation is only valid for entities with a null or zero ID"); - } - } - IncompleteKey[] incompleteKeys = new IncompleteKey[entities.size()]; - int i = 0; - for (Object entity : entities) { - incompleteKeys[i++] = getIncompleteKey(entity); - } - List nativeKeys = datastore.allocateId(incompleteKeys); - return DatastoreUtils.toDatastoreKeys(nativeKeys); - } - - /** - * Returns an IncompleteKey of the given entity. - * - * @param entity - * the entity - * @return the incomplete key - */ - private IncompleteKey getIncompleteKey(Object entity) { - EntityMetadata entityMetadata = EntityIntrospector.introspect(entity.getClass()); - String kind = entityMetadata.getKind(); - ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); - DatastoreKey parentKey = null; - IncompleteKey incompleteKey = null; - if (parentKeyMetadata != null) { - parentKey = (DatastoreKey) IntrospectionUtils.getFieldValue(parentKeyMetadata, entity); - } - if (parentKey != null) { - incompleteKey = IncompleteKey.newBuilder(parentKey.nativeKey(), kind).build(); - } else { - incompleteKey = IncompleteKey.newBuilder(datastore.getOptions().getProjectId(), kind) - .setNamespace(getEffectiveNamespace()).build(); - } - return incompleteKey; - } - - @Override - public void setDefaultListeners(Class... entityListeners) { - globalCallbacks = new EnumMap<>(CallbackType.class); - for (Class listenerClass : entityListeners) { - ExternalListenerMetadata listenerMetadata = ExternalListenerIntrospector.introspect(listenerClass); - Map callbacks = listenerMetadata.getCallbacks(); - if (callbacks != null) { - for (Map.Entry entry : callbacks.entrySet()) { - CallbackType callbackType = entry.getKey(); - Method callbackMethod = entry.getValue(); - CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.DEFAULT, callbackType, - callbackMethod); - putDefaultCallback(callbackType, callbackMetadata); - } - } - } - } - - /** - * Puts/adds the given callback type and its metadata to the list of default - * listeners. - * - * @param callbackType - * the event type - * @param metadata - * the callback metadata - */ - private void putDefaultCallback(CallbackType callbackType, CallbackMetadata metadata) { - List metadataList = globalCallbacks.get(callbackType); - if (metadataList == null) { - metadataList = new ArrayList<>(); - globalCallbacks.put(callbackType, metadataList); - } - metadataList.add(metadata); - } - - /** - * Executes the entity listeners associated with the given entity. - * - * @param callbackType - * the event type - * @param entity - * the entity that produced the event - */ - public void executeEntityListeners(CallbackType callbackType, Object entity) { - // We may get null entities here. For example loading a nonexistent ID - // or IDs. - if (entity == null) { - return; - } - EntityListenersMetadata entityListenersMetadata = EntityIntrospector.getEntityListenersMetadata(entity); - List callbacks = entityListenersMetadata.getCallbacks(callbackType); - if (!entityListenersMetadata.isExcludeDefaultListeners()) { - executeGlobalListeners(callbackType, entity); - } - if (callbacks == null) { - return; - } - for (CallbackMetadata callback : callbacks) { - switch (callback.getListenerType()) { - case EXTERNAL: - Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); - invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); - break; - case INTERNAL: - invokeCallbackMethod(callback.getCallbackMethod(), entity); - break; - default: - String message = String.format("Unknown or unimplemented callback listener type: %s", - callback.getListenerType()); - throw new EntityManagerException(message); - } - } - } - - /** - * Executes the entity listeners associated with the given list of entities. - * - * @param callbackType - * the callback type - * @param entities - * the entities - */ - public void executeEntityListeners(CallbackType callbackType, List entities) { - for (Object entity : entities) { - executeEntityListeners(callbackType, entity); - } - } - - /** - * Executes the global listeners for the given event type for the given - * entity. - * - * @param callbackType - * the event type - * @param entity - * the entity - */ - private void executeGlobalListeners(CallbackType callbackType, Object entity) { - if (globalCallbacks == null) { - return; - } - List callbacks = globalCallbacks.get(callbackType); - if (callbacks == null) { - return; - } - for (CallbackMetadata callback : callbacks) { - Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); - invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); - } - } - - /** - * Invokes the given callback method on the given target object. - * - * @param callbackMethod - * the callback method - * @param listener - * the listener object on which to invoke the method - * @param entity - * the entity for which the callback is being invoked. - */ - private static void invokeCallbackMethod(Method callbackMethod, Object listener, Object entity) { - try { - callbackMethod.invoke(listener, entity); - } catch (Exception exp) { - String message = String.format("Failed to execute callback method %s of class %s", callbackMethod.getName(), - callbackMethod.getDeclaringClass().getName()); - throw new EntityManagerException(message, exp); - } - - } - - /** - * Invokes the given callback method on the given target object. - * - * @param callbackMethod - * the callback method - * @param entity - * the entity for which the callback is being invoked - */ - private static void invokeCallbackMethod(Method callbackMethod, Object entity) { - try { - callbackMethod.invoke(entity); - } catch (Exception exp) { - String message = String.format("Failed to execute callback method %s of class %s", callbackMethod.getName(), - callbackMethod.getDeclaringClass().getName()); - throw new EntityManagerException(message, exp); - } - - } - - /** - * Creates and returns a new native KeyFactory. If a namespace was specified - * using {@link Tenant}, the returned KeyFactory will have the specified - * namespace. - * - * @return a {@link KeyFactory} - */ - KeyFactory newNativeKeyFactory() { - KeyFactory keyFactory = datastore.newKeyFactory(); - String namespace = Tenant.getNamespace(); - if (namespace != null) { - keyFactory.setNamespace(namespace); - } - return keyFactory; - } - - /** - * Returns the effective namespace. If a namespace was specified using - * {@link Tenant}, it will be returned. Otherwise, the namespace of this - * EntityManager is returned. - * - * @return the effective namespace. - */ - String getEffectiveNamespace() { - String namespace = Tenant.getNamespace(); - if (namespace == null) { - namespace = datastore.getOptions().getNamespace(); - } - return namespace; - } + /** + * Batch size for sending delete requests when using the deleteAll method + */ + private static final int DEFAULT_DELETE_ALL_BATCH_SIZE = 100; + + /** + * Reference to the native Datastore object + */ + private Datastore datastore; + + /** + * Datastore writer + */ + private DefaultDatastoreWriter writer; + + /** + * Datastore reader + */ + private DefaultDatastoreReader reader; + + /** + * Metadata of global callbacks + */ + private Map> globalCallbacks; + + /** + * Creates a new instance of DefaultEntityManager. + * + * @param datastore + * the Datastore object + */ + public DefaultEntityManager(Datastore datastore) { + this.datastore = datastore; + writer = new DefaultDatastoreWriter(this); + reader = new DefaultDatastoreReader(this); + } + + /** + * Returns the underlying Datastore object. + * + * @return the underlying Datastore object. + */ + public Datastore getDatastore() { + return datastore; + } + + @Override + public long deleteAll(Class entityClass) { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); + return deleteAll(entityMetadata.getKind()); + } + + @Override + public long deleteAll(String kind) { + if (Utility.isNullOrEmpty(kind)) { + throw new IllegalArgumentException("kind cannot be null or blank"); + } + String query = "SELECT __key__ FROM " + kind; + try { + GqlQuery gqlQuery = Query.newGqlQueryBuilder(Query.ResultType.KEY, query) + .setNamespace(getEffectiveNamespace()).build(); + QueryResults keys = datastore.run(gqlQuery); + Key[] nativeKeys = new Key[DEFAULT_DELETE_ALL_BATCH_SIZE]; + long deleteCount = 0; + int i = 0; + while (keys.hasNext()) { + nativeKeys[i++] = keys.next(); + if (i % DEFAULT_DELETE_ALL_BATCH_SIZE == 0) { + datastore.delete(nativeKeys); + deleteCount += DEFAULT_DELETE_ALL_BATCH_SIZE; + i = 0; + } + } + if (i > 0) { + datastore.delete(Arrays.copyOfRange(nativeKeys, 0, i)); + deleteCount += i; + } + return deleteCount; + } catch (DatastoreException exp) { + throw new EntityManagerException(exp); + } + } + + @Override + public DefaultDatastoreTransaction newTransaction() { + return new DefaultDatastoreTransaction(this); + } + + @Override + public DatastoreBatch newBatch() { + return new DefaultDatastoreBatch(this); + } + + @Override + public T executeInTransaction(TransactionalTask task) { + DatastoreTransaction transaction = null; + try { + transaction = newTransaction(); + T returnValue = task.execute(transaction); + transaction.commit(); + return returnValue; + } catch (Exception exp) { + if (transaction != null) { + transaction.rollback(); + } + throw new EntityManagerException(exp); + } finally { + if (transaction != null && transaction.isActive()) { + transaction.rollback(); + } + } + } + + @Override + public E insert(E entity) { + return writer.insert(entity); + } + + @Override + public List insert(List entities) { + return writer.insert(entities); + } + + @Override + public E update(E entity) { + return writer.updateWithOptimisticLock(entity); + } + + @Override + public List update(List entities) { + return writer.updateWithOptimisticLock(entities); + } + + @Override + public E upsert(E entity) { + return writer.upsert(entity); + } + + @Override + public List upsert(List entities) { + return writer.upsert(entities); + } + + @Override + public void delete(Object entity) { + writer.delete(entity); + } + + @Override + public void delete(List entities) { + writer.delete(entities); + } + + @Override + public void delete(Class entityClass, long id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, String id) { + writer.delete(entityClass, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, long id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void delete(Class entityClass, DatastoreKey parentKey, String id) { + writer.delete(entityClass, parentKey, id); + } + + @Override + public void deleteByKey(DatastoreKey key) { + writer.deleteByKey(key); + } + + @Override + public void deleteByKey(List keys) { + writer.deleteByKey(keys); + } + + @Override + public E load(Class entityClass, long id) { + return reader.load(entityClass, id); + } + + @Override + public E load(Class entityClass, String id) { + return reader.load(entityClass, id); + } + + @Override + public E load(Class entityClass, DatastoreKey parentKey, long id) { + return reader.load(entityClass, parentKey, id); + } + + @Override + public E load(Class entityClass, DatastoreKey parentKey, String id) { + return reader.load(entityClass, parentKey, id); + } + + @Override + public E load(Class entityClass, DatastoreKey key) { + return reader.load(entityClass, key); + } + + @Override + public List loadById(Class entityClass, List identifiers) { + return reader.loadById(entityClass, identifiers); + } + + @Override + public List loadByName(Class entityClass, List identifiers) { + return reader.loadByName(entityClass, identifiers); + } + + @Override + public List loadByKey(Class entityClass, List keys) { + return reader.loadByKey(entityClass, keys); + } + + @Override + public EntityQueryRequest createEntityQueryRequest(String query) { + return reader.createEntityQueryRequest(query); + } + + @Override + public ProjectionQueryRequest createProjectionQueryRequest(String query) { + return reader.createProjectionQueryRequest(query); + } + + @Override + public KeyQueryRequest createKeyQueryRequest(String query) { + return reader.createKeyQueryRequest(query); + } + + @Override + public QueryResponse executeEntityQueryRequest(Class expectedResultType, + EntityQueryRequest request) { + return reader.executeEntityQueryRequest(expectedResultType, request); + } + + @Override + public QueryResponse executeProjectionQueryRequest(Class expectedResultType, + ProjectionQueryRequest request) { + return reader.executeProjectionQueryRequest(expectedResultType, request); + } + + @Override + public QueryResponse executeKeyQueryRequest(KeyQueryRequest request) { + return reader.executeKeyQueryRequest(request); + } + + @Override + public DatastoreMetadata getDatastoreMetadata() { + return new DefaultDatastoreMetadata(this); + } + + @Override + public DatastoreStats getDatastoreStats() { + return new DefaultDatastoreStats(this); + } + + @Override + public DatastoreKey allocateId(Object entity) { + List keys = allocateId(Arrays.asList(new Object[] { entity })); + return keys.get(0); + } + + @Override + public List allocateId(List entities) { + for (Object entity : entities) { + IdentifierMetadata identifierMetadata = EntityIntrospector.getIdentifierMetadata(entity); + if (DataType.STRING == identifierMetadata.getDataType()) { + throw new IllegalArgumentException( + "ID allocation is only valid for entities with numeric identifiers"); + } + Object id = IntrospectionUtils.getFieldValue(identifierMetadata, entity); + if (!(id == null || ((long) id) == 0)) { + throw new IllegalArgumentException( + "ID allocation is only valid for entities with a null or zero ID"); + } + } + IncompleteKey[] incompleteKeys = new IncompleteKey[entities.size()]; + int i = 0; + for (Object entity : entities) { + incompleteKeys[i++] = getIncompleteKey(entity); + } + List nativeKeys = datastore.allocateId(incompleteKeys); + return DatastoreUtils.toDatastoreKeys(nativeKeys); + } + + /** + * Returns an IncompleteKey of the given entity. + * + * @param entity + * the entity + * @return the incomplete key + */ + private IncompleteKey getIncompleteKey(Object entity) { + EntityMetadata entityMetadata = EntityIntrospector.introspect(entity.getClass()); + String kind = entityMetadata.getKind(); + ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); + DatastoreKey parentKey = null; + IncompleteKey incompleteKey = null; + if (parentKeyMetadata != null) { + parentKey = (DatastoreKey) IntrospectionUtils.getFieldValue(parentKeyMetadata, entity); + } + if (parentKey != null) { + incompleteKey = IncompleteKey.newBuilder(parentKey.nativeKey(), kind).build(); + } else { + incompleteKey = IncompleteKey.newBuilder(datastore.getOptions().getProjectId(), kind) + .setNamespace(getEffectiveNamespace()).build(); + } + return incompleteKey; + } + + @Override + public void setDefaultListeners(Class... entityListeners) { + globalCallbacks = new EnumMap<>(CallbackType.class); + for (Class listenerClass : entityListeners) { + ExternalListenerMetadata listenerMetadata = ExternalListenerIntrospector + .introspect(listenerClass); + Map callbacks = listenerMetadata.getCallbacks(); + if (callbacks != null) { + for (Map.Entry entry : callbacks.entrySet()) { + CallbackType callbackType = entry.getKey(); + Method callbackMethod = entry.getValue(); + CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.DEFAULT, + callbackType, callbackMethod); + putDefaultCallback(callbackType, callbackMetadata); + } + } + } + } + + /** + * Puts/adds the given callback type and its metadata to the list of default listeners. + * + * @param callbackType + * the event type + * @param metadata + * the callback metadata + */ + private void putDefaultCallback(CallbackType callbackType, CallbackMetadata metadata) { + List metadataList = globalCallbacks.get(callbackType); + if (metadataList == null) { + metadataList = new ArrayList<>(); + globalCallbacks.put(callbackType, metadataList); + } + metadataList.add(metadata); + } + + /** + * Executes the entity listeners associated with the given entity. + * + * @param callbackType + * the event type + * @param entity + * the entity that produced the event + */ + public void executeEntityListeners(CallbackType callbackType, Object entity) { + // We may get null entities here. For example loading a nonexistent ID + // or IDs. + if (entity == null) { + return; + } + EntityListenersMetadata entityListenersMetadata = EntityIntrospector + .getEntityListenersMetadata(entity); + List callbacks = entityListenersMetadata.getCallbacks(callbackType); + if (!entityListenersMetadata.isExcludeDefaultListeners()) { + executeGlobalListeners(callbackType, entity); + } + if (callbacks == null) { + return; + } + for (CallbackMetadata callback : callbacks) { + switch (callback.getListenerType()) { + case EXTERNAL: + Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); + invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); + break; + case INTERNAL: + invokeCallbackMethod(callback.getCallbackMethod(), entity); + break; + default: + String message = String.format("Unknown or unimplemented callback listener type: %s", + callback.getListenerType()); + throw new EntityManagerException(message); + } + } + } + + /** + * Executes the entity listeners associated with the given list of entities. + * + * @param callbackType + * the callback type + * @param entities + * the entities + */ + public void executeEntityListeners(CallbackType callbackType, List entities) { + for (Object entity : entities) { + executeEntityListeners(callbackType, entity); + } + } + + /** + * Executes the global listeners for the given event type for the given entity. + * + * @param callbackType + * the event type + * @param entity + * the entity + */ + private void executeGlobalListeners(CallbackType callbackType, Object entity) { + if (globalCallbacks == null) { + return; + } + List callbacks = globalCallbacks.get(callbackType); + if (callbacks == null) { + return; + } + for (CallbackMetadata callback : callbacks) { + Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); + invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); + } + } + + /** + * Invokes the given callback method on the given target object. + * + * @param callbackMethod + * the callback method + * @param listener + * the listener object on which to invoke the method + * @param entity + * the entity for which the callback is being invoked. + */ + private static void invokeCallbackMethod(Method callbackMethod, Object listener, Object entity) { + try { + callbackMethod.invoke(listener, entity); + } catch (Exception exp) { + String message = String.format("Failed to execute callback method %s of class %s", + callbackMethod.getName(), callbackMethod.getDeclaringClass().getName()); + throw new EntityManagerException(message, exp); + } + + } + + /** + * Invokes the given callback method on the given target object. + * + * @param callbackMethod + * the callback method + * @param entity + * the entity for which the callback is being invoked + */ + private static void invokeCallbackMethod(Method callbackMethod, Object entity) { + try { + callbackMethod.invoke(entity); + } catch (Exception exp) { + String message = String.format("Failed to execute callback method %s of class %s", + callbackMethod.getName(), callbackMethod.getDeclaringClass().getName()); + throw new EntityManagerException(message, exp); + } + + } + + /** + * Creates and returns a new native KeyFactory. If a namespace was specified using {@link Tenant}, + * the returned KeyFactory will have the specified namespace. + * + * @return a {@link KeyFactory} + */ + KeyFactory newNativeKeyFactory() { + KeyFactory keyFactory = datastore.newKeyFactory(); + String namespace = Tenant.getNamespace(); + if (namespace != null) { + keyFactory.setNamespace(namespace); + } + return keyFactory; + } + + /** + * Returns the effective namespace. If a namespace was specified using {@link Tenant}, it will be + * returned. Otherwise, the namespace of this EntityManager is returned. + * + * @return the effective namespace. + */ + String getEffectiveNamespace() { + String namespace = Tenant.getNamespace(); + if (namespace == null) { + namespace = datastore.getOptions().getNamespace(); + } + return namespace; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EmbeddableIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/EmbeddableIntrospector.java index 2553796..e2f9262 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EmbeddableIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EmbeddableIntrospector.java @@ -24,107 +24,106 @@ import com.jmethods.catatumbo.EntityManagerException; /** - * Introspects an {@link Embeddable} class and prepares the metadata for the - * class. + * Introspects an {@link Embeddable} class and prepares the metadata for the class. * * @author Sai Pullabhotla * */ public class EmbeddableIntrospector { - /** - * Embeddable class. - */ - private final Class embeddableClass; + /** + * Embeddable class. + */ + private final Class embeddableClass; - /** - * Output - the metadata of the Embeddable class. - */ - private EmbeddableMetadata metadata; + /** + * Output - the metadata of the Embeddable class. + */ + private EmbeddableMetadata metadata; - /** - * Creates a new instance if EmbeddableIntrospector. - * - * @param embeddableClass - * the Embeddable class to introspect - */ - private EmbeddableIntrospector(Class embeddableClass) { - this.embeddableClass = embeddableClass; - } + /** + * Creates a new instance if EmbeddableIntrospector. + * + * @param embeddableClass + * the Embeddable class to introspect + */ + private EmbeddableIntrospector(Class embeddableClass) { + this.embeddableClass = embeddableClass; + } - /** - * Introspects the given Embeddable class and returns the metadata. - * - * @param embeddableClass - * the Embeddable class - * @return the metadata of the given class - */ - public static EmbeddableMetadata introspect(Class embeddableClass) { - EmbeddableIntrospector introspector = new EmbeddableIntrospector(embeddableClass); - introspector.introspect(); - return introspector.metadata; - } + /** + * Introspects the given Embeddable class and returns the metadata. + * + * @param embeddableClass + * the Embeddable class + * @return the metadata of the given class + */ + public static EmbeddableMetadata introspect(Class embeddableClass) { + EmbeddableIntrospector introspector = new EmbeddableIntrospector(embeddableClass); + introspector.introspect(); + return introspector.metadata; + } - /** - * Introspects the Embeddable. - */ - private void introspect() { - // Make sure the class is Embeddable - if (!embeddableClass.isAnnotationPresent(Embeddable.class)) { - String message = String.format("Class %s must have %s annotation", embeddableClass.getName(), - Embeddable.class.getName()); - throw new EntityManagerException(message); - } - metadata = new EmbeddableMetadata(embeddableClass); - processFields(); - } + /** + * Introspects the Embeddable. + */ + private void introspect() { + // Make sure the class is Embeddable + if (!embeddableClass.isAnnotationPresent(Embeddable.class)) { + String message = String.format("Class %s must have %s annotation", embeddableClass.getName(), + Embeddable.class.getName()); + throw new EntityManagerException(message); + } + metadata = new EmbeddableMetadata(embeddableClass); + processFields(); + } - /** - * Processes each field in this Embeddable and updates the metadata. - */ - private void processFields() { - List fields = IntrospectionUtils.getPersistableFields(embeddableClass); - for (Field field : fields) { - if (field.isAnnotationPresent(Embedded.class)) { - processEmbeddedField(field); - } else { - processSimpleField(field); - } - } - } + /** + * Processes each field in this Embeddable and updates the metadata. + */ + private void processFields() { + List fields = IntrospectionUtils.getPersistableFields(embeddableClass); + for (Field field : fields) { + if (field.isAnnotationPresent(Embedded.class)) { + processEmbeddedField(field); + } else { + processSimpleField(field); + } + } + } - /** - * Processes the given simple (or primitive) field and updates the metadata. - * - * @param field - * the field to process - */ - private void processSimpleField(Field field) { - PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(field); - if (propertyMetadata != null) { - metadata.putPropertyMetadata(propertyMetadata); - } - } + /** + * Processes the given simple (or primitive) field and updates the metadata. + * + * @param field + * the field to process + */ + private void processSimpleField(Field field) { + PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(field); + if (propertyMetadata != null) { + metadata.putPropertyMetadata(propertyMetadata); + } + } - /** - * Processes a nested embedded field. - * - * @param field - * the embedded field. - */ - private void processEmbeddedField(Field field) { - // We are creating a PropertyMetadata for the embedded field... The new - // Mapper, EmbeddedObjectMapper, takes care of mapping embedded fields - // to embedded entities. - Embedded embeddedAnnotation = field.getAnnotation(Embedded.class); - String name = embeddedAnnotation.name(); - if (name == null || name.trim().length() == 0) { - name = field.getName(); - } - boolean indexed = embeddedAnnotation.indexed(); - boolean optional = embeddedAnnotation.optional(); - PropertyMetadata propertyMetadata = new PropertyMetadata(field, name, indexed, optional); - metadata.putPropertyMetadata(propertyMetadata); - } + /** + * Processes a nested embedded field. + * + * @param field + * the embedded field. + */ + private void processEmbeddedField(Field field) { + // We are creating a PropertyMetadata for the embedded field... The new + // Mapper, EmbeddedObjectMapper, takes care of mapping embedded fields + // to embedded entities. + Embedded embeddedAnnotation = field.getAnnotation(Embedded.class); + String name = embeddedAnnotation.name(); + if (name == null || name.trim().length() == 0) { + name = field.getName(); + } + boolean indexed = embeddedAnnotation.indexed(); + boolean optional = embeddedAnnotation.optional(); + PropertyMetadata propertyMetadata = new PropertyMetadata(field, name, indexed, optional); + metadata.putPropertyMetadata(propertyMetadata); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EmbeddableMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/EmbeddableMetadata.java index 04cf9a5..efd3143 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EmbeddableMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EmbeddableMetadata.java @@ -26,14 +26,14 @@ */ public class EmbeddableMetadata extends MetadataBase { - /** - * Creates a new instance of EmbeddableMetadata. - * - * @param clazz - * the Embeddable class - */ - public EmbeddableMetadata(Class clazz) { - super(clazz); - } + /** + * Creates a new instance of EmbeddableMetadata. + * + * @param clazz + * the Embeddable class + */ + public EmbeddableMetadata(Class clazz) { + super(clazz); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedField.java b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedField.java index 4a3f81c..6c13a8a 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedField.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedField.java @@ -27,133 +27,132 @@ */ public class EmbeddedField { - /** - * The underlying field - */ - private Field field; - - /** - * Parent embedded field, if any - */ - private EmbeddedField parent; - - /** - * Qualified name of this embedded field (e.g. If city is a field in Address - * class and Address is embedded in a class called Customer as - * billingAddress, the qualified name of this field would be - * billingAddress.city). - */ - private String qualifiedName; - - /** - * Creates a new instance of EmbeddedField. - * - * @param field - * the underlying field - */ - public EmbeddedField(Field field) { - this(field, null); - } - - /** - * Creates a new instance of EmbeddedField. - * - * @param field - * the underlying field - * @param parent - * the parent embedded field. May be null. - */ - public EmbeddedField(Field field, EmbeddedField parent) { - this.field = field; - this.parent = parent; - computeQualifiedName(); - } - - /** - * Returns the underlying field. - * - * @return the field the underlying field. - */ - public Field getField() { - return field; - } - - /** - * Returns the parent field. - * - * @return the parent field. - */ - public EmbeddedField getParent() { - return parent; - } - - /** - * Returns the qualified name of this embedded field. - * - * @return the qualified name of this embedded field. - */ - public String getQualifiedName() { - return qualifiedName; - } - - /** - * Returns the type of this field. - * - * @return the type of this field. - */ - public Class getType() { - return field.getType(); - } - - /** - * Returns the name of this field. - * - * @return the name of this field. - */ - public String getName() { - return field.getName(); - } - - /** - * Returns the class in which this field is declared. - * - * @return the class in which this field is declared. - */ - public Class getDeclaringClass() { - return field.getDeclaringClass(); - } - - /** - * Computes and sets the qualified name of this field. - */ - private void computeQualifiedName() { - if (parent != null) { - qualifiedName = parent.qualifiedName + "." + field.getName(); - } else { - qualifiedName = field.getName(); - } - } - - @Override - public String toString() { - return qualifiedName; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof EmbeddedField)) { - return false; - } - if (this == obj) { - return true; - } - EmbeddedField that = (EmbeddedField) obj; - return Objects.equals(this.field, that.field) && Objects.equals(this.parent, that.parent); - } - - @Override - public int hashCode() { - return Objects.hash(field, parent); - } + /** + * The underlying field + */ + private Field field; + + /** + * Parent embedded field, if any + */ + private EmbeddedField parent; + + /** + * Qualified name of this embedded field (e.g. If city is a field in Address class and Address is + * embedded in a class called Customer as billingAddress, the qualified name of this field would + * be billingAddress.city). + */ + private String qualifiedName; + + /** + * Creates a new instance of EmbeddedField. + * + * @param field + * the underlying field + */ + public EmbeddedField(Field field) { + this(field, null); + } + + /** + * Creates a new instance of EmbeddedField. + * + * @param field + * the underlying field + * @param parent + * the parent embedded field. May be null. + */ + public EmbeddedField(Field field, EmbeddedField parent) { + this.field = field; + this.parent = parent; + computeQualifiedName(); + } + + /** + * Returns the underlying field. + * + * @return the field the underlying field. + */ + public Field getField() { + return field; + } + + /** + * Returns the parent field. + * + * @return the parent field. + */ + public EmbeddedField getParent() { + return parent; + } + + /** + * Returns the qualified name of this embedded field. + * + * @return the qualified name of this embedded field. + */ + public String getQualifiedName() { + return qualifiedName; + } + + /** + * Returns the type of this field. + * + * @return the type of this field. + */ + public Class getType() { + return field.getType(); + } + + /** + * Returns the name of this field. + * + * @return the name of this field. + */ + public String getName() { + return field.getName(); + } + + /** + * Returns the class in which this field is declared. + * + * @return the class in which this field is declared. + */ + public Class getDeclaringClass() { + return field.getDeclaringClass(); + } + + /** + * Computes and sets the qualified name of this field. + */ + private void computeQualifiedName() { + if (parent != null) { + qualifiedName = parent.qualifiedName + "." + field.getName(); + } else { + qualifiedName = field.getName(); + } + } + + @Override + public String toString() { + return qualifiedName; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof EmbeddedField)) { + return false; + } + if (this == obj) { + return true; + } + EmbeddedField that = (EmbeddedField) obj; + return Objects.equals(this.field, that.field) && Objects.equals(this.parent, that.parent); + } + + @Override + public int hashCode() { + return Objects.hash(field, parent); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedIntrospector.java index b4d0978..948d4d7 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedIntrospector.java @@ -26,152 +26,152 @@ import com.jmethods.catatumbo.Property; /** - * Introspects and prepares the metadata of an embedded field. An embedded field - * is a complex object that is embedded in an entity or another embedded field. + * Introspects and prepares the metadata of an embedded field. An embedded field is a complex object + * that is embedded in an entity or another embedded field. * * @author Sai Pullabhotla * */ public class EmbeddedIntrospector { - /** - * Embedded field that is being introspected - */ - private final EmbeddedField field; - - /** - * The metadata of the embedded field - */ - private EmbeddedMetadata metadata; - - /** - * The type of the embedded field - */ - private final Class clazz; - - /** - * Metadata of the owning entity - */ - private EntityMetadata entityMetadata; - - /** - * Creates a new instance of EmbeddedIntrospector. - * - * @param field - * the embedded field to introspect. - * @param entityMetadata - * metadata of the owning entity - */ - private EmbeddedIntrospector(EmbeddedField field, EntityMetadata entityMetadata) { - this.field = field; - this.entityMetadata = entityMetadata; - this.clazz = field.getType(); - } - - /** - * Introspects the given embedded field and returns its metadata. - * - * @param field - * the embedded field to introspect - * @param entityMetadata - * metadata of the owning entity - * @return the metadata of the embedded field - */ - public static EmbeddedMetadata introspect(EmbeddedField field, EntityMetadata entityMetadata) { - EmbeddedIntrospector introspector = new EmbeddedIntrospector(field, entityMetadata); - introspector.process(); - return introspector.metadata; - } - - /** - * Worker class for introspection. - */ - private void process() { - metadata = new EmbeddedMetadata(field); - - // Make sure the class has @Embeddable annotation - if (!clazz.isAnnotationPresent(Embeddable.class)) { - String message = String.format("Class %s must have %s annotation", clazz.getName(), - Embeddable.class.getName()); - throw new EntityManagerException(message); - } - - // Check the mapped name and indexed attributes - Embedded embeddedAnnotation = field.getField().getAnnotation(Embedded.class); - String mappedName = embeddedAnnotation.name(); - if (mappedName == null || mappedName.trim().length() == 0) { - mappedName = field.getName(); - } - metadata.setMappedName(mappedName); - metadata.setIndexed(embeddedAnnotation.indexed()); - metadata.setOptional(embeddedAnnotation.optional()); - - // If there is an annotation for storing the embedded with Imploded - // strategy... - if (field.getField().isAnnotationPresent(Imploded.class)) { - metadata.setStorageStrategy(StorageStrategy.IMPLODED); - } - processFields(); - } - - /** - * Processes each field in this embedded object and updates the metadata. - */ - private void processFields() { - List children = IntrospectionUtils.getPersistableFields(clazz); - for (Field child : children) { - if (child.isAnnotationPresent(Embedded.class)) { - processEmbeddedField(child); - } else { - processSimpleField(child); - } - } - } - - /** - * Processes the given simple (or primitive) field and updates the metadata. - * - * @param child - * the field to process - */ - private void processSimpleField(Field child) { - PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(child); - if (propertyMetadata != null) { - // Process override - processPropertyOverride(propertyMetadata); - metadata.putPropertyMetadata(propertyMetadata); - } - } - - /** - * Processes the override, if any, for the given property. - * - * @param propertyMetadata - * the metadata of the property - */ - private void processPropertyOverride(PropertyMetadata propertyMetadata) { - String qualifiedName = field.getQualifiedName() + "." + propertyMetadata.getField().getName(); - Property override = entityMetadata.getPropertyOverride(qualifiedName); - if (override != null) { - String mappedName = override.name(); - if (mappedName != null && mappedName.trim().length() > 0) { - propertyMetadata.setMappedName(mappedName); - } - propertyMetadata.setIndexed(override.indexed()); - propertyMetadata.setOptional(override.optional()); - } - } - - /** - * Processes a nested embedded field. - * - * @param child - * the nested embedded field. - */ - private void processEmbeddedField(Field child) { - EmbeddedField embeddedChild = new EmbeddedField(child, field); - EmbeddedMetadata childMetadata = EmbeddedIntrospector.introspect(embeddedChild, entityMetadata); - metadata.putEmbeddedMetadata(childMetadata); - } + /** + * Embedded field that is being introspected + */ + private final EmbeddedField field; + + /** + * The metadata of the embedded field + */ + private EmbeddedMetadata metadata; + + /** + * The type of the embedded field + */ + private final Class clazz; + + /** + * Metadata of the owning entity + */ + private EntityMetadata entityMetadata; + + /** + * Creates a new instance of EmbeddedIntrospector. + * + * @param field + * the embedded field to introspect. + * @param entityMetadata + * metadata of the owning entity + */ + private EmbeddedIntrospector(EmbeddedField field, EntityMetadata entityMetadata) { + this.field = field; + this.entityMetadata = entityMetadata; + this.clazz = field.getType(); + } + + /** + * Introspects the given embedded field and returns its metadata. + * + * @param field + * the embedded field to introspect + * @param entityMetadata + * metadata of the owning entity + * @return the metadata of the embedded field + */ + public static EmbeddedMetadata introspect(EmbeddedField field, EntityMetadata entityMetadata) { + EmbeddedIntrospector introspector = new EmbeddedIntrospector(field, entityMetadata); + introspector.process(); + return introspector.metadata; + } + + /** + * Worker class for introspection. + */ + private void process() { + metadata = new EmbeddedMetadata(field); + + // Make sure the class has @Embeddable annotation + if (!clazz.isAnnotationPresent(Embeddable.class)) { + String message = String.format("Class %s must have %s annotation", clazz.getName(), + Embeddable.class.getName()); + throw new EntityManagerException(message); + } + + // Check the mapped name and indexed attributes + Embedded embeddedAnnotation = field.getField().getAnnotation(Embedded.class); + String mappedName = embeddedAnnotation.name(); + if (mappedName == null || mappedName.trim().length() == 0) { + mappedName = field.getName(); + } + metadata.setMappedName(mappedName); + metadata.setIndexed(embeddedAnnotation.indexed()); + metadata.setOptional(embeddedAnnotation.optional()); + + // If there is an annotation for storing the embedded with Imploded + // strategy... + if (field.getField().isAnnotationPresent(Imploded.class)) { + metadata.setStorageStrategy(StorageStrategy.IMPLODED); + } + processFields(); + } + + /** + * Processes each field in this embedded object and updates the metadata. + */ + private void processFields() { + List children = IntrospectionUtils.getPersistableFields(clazz); + for (Field child : children) { + if (child.isAnnotationPresent(Embedded.class)) { + processEmbeddedField(child); + } else { + processSimpleField(child); + } + } + } + + /** + * Processes the given simple (or primitive) field and updates the metadata. + * + * @param child + * the field to process + */ + private void processSimpleField(Field child) { + PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(child); + if (propertyMetadata != null) { + // Process override + processPropertyOverride(propertyMetadata); + metadata.putPropertyMetadata(propertyMetadata); + } + } + + /** + * Processes the override, if any, for the given property. + * + * @param propertyMetadata + * the metadata of the property + */ + private void processPropertyOverride(PropertyMetadata propertyMetadata) { + String qualifiedName = field.getQualifiedName() + "." + propertyMetadata.getField().getName(); + Property override = entityMetadata.getPropertyOverride(qualifiedName); + if (override != null) { + String mappedName = override.name(); + if (mappedName != null && mappedName.trim().length() > 0) { + propertyMetadata.setMappedName(mappedName); + } + propertyMetadata.setIndexed(override.indexed()); + propertyMetadata.setOptional(override.optional()); + } + } + + /** + * Processes a nested embedded field. + * + * @param child + * the nested embedded field. + */ + private void processEmbeddedField(Field child) { + EmbeddedField embeddedChild = new EmbeddedField(child, field); + EmbeddedMetadata childMetadata = EmbeddedIntrospector.introspect(embeddedChild, entityMetadata); + metadata.putEmbeddedMetadata(childMetadata); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedMetadata.java index 285beeb..17dd14b 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EmbeddedMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EmbeddedMetadata.java @@ -26,166 +26,161 @@ */ public class EmbeddedMetadata extends MetadataBase { - /** - * The embedded field to which this metadata belongs. - */ - private final EmbeddedField field; - - /** - * Read method for this embedded field - */ - private final MethodHandle readMethod; - - /** - * Write method for this embedded field - */ - private final MethodHandle writeMethod; - - /** - * Storage strategy to use for the embedded field - */ - private StorageStrategy storageStrategy; - - /** - * The property name under which to store this embedded field - */ - private String mappedName; - - /** - * Whether or not to index this embedded field - */ - private boolean indexed; - - /** - * Whether or not this embedded field is optional - */ - private boolean optional = false; - - /** - * Creates a new instance of EmbeddedMetadata. - * - * @param field - * the embedded field to which this metadata belongs - */ - public EmbeddedMetadata(EmbeddedField field) { - super(field.getType()); - this.field = field; - // Default storage strategy is EXPLODED - this.storageStrategy = StorageStrategy.EXPLODED; - this.readMethod = IntrospectionUtils.findReadMethodHandle(field.getField()); - this.writeMethod = IntrospectionUtils.findWriteMethodHandle(field.getField()); - } - - /** - * Returns the embedded field to which this metadata belongs. - * - * @return the embedded field to which this metadata belongs. - */ - public EmbeddedField getField() { - return field; - } - - /** - * Returns the read method of the embedded field to which this metadata - * belongs. - * - * @return the read method of the embedded field to which this metadata - * belongs. - */ - public MethodHandle getReadMethod() { - return readMethod; - } - - /** - * Returns the storage strategy. - * - * @return the storage strategy. - */ - public StorageStrategy getStorageStrategy() { - return storageStrategy; - } - - /** - * Sets the storage strategy to the given value. - * - * @param storageStrategy - * the storage strategy - */ - public void setStorageStrategy(StorageStrategy storageStrategy) { - this.storageStrategy = storageStrategy; - } - - /** - * Returns the write method of the embedded field to which this metadata - * belongs. - * - * @return the write method of the embedded field to which this metadata - * belongs. - */ - public MethodHandle getWriteMethod() { - return writeMethod; - } - - /** - * Returns the property name to which this embedded field is mapped. Only - * used when the storage strategy is {@link StorageStrategy#IMPLODED}. - * - * @return the property name to which this embedded field is mapped. - */ - public String getMappedName() { - return mappedName; - } - - /** - * Sets the property name to which this embedded field is mapped. - * - * @param mappedName - * the property name to which this embedded field is mapped. - */ - public void setMappedName(String mappedName) { - this.mappedName = mappedName; - } - - /** - * Returns whether or not this embedded object should be indexed. Only used - * when the storage strategy is {@link StorageStrategy#IMPLODED}. - * - * @return the indexed true, if this embedded object should be - * indexed; false, otherwise. - */ - public boolean isIndexed() { - return indexed; - } - - /** - * Sets whether or not to index this embedded field. - * - * @param indexed - * whether or not to index this embedded field. - */ - public void setIndexed(boolean indexed) { - this.indexed = indexed; - } - - /** - * Tells whether or not the field represented by this metadata is optional. - * - * @return true, if the field represented by this metadata is - * optional; false, otherwise. - */ - public boolean isOptional() { - return optional; - } - - /** - * Sets whether or not the field represented by this metadata is optional. - * - * @param optional - * whether or not the field represented by this metadata is - * optional. - */ - public void setOptional(boolean optional) { - this.optional = optional; - } + /** + * The embedded field to which this metadata belongs. + */ + private final EmbeddedField field; + + /** + * Read method for this embedded field + */ + private final MethodHandle readMethod; + + /** + * Write method for this embedded field + */ + private final MethodHandle writeMethod; + + /** + * Storage strategy to use for the embedded field + */ + private StorageStrategy storageStrategy; + + /** + * The property name under which to store this embedded field + */ + private String mappedName; + + /** + * Whether or not to index this embedded field + */ + private boolean indexed; + + /** + * Whether or not this embedded field is optional + */ + private boolean optional = false; + + /** + * Creates a new instance of EmbeddedMetadata. + * + * @param field + * the embedded field to which this metadata belongs + */ + public EmbeddedMetadata(EmbeddedField field) { + super(field.getType()); + this.field = field; + // Default storage strategy is EXPLODED + this.storageStrategy = StorageStrategy.EXPLODED; + this.readMethod = IntrospectionUtils.findReadMethodHandle(field.getField()); + this.writeMethod = IntrospectionUtils.findWriteMethodHandle(field.getField()); + } + + /** + * Returns the embedded field to which this metadata belongs. + * + * @return the embedded field to which this metadata belongs. + */ + public EmbeddedField getField() { + return field; + } + + /** + * Returns the read method of the embedded field to which this metadata belongs. + * + * @return the read method of the embedded field to which this metadata belongs. + */ + public MethodHandle getReadMethod() { + return readMethod; + } + + /** + * Returns the storage strategy. + * + * @return the storage strategy. + */ + public StorageStrategy getStorageStrategy() { + return storageStrategy; + } + + /** + * Sets the storage strategy to the given value. + * + * @param storageStrategy + * the storage strategy + */ + public void setStorageStrategy(StorageStrategy storageStrategy) { + this.storageStrategy = storageStrategy; + } + + /** + * Returns the write method of the embedded field to which this metadata belongs. + * + * @return the write method of the embedded field to which this metadata belongs. + */ + public MethodHandle getWriteMethod() { + return writeMethod; + } + + /** + * Returns the property name to which this embedded field is mapped. Only used when the storage + * strategy is {@link StorageStrategy#IMPLODED}. + * + * @return the property name to which this embedded field is mapped. + */ + public String getMappedName() { + return mappedName; + } + + /** + * Sets the property name to which this embedded field is mapped. + * + * @param mappedName + * the property name to which this embedded field is mapped. + */ + public void setMappedName(String mappedName) { + this.mappedName = mappedName; + } + + /** + * Returns whether or not this embedded object should be indexed. Only used when the storage + * strategy is {@link StorageStrategy#IMPLODED}. + * + * @return the indexed true, if this embedded object should be indexed; + * false, otherwise. + */ + public boolean isIndexed() { + return indexed; + } + + /** + * Sets whether or not to index this embedded field. + * + * @param indexed + * whether or not to index this embedded field. + */ + public void setIndexed(boolean indexed) { + this.indexed = indexed; + } + + /** + * Tells whether or not the field represented by this metadata is optional. + * + * @return true, if the field represented by this metadata is optional; + * false, otherwise. + */ + public boolean isOptional() { + return optional; + } + + /** + * Sets whether or not the field represented by this metadata is optional. + * + * @param optional + * whether or not the field represented by this metadata is optional. + */ + public void setOptional(boolean optional) { + this.optional = optional; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EntityIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/EntityIntrospector.java index 9623f41..29edec6 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EntityIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EntityIntrospector.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Field; @@ -42,459 +43,443 @@ import com.jmethods.catatumbo.Version; /** - * Introspector for model classes with the annotation of {@link Entity} or - * {@link ProjectedEntity}. The introspect method gathers metadata about the - * given entity class. This metadata is needed for performing the object to - * Datastore mapping and vice versa. The first time an entity class is - * introspected, the metadata is cached and reused for better performance. The - * introspector traverses through the entire entity graph to process simple (or - * primitive) fields as well as an embedded complex objects. + * Introspector for model classes with the annotation of {@link Entity} or {@link ProjectedEntity}. + * The introspect method gathers metadata about the given entity class. This metadata is needed for + * performing the object to Datastore mapping and vice versa. The first time an entity class is + * introspected, the metadata is cached and reused for better performance. The introspector + * traverses through the entire entity graph to process simple (or primitive) fields as well as an + * embedded complex objects. * * @author Sai Pullabhotla */ public class EntityIntrospector { - /** - * Valid data types for fields that are marked with either - * {@link CreatedTimestamp} or {@link UpdatedTimestamp}. - */ - private static final List VALID_TIMESTAMP_TYPES = Arrays - .asList(new String[] { long.class.getName(), Long.class.getName(), Date.class.getName(), - Calendar.class.getName(), OffsetDateTime.class.getName(), ZonedDateTime.class.getName() }); - - static { - // Sort the valid types so we can do a binary search. - Collections.sort(VALID_TIMESTAMP_TYPES); - } - - /** - * Cache of introspected classes - */ - private static final Cache, EntityMetadata> cache = new Cache<>(64); - - /** - * The class to introspect - */ - private final Class entityClass; - - /** - * Output of the introspection, the metadata about the entity - */ - private EntityMetadata entityMetadata; - - /** - * Creates a new instance of EntityIntrospector. - * - * @param entityClass - * the entity class to introspect - */ - private EntityIntrospector(Class entityClass) { - this.entityClass = entityClass; - } - - /** - * Introspects the given entity and returns the metadata associated with the - * entity. - * - * @param entity - * the entity object to introspect. - * @return the metadata of the entity - */ - public static EntityMetadata introspect(Object entity) { - return introspect(entity.getClass()); - } - - /** - * Introspects the given entity class and returns the metadata of the - * entity. - * - * @param entityClass - * the entity class to introspect - * @return the metadata of the entity - */ - public static EntityMetadata introspect(Class entityClass) { - EntityMetadata cachedMetadata = cache.get(entityClass); - if (cachedMetadata != null) { - return cachedMetadata; - } - return loadMetadata(entityClass); - } - - /** - * Loads the metadata for the given class and puts it in the cache and - * returns it. - * - * @param entityClass - * the entity class - * @return the metadata for the given class - */ - private static EntityMetadata loadMetadata(Class entityClass) { - synchronized (entityClass) { - EntityMetadata metadata = cache.get(entityClass); - if (metadata == null) { - EntityIntrospector introspector = new EntityIntrospector(entityClass); - introspector.process(); - metadata = introspector.entityMetadata; - cache.put(entityClass, metadata); - } - return metadata; - } - } - - /** - * Processes the entity class using reflection and builds the metadata. - */ - private void process() { - Entity entity = entityClass.getAnnotation(Entity.class); - ProjectedEntity projectedEntity = entityClass.getAnnotation(ProjectedEntity.class); - if (entity != null) { - initEntityMetadata(entity); - } else if (projectedEntity != null) { - initEntityMetadata(projectedEntity); - } else { - String message = String.format("Class %s must either have %s or %s annotation", entityClass.getName(), - Entity.class.getName(), ProjectedEntity.class.getName()); - throw new EntityManagerException(message); - } - - processPropertyOverrides(); - - processFields(); - // If we did not find valid Identifier... - if (entityMetadata.getIdentifierMetadata() == null) { - throw new EntityManagerException(String.format("Class %s requires a field with annotation of %s", - entityClass.getName(), Identifier.class.getName())); - } - entityMetadata.setEntityListenersMetadata(EntityListenersIntrospector.introspect(entityClass)); - entityMetadata.ensureUniqueProperties(); - entityMetadata.cleanup(); - } - - /** - * Initializes the metadata using the given {@link Entity} annotation. - * - * @param entity - * the {@link Entity} annotation. - */ - private void initEntityMetadata(Entity entity) { - String kind = entity.kind(); - if (kind.trim().length() == 0) { - kind = entityClass.getSimpleName(); - } - entityMetadata = new EntityMetadata(entityClass, kind); - } - - /** - * Initializes the metadata using the given {@link ProjectedEntity} - * annotation. - * - * @param projectedEntity - * the {@link ProjectedEntity} annotation. - */ - private void initEntityMetadata(ProjectedEntity projectedEntity) { - String kind = projectedEntity.kind(); - if (kind.trim().length() == 0) { - String message = String.format("Class %s requires a non-blank Kind", entityClass.getName()); - throw new EntityManagerException(message); - } - entityMetadata = new EntityMetadata(entityClass, kind, true); - } - - /** - * Processes the property overrides for the embedded objects, if any. - */ - private void processPropertyOverrides() { - PropertyOverrides propertyOverrides = entityClass.getAnnotation(PropertyOverrides.class); - if (propertyOverrides == null) { - return; - } - PropertyOverride[] propertyOverridesArray = propertyOverrides.value(); - for (PropertyOverride propertyOverride : propertyOverridesArray) { - entityMetadata.putPropertyOverride(propertyOverride); - } - } - - /** - * Processes the fields defined in this entity and updates the metadata. - */ - private void processFields() { - List fields = getAllFields(); - for (Field field : fields) { - if (field.isAnnotationPresent(Identifier.class)) { - processIdentifierField(field); - } else if (field.isAnnotationPresent(Key.class)) { - processKeyField(field); - } else if (field.isAnnotationPresent(ParentKey.class)) { - processParentKeyField(field); - } else if (field.isAnnotationPresent(Embedded.class)) { - processEmbeddedField(field); - } else { - processField(field); - } - } - } - - /** - * Processes the entity class and any super classes that are - * MappedSupperClasses and returns the fields. - * - * @return all fields of the entity hierarchy. - */ - private List getAllFields() { - List allFields = new ArrayList<>(); - Class clazz = entityClass; - boolean stop; - do { - List fields = IntrospectionUtils.getPersistableFields(clazz); - allFields.addAll(fields); - clazz = clazz.getSuperclass(); - stop = clazz == null || !clazz.isAnnotationPresent(MappedSuperClass.class); - } while (!stop); - return allFields; - } - - /** - * Processes the identifier field and builds the identifier metadata. - * - * @param field - * the identifier field - */ - private void processIdentifierField(Field field) { - Identifier identifier = field.getAnnotation(Identifier.class); - boolean autoGenerated = identifier.autoGenerated(); - IdentifierMetadata identifierMetadata = new IdentifierMetadata(field, autoGenerated); - entityMetadata.setIdentifierMetadata(identifierMetadata); - } - - /** - * Processes the Key field and builds the entity metadata. - * - * @param field - * the Key field - */ - private void processKeyField(Field field) { - String fieldName = field.getName(); - Class type = field.getType(); - if (!type.equals(DatastoreKey.class)) { - String message = String.format("Invalid type, %s, for Key field %s in class %s. ", type, fieldName, - entityClass); - throw new EntityManagerException(message); - } - KeyMetadata keyMetadata = new KeyMetadata(field); - entityMetadata.setKeyMetadata(keyMetadata); - } - - /** - * Processes the ParentKey field and builds the entity metadata. - * - * @param field - * the ParentKey field - */ - private void processParentKeyField(Field field) { - String fieldName = field.getName(); - Class type = field.getType(); - if (!type.equals(DatastoreKey.class)) { - String message = String.format("Invalid type, %s, for ParentKey field %s in class %s. ", type, fieldName, - entityClass); - throw new EntityManagerException(message); - } - ParentKeyMetadata parentKeyMetadata = new ParentKeyMetadata(field); - entityMetadata.setParentKetMetadata(parentKeyMetadata); - } - - /** - * Processes the given field and generates the metadata. - * - * @param field - * the field to process - */ - private void processField(Field field) { - PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(field); - if (propertyMetadata != null) { - // If the field is from a super class, there might be some - // overrides, so process those. - if (!field.getDeclaringClass().equals(entityClass)) { - applyPropertyOverride(propertyMetadata); - } - entityMetadata.putPropertyMetadata(propertyMetadata); - if (field.isAnnotationPresent(Version.class)) { - processVersionField(propertyMetadata); - } else if (field.isAnnotationPresent(CreatedTimestamp.class)) { - processCreatedTimestampField(propertyMetadata); - } else if (field.isAnnotationPresent(UpdatedTimestamp.class)) { - processUpdatedTimestampField(propertyMetadata); - } - } - } - - /** - * Processes the Version annotation of the field with the given metadata. - * - * @param propertyMetadata - * the metadata of the field that has the Version annotation. - */ - private void processVersionField(PropertyMetadata propertyMetadata) { - Class dataClass = propertyMetadata.getDeclaredType(); - if (!long.class.equals(dataClass)) { - String messageFormat = "Field %s in class %s must be of type %s"; - throw new EntityManagerException( - String.format(messageFormat, propertyMetadata.getField().getName(), entityClass, long.class)); - } - entityMetadata.setVersionMetadata(propertyMetadata); - } - - /** - * Processes the field that is marked with {@link CreatedTimestamp} - * annotation. - * - * @param propertyMetadata - * the metadata of the field that was annotated with - * {@link CreatedTimestamp}. - */ - private void processCreatedTimestampField(PropertyMetadata propertyMetadata) { - validateAutoTimestampField(propertyMetadata); - entityMetadata.setCreatedTimestampMetadata(propertyMetadata); - } - - /** - * Processes the field that is marked with {@link UpdatedTimestamp} - * annotation. - * - * @param propertyMetadata - * the metadata of the field that was annotated with - * {@link UpdatedTimestamp}. - */ - private void processUpdatedTimestampField(PropertyMetadata propertyMetadata) { - validateAutoTimestampField(propertyMetadata); - entityMetadata.setUpdatedTimestampMetadata(propertyMetadata); - } - - /** - * Validates the given property metadata to ensure it is valid for an - * automatic timestamp field. - * - * @param propertyMetadata - * the metadata to validate - */ - private void validateAutoTimestampField(PropertyMetadata propertyMetadata) { - Class dataClass = propertyMetadata.getDeclaredType(); - if (Collections.binarySearch(VALID_TIMESTAMP_TYPES, dataClass.getName()) < 0) { - String messageFormat = "Field %s in class %s must be one of the following types - %s"; - throw new EntityManagerException(String.format(messageFormat, propertyMetadata.getField().getName(), - entityClass, VALID_TIMESTAMP_TYPES)); - } - } - - /** - * Applies any override information for the property with the given - * metadata. - * - * @param propertyMetadata - * the metadata of the property - */ - private void applyPropertyOverride(PropertyMetadata propertyMetadata) { - String name = propertyMetadata.getName(); - Property override = entityMetadata.getPropertyOverride(name); - if (override != null) { - String mappedName = override.name(); - if (mappedName != null && mappedName.trim().length() > 0) { - propertyMetadata.setMappedName(mappedName); - } - propertyMetadata.setIndexed(override.indexed()); - propertyMetadata.setOptional(override.optional()); - } - - } - - /** - * Processes and gathers the metadata for the given embedded field. - * - * @param field - * the embedded field - */ - private void processEmbeddedField(Field field) { - // First create EmbeddedField so we can maintain the path/depth of the - // embedded field - EmbeddedField embeddedField = new EmbeddedField(field); - // Introspect the embedded field. - EmbeddedMetadata embeddedMetadata = EmbeddedIntrospector.introspect(embeddedField, entityMetadata); - entityMetadata.putEmbeddedMetadata(embeddedMetadata); - } - - /** - * Convenient method for getting the metadata of the field used for - * optimistic locking. - * - * @param entityClass - * the entity class - * @return the metadata of the field used for optimistic locking. Returns - * null, if the class does not have a field with - * {@link Version} annotation. - */ - public static PropertyMetadata getVersionMetadata(Class entityClass) { - return introspect(entityClass).getVersionMetadata(); - } - - /** - * Convenient method for getting the metadata of the field used for - * optimistic locking. - * - * @param entity - * the entity - * @return the metadata of the field used for optimistic locking. Returns - * null, if the class does not have a field with - * {@link Version} annotation. - */ - public static PropertyMetadata getVersionMetadata(Object entity) { - return introspect(entity.getClass()).getVersionMetadata(); - } - - /** - * Returns the Identifier Metadata for the given entity. - * - * @param entity - * the entity - * @return the Identifier Metadata - */ - public static IdentifierMetadata getIdentifierMetadata(Object entity) { - return getIdentifierMetadata(entity.getClass()); - } - - /** - * Returns the Identifier Metadata for the given entity class. - * - * @param entityClass - * the entity class - * @return the Identifier Metadata - */ - public static IdentifierMetadata getIdentifierMetadata(Class entityClass) { - return introspect(entityClass).getIdentifierMetadata(); - - } - - /** - * Returns the metadata of entity listeners associated with the given - * entity. - * - * @param entity - * the entity - * @return the metadata of EntityListeners associated with the given entity. - */ - public static EntityListenersMetadata getEntityListenersMetadata(Object entity) { - return introspect(entity.getClass()).getEntityListenersMetadata(); - } - - /** - * Returns the metadata of entity listeners associated with the given entity - * class. - * - * @param entityClass - * the entity class - * @return the metadata of entity listeners associated with the given entity - * class. - */ - public static EntityListenersMetadata getEntityListenersMetadata(Class entityClass) { - return introspect(entityClass).getEntityListenersMetadata(); - } + /** + * Valid data types for fields that are marked with either {@link CreatedTimestamp} or + * {@link UpdatedTimestamp}. + */ + private static final List VALID_TIMESTAMP_TYPES = Arrays.asList(new String[] { + long.class.getName(), Long.class.getName(), Date.class.getName(), Calendar.class.getName(), + OffsetDateTime.class.getName(), ZonedDateTime.class.getName() }); + + static { + // Sort the valid types so we can do a binary search. + Collections.sort(VALID_TIMESTAMP_TYPES); + } + + /** + * Cache of introspected classes + */ + private static final Cache, EntityMetadata> cache = new Cache<>(64); + + /** + * The class to introspect + */ + private final Class entityClass; + + /** + * Output of the introspection, the metadata about the entity + */ + private EntityMetadata entityMetadata; + + /** + * Creates a new instance of EntityIntrospector. + * + * @param entityClass + * the entity class to introspect + */ + private EntityIntrospector(Class entityClass) { + this.entityClass = entityClass; + } + + /** + * Introspects the given entity and returns the metadata associated with the entity. + * + * @param entity + * the entity object to introspect. + * @return the metadata of the entity + */ + public static EntityMetadata introspect(Object entity) { + return introspect(entity.getClass()); + } + + /** + * Introspects the given entity class and returns the metadata of the entity. + * + * @param entityClass + * the entity class to introspect + * @return the metadata of the entity + */ + public static EntityMetadata introspect(Class entityClass) { + EntityMetadata cachedMetadata = cache.get(entityClass); + if (cachedMetadata != null) { + return cachedMetadata; + } + return loadMetadata(entityClass); + } + + /** + * Loads the metadata for the given class and puts it in the cache and returns it. + * + * @param entityClass + * the entity class + * @return the metadata for the given class + */ + private static EntityMetadata loadMetadata(Class entityClass) { + synchronized (entityClass) { + EntityMetadata metadata = cache.get(entityClass); + if (metadata == null) { + EntityIntrospector introspector = new EntityIntrospector(entityClass); + introspector.process(); + metadata = introspector.entityMetadata; + cache.put(entityClass, metadata); + } + return metadata; + } + } + + /** + * Processes the entity class using reflection and builds the metadata. + */ + private void process() { + Entity entity = entityClass.getAnnotation(Entity.class); + ProjectedEntity projectedEntity = entityClass.getAnnotation(ProjectedEntity.class); + if (entity != null) { + initEntityMetadata(entity); + } else if (projectedEntity != null) { + initEntityMetadata(projectedEntity); + } else { + String message = String.format("Class %s must either have %s or %s annotation", + entityClass.getName(), Entity.class.getName(), ProjectedEntity.class.getName()); + throw new EntityManagerException(message); + } + + processPropertyOverrides(); + + processFields(); + // If we did not find valid Identifier... + if (entityMetadata.getIdentifierMetadata() == null) { + throw new EntityManagerException( + String.format("Class %s requires a field with annotation of %s", entityClass.getName(), + Identifier.class.getName())); + } + entityMetadata.setEntityListenersMetadata(EntityListenersIntrospector.introspect(entityClass)); + entityMetadata.ensureUniqueProperties(); + entityMetadata.cleanup(); + } + + /** + * Initializes the metadata using the given {@link Entity} annotation. + * + * @param entity + * the {@link Entity} annotation. + */ + private void initEntityMetadata(Entity entity) { + String kind = entity.kind(); + if (kind.trim().length() == 0) { + kind = entityClass.getSimpleName(); + } + entityMetadata = new EntityMetadata(entityClass, kind); + } + + /** + * Initializes the metadata using the given {@link ProjectedEntity} annotation. + * + * @param projectedEntity + * the {@link ProjectedEntity} annotation. + */ + private void initEntityMetadata(ProjectedEntity projectedEntity) { + String kind = projectedEntity.kind(); + if (kind.trim().length() == 0) { + String message = String.format("Class %s requires a non-blank Kind", entityClass.getName()); + throw new EntityManagerException(message); + } + entityMetadata = new EntityMetadata(entityClass, kind, true); + } + + /** + * Processes the property overrides for the embedded objects, if any. + */ + private void processPropertyOverrides() { + PropertyOverrides propertyOverrides = entityClass.getAnnotation(PropertyOverrides.class); + if (propertyOverrides == null) { + return; + } + PropertyOverride[] propertyOverridesArray = propertyOverrides.value(); + for (PropertyOverride propertyOverride : propertyOverridesArray) { + entityMetadata.putPropertyOverride(propertyOverride); + } + } + + /** + * Processes the fields defined in this entity and updates the metadata. + */ + private void processFields() { + List fields = getAllFields(); + for (Field field : fields) { + if (field.isAnnotationPresent(Identifier.class)) { + processIdentifierField(field); + } else if (field.isAnnotationPresent(Key.class)) { + processKeyField(field); + } else if (field.isAnnotationPresent(ParentKey.class)) { + processParentKeyField(field); + } else if (field.isAnnotationPresent(Embedded.class)) { + processEmbeddedField(field); + } else { + processField(field); + } + } + } + + /** + * Processes the entity class and any super classes that are MappedSupperClasses and returns the + * fields. + * + * @return all fields of the entity hierarchy. + */ + private List getAllFields() { + List allFields = new ArrayList<>(); + Class clazz = entityClass; + boolean stop; + do { + List fields = IntrospectionUtils.getPersistableFields(clazz); + allFields.addAll(fields); + clazz = clazz.getSuperclass(); + stop = clazz == null || !clazz.isAnnotationPresent(MappedSuperClass.class); + } while (!stop); + return allFields; + } + + /** + * Processes the identifier field and builds the identifier metadata. + * + * @param field + * the identifier field + */ + private void processIdentifierField(Field field) { + Identifier identifier = field.getAnnotation(Identifier.class); + boolean autoGenerated = identifier.autoGenerated(); + IdentifierMetadata identifierMetadata = new IdentifierMetadata(field, autoGenerated); + entityMetadata.setIdentifierMetadata(identifierMetadata); + } + + /** + * Processes the Key field and builds the entity metadata. + * + * @param field + * the Key field + */ + private void processKeyField(Field field) { + String fieldName = field.getName(); + Class type = field.getType(); + if (!type.equals(DatastoreKey.class)) { + String message = String.format("Invalid type, %s, for Key field %s in class %s. ", type, + fieldName, entityClass); + throw new EntityManagerException(message); + } + KeyMetadata keyMetadata = new KeyMetadata(field); + entityMetadata.setKeyMetadata(keyMetadata); + } + + /** + * Processes the ParentKey field and builds the entity metadata. + * + * @param field + * the ParentKey field + */ + private void processParentKeyField(Field field) { + String fieldName = field.getName(); + Class type = field.getType(); + if (!type.equals(DatastoreKey.class)) { + String message = String.format("Invalid type, %s, for ParentKey field %s in class %s. ", type, + fieldName, entityClass); + throw new EntityManagerException(message); + } + ParentKeyMetadata parentKeyMetadata = new ParentKeyMetadata(field); + entityMetadata.setParentKetMetadata(parentKeyMetadata); + } + + /** + * Processes the given field and generates the metadata. + * + * @param field + * the field to process + */ + private void processField(Field field) { + PropertyMetadata propertyMetadata = IntrospectionUtils.getPropertyMetadata(field); + if (propertyMetadata != null) { + // If the field is from a super class, there might be some + // overrides, so process those. + if (!field.getDeclaringClass().equals(entityClass)) { + applyPropertyOverride(propertyMetadata); + } + entityMetadata.putPropertyMetadata(propertyMetadata); + if (field.isAnnotationPresent(Version.class)) { + processVersionField(propertyMetadata); + } else if (field.isAnnotationPresent(CreatedTimestamp.class)) { + processCreatedTimestampField(propertyMetadata); + } else if (field.isAnnotationPresent(UpdatedTimestamp.class)) { + processUpdatedTimestampField(propertyMetadata); + } + } + } + + /** + * Processes the Version annotation of the field with the given metadata. + * + * @param propertyMetadata + * the metadata of the field that has the Version annotation. + */ + private void processVersionField(PropertyMetadata propertyMetadata) { + Class dataClass = propertyMetadata.getDeclaredType(); + if (!long.class.equals(dataClass)) { + String messageFormat = "Field %s in class %s must be of type %s"; + throw new EntityManagerException(String.format(messageFormat, + propertyMetadata.getField().getName(), entityClass, long.class)); + } + entityMetadata.setVersionMetadata(propertyMetadata); + } + + /** + * Processes the field that is marked with {@link CreatedTimestamp} annotation. + * + * @param propertyMetadata + * the metadata of the field that was annotated with {@link CreatedTimestamp}. + */ + private void processCreatedTimestampField(PropertyMetadata propertyMetadata) { + validateAutoTimestampField(propertyMetadata); + entityMetadata.setCreatedTimestampMetadata(propertyMetadata); + } + + /** + * Processes the field that is marked with {@link UpdatedTimestamp} annotation. + * + * @param propertyMetadata + * the metadata of the field that was annotated with {@link UpdatedTimestamp}. + */ + private void processUpdatedTimestampField(PropertyMetadata propertyMetadata) { + validateAutoTimestampField(propertyMetadata); + entityMetadata.setUpdatedTimestampMetadata(propertyMetadata); + } + + /** + * Validates the given property metadata to ensure it is valid for an automatic timestamp field. + * + * @param propertyMetadata + * the metadata to validate + */ + private void validateAutoTimestampField(PropertyMetadata propertyMetadata) { + Class dataClass = propertyMetadata.getDeclaredType(); + if (Collections.binarySearch(VALID_TIMESTAMP_TYPES, dataClass.getName()) < 0) { + String messageFormat = "Field %s in class %s must be one of the following types - %s"; + throw new EntityManagerException(String.format(messageFormat, + propertyMetadata.getField().getName(), entityClass, VALID_TIMESTAMP_TYPES)); + } + } + + /** + * Applies any override information for the property with the given metadata. + * + * @param propertyMetadata + * the metadata of the property + */ + private void applyPropertyOverride(PropertyMetadata propertyMetadata) { + String name = propertyMetadata.getName(); + Property override = entityMetadata.getPropertyOverride(name); + if (override != null) { + String mappedName = override.name(); + if (mappedName != null && mappedName.trim().length() > 0) { + propertyMetadata.setMappedName(mappedName); + } + propertyMetadata.setIndexed(override.indexed()); + propertyMetadata.setOptional(override.optional()); + } + + } + + /** + * Processes and gathers the metadata for the given embedded field. + * + * @param field + * the embedded field + */ + private void processEmbeddedField(Field field) { + // First create EmbeddedField so we can maintain the path/depth of the + // embedded field + EmbeddedField embeddedField = new EmbeddedField(field); + // Introspect the embedded field. + EmbeddedMetadata embeddedMetadata = EmbeddedIntrospector.introspect(embeddedField, + entityMetadata); + entityMetadata.putEmbeddedMetadata(embeddedMetadata); + } + + /** + * Convenient method for getting the metadata of the field used for optimistic locking. + * + * @param entityClass + * the entity class + * @return the metadata of the field used for optimistic locking. Returns null, if + * the class does not have a field with {@link Version} annotation. + */ + public static PropertyMetadata getVersionMetadata(Class entityClass) { + return introspect(entityClass).getVersionMetadata(); + } + + /** + * Convenient method for getting the metadata of the field used for optimistic locking. + * + * @param entity + * the entity + * @return the metadata of the field used for optimistic locking. Returns null, if + * the class does not have a field with {@link Version} annotation. + */ + public static PropertyMetadata getVersionMetadata(Object entity) { + return introspect(entity.getClass()).getVersionMetadata(); + } + + /** + * Returns the Identifier Metadata for the given entity. + * + * @param entity + * the entity + * @return the Identifier Metadata + */ + public static IdentifierMetadata getIdentifierMetadata(Object entity) { + return getIdentifierMetadata(entity.getClass()); + } + + /** + * Returns the Identifier Metadata for the given entity class. + * + * @param entityClass + * the entity class + * @return the Identifier Metadata + */ + public static IdentifierMetadata getIdentifierMetadata(Class entityClass) { + return introspect(entityClass).getIdentifierMetadata(); + + } + + /** + * Returns the metadata of entity listeners associated with the given entity. + * + * @param entity + * the entity + * @return the metadata of EntityListeners associated with the given entity. + */ + public static EntityListenersMetadata getEntityListenersMetadata(Object entity) { + return introspect(entity.getClass()).getEntityListenersMetadata(); + } + + /** + * Returns the metadata of entity listeners associated with the given entity class. + * + * @param entityClass + * the entity class + * @return the metadata of entity listeners associated with the given entity class. + */ + public static EntityListenersMetadata getEntityListenersMetadata(Class entityClass) { + return introspect(entityClass).getEntityListenersMetadata(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EntityListenerType.java b/src/main/java/com/jmethods/catatumbo/impl/EntityListenerType.java index 3f6620b..e951852 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EntityListenerType.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EntityListenerType.java @@ -27,25 +27,22 @@ */ public enum EntityListenerType { - /** - * Default (aka Global) Listener. These type of listeners are registered - * with the {@link EntityManager} using - * {@link EntityManager#setDefaultListeners(Class...)} and these listeners - * will be executed for all types of Entities managed by the - * {@link EntityManager}. - */ - DEFAULT, + /** + * Default (aka Global) Listener. These type of listeners are registered with the + * {@link EntityManager} using {@link EntityManager#setDefaultListeners(Class...)} and these + * listeners will be executed for all types of Entities managed by the {@link EntityManager}. + */ + DEFAULT, - /** - * External Listener. These type of listeners are specified on the Entity - * class or MappedSuperClass using the {@link EntityListeners} annotations. - */ - EXTERNAL, + /** + * External Listener. These type of listeners are specified on the Entity class or + * MappedSuperClass using the {@link EntityListeners} annotations. + */ + EXTERNAL, - /** - * Internal Listeners. These type of listeners are defined within the Entity - * or MappedSuperClass. - */ - INTERNAL; + /** + * Internal Listeners. These type of listeners are defined within the Entity or MappedSuperClass. + */ + INTERNAL; } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EntityListenersIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/EntityListenersIntrospector.java index d218d6a..bc5ac81 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EntityListenersIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EntityListenersIntrospector.java @@ -29,196 +29,200 @@ import com.jmethods.catatumbo.MappedSuperClass; /** - * Introspects the given entity class to find all listeners that would receive - * lifecycle callbacks. + * Introspects the given entity class to find all listeners that would receive lifecycle callbacks. * * @author Sai Pullabhotla * */ public class EntityListenersIntrospector { - /** - * Entity class - */ - private Class entityClass; - - /** - * Metadata of various listeners - */ - private EntityListenersMetadata metadata; - - /** - * Creates a new instance of EntityListenersMetadata. - * - * @param entityClass - * the entity class to introspect - */ - private EntityListenersIntrospector(Class entityClass) { - this.entityClass = entityClass; - } - - /** - * Returns the metadata of various registered listeners for the given - * entity. - * - * @param entity - * the entity to introspect - * @return the metadata of various listeners. - */ - public static EntityListenersMetadata introspect(Object entity) { - return introspect(entity.getClass()); - } - - /** - * Returns the metadata of various registered listeners for the given entity - * class. - * - * @param entityClass - * the entity class to introspect - * @return the metadata of various listeners. - */ - public static EntityListenersMetadata introspect(Class entityClass) { - EntityListenersIntrospector introspector = new EntityListenersIntrospector(entityClass); - introspector.introspect(); - return introspector.metadata; - } - - /** - * Introspects the entity class and builds the listeners metadata. - */ - private void introspect() { - metadata = new EntityListenersMetadata(entityClass); - processExternalListeners(); - processInternalListeners(); - } - - /** - * Gathers information about all external listeners (listeners specified - * with {@link EntityListeners} annotation) and updates the metadata. - */ - private void processExternalListeners() { - List> externalListeners = getAllExternalListeners(); - for (Class externalListener : externalListeners) { - processExternalListener(externalListener); - } - } - - /** - * Inspects the entity hierarchy and returns all external listeners. - * - * @return list of all external listeners - */ - private List> getAllExternalListeners() { - Class clazz = entityClass; - List> allListeners = new ArrayList<>(); - boolean stop = false; - while (!stop) { - EntityListeners entityListenersAnnotation = clazz.getAnnotation(EntityListeners.class); - if (entityListenersAnnotation != null) { - Class[] listeners = entityListenersAnnotation.value(); - if (listeners.length > 0) { - allListeners.addAll(0, Arrays.asList(listeners)); - } - } - boolean excludeDefaultListeners = clazz.isAnnotationPresent(ExcludeDefaultListeners.class); - boolean excludeSuperClassListeners = clazz.isAnnotationPresent(ExcludeSuperclassListeners.class); - if (excludeDefaultListeners) { - metadata.setExcludeDefaultListeners(true); - } - if (excludeSuperClassListeners) { - metadata.setExcludeSuperClassListeners(true); - } - clazz = clazz.getSuperclass(); - stop = excludeSuperClassListeners || clazz == null || !clazz.isAnnotationPresent(MappedSuperClass.class); - } - return allListeners; - } - - /** - * Introspects the given listener class and finds all methods that should - * receive callback event notifications. - * - * @param listenerClass - * the listener class - */ - private void processExternalListener(Class listenerClass) { - ExternalListenerMetadata listenerMetadata = ExternalListenerIntrospector.introspect(listenerClass); - Map callbacks = listenerMetadata.getCallbacks(); - if (callbacks != null) { - for (Map.Entry entry : callbacks.entrySet()) { - validateExternalCallback(entry.getValue(), entry.getKey()); - } - } - } - - /** - * Validates and registers the given callback method. - * - * @param method - * the callback method - * @param callbackType - * the callback type - */ - private void validateExternalCallback(Method method, CallbackType callbackType) { - Class[] parameters = method.getParameterTypes(); - if (!parameters[0].isAssignableFrom(entityClass)) { - String message = String.format("Method %s in class %s is not valid for entity %s", method.getName(), - method.getDeclaringClass().getName(), entityClass.getName()); - throw new EntityManagerException(message); - } - CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.EXTERNAL, callbackType, method); - metadata.put(callbackType, callbackMetadata); - } - - /** - * Introspects the entity class hierarchy for any internal callback methods - * and updates the metadata. - */ - private void processInternalListeners() { - List> internalListeners = getAllInternalListeners(); - for (Class internalListener : internalListeners) { - processInternalListener(internalListener); - } - } - - /** - * Traverses up the entity class hierarchy and returns the list of all - * classes that may potentially have callback listeners. - * - * @return all internal callback listeners - */ - private List> getAllInternalListeners() { - Class clazz = entityClass; - List> allListeners = new ArrayList<>(); - boolean stop = false; - while (!stop) { - allListeners.add(0, clazz); - boolean excludeSuperClassListeners = clazz.isAnnotationPresent(ExcludeSuperclassListeners.class); - clazz = clazz.getSuperclass(); - stop = excludeSuperClassListeners || clazz == null || !clazz.isAnnotationPresent(MappedSuperClass.class); - } - return allListeners; - - } - - /** - * Processes the given class and finds any internal callbacks. - * - * @param listenerClass - * the class to introspect - */ - private void processInternalListener(Class listenerClass) { - InternalListenerMetadata listenerMetadata = InternalListenerIntrospector.introspect(listenerClass); - Map callbacks = listenerMetadata.getCallbacks(); - if (callbacks != null) { - for (Map.Entry entry : callbacks.entrySet()) { - CallbackType callbackType = entry.getKey(); - Method callbackMethod = entry.getValue(); - CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.INTERNAL, callbackType, - callbackMethod); - metadata.put(callbackType, callbackMetadata); - } - } - } + /** + * Entity class + */ + private Class entityClass; + + /** + * Metadata of various listeners + */ + private EntityListenersMetadata metadata; + + /** + * Creates a new instance of EntityListenersMetadata. + * + * @param entityClass + * the entity class to introspect + */ + private EntityListenersIntrospector(Class entityClass) { + this.entityClass = entityClass; + } + + /** + * Returns the metadata of various registered listeners for the given entity. + * + * @param entity + * the entity to introspect + * @return the metadata of various listeners. + */ + public static EntityListenersMetadata introspect(Object entity) { + return introspect(entity.getClass()); + } + + /** + * Returns the metadata of various registered listeners for the given entity class. + * + * @param entityClass + * the entity class to introspect + * @return the metadata of various listeners. + */ + public static EntityListenersMetadata introspect(Class entityClass) { + EntityListenersIntrospector introspector = new EntityListenersIntrospector(entityClass); + introspector.introspect(); + return introspector.metadata; + } + + /** + * Introspects the entity class and builds the listeners metadata. + */ + private void introspect() { + metadata = new EntityListenersMetadata(entityClass); + processExternalListeners(); + processInternalListeners(); + } + + /** + * Gathers information about all external listeners (listeners specified with + * {@link EntityListeners} annotation) and updates the metadata. + */ + private void processExternalListeners() { + List> externalListeners = getAllExternalListeners(); + for (Class externalListener : externalListeners) { + processExternalListener(externalListener); + } + } + + /** + * Inspects the entity hierarchy and returns all external listeners. + * + * @return list of all external listeners + */ + private List> getAllExternalListeners() { + Class clazz = entityClass; + List> allListeners = new ArrayList<>(); + boolean stop = false; + while (!stop) { + EntityListeners entityListenersAnnotation = clazz.getAnnotation(EntityListeners.class); + if (entityListenersAnnotation != null) { + Class[] listeners = entityListenersAnnotation.value(); + if (listeners.length > 0) { + allListeners.addAll(0, Arrays.asList(listeners)); + } + } + boolean excludeDefaultListeners = clazz.isAnnotationPresent(ExcludeDefaultListeners.class); + boolean excludeSuperClassListeners = clazz + .isAnnotationPresent(ExcludeSuperclassListeners.class); + if (excludeDefaultListeners) { + metadata.setExcludeDefaultListeners(true); + } + if (excludeSuperClassListeners) { + metadata.setExcludeSuperClassListeners(true); + } + clazz = clazz.getSuperclass(); + stop = excludeSuperClassListeners || clazz == null + || !clazz.isAnnotationPresent(MappedSuperClass.class); + } + return allListeners; + } + + /** + * Introspects the given listener class and finds all methods that should receive callback event + * notifications. + * + * @param listenerClass + * the listener class + */ + private void processExternalListener(Class listenerClass) { + ExternalListenerMetadata listenerMetadata = ExternalListenerIntrospector + .introspect(listenerClass); + Map callbacks = listenerMetadata.getCallbacks(); + if (callbacks != null) { + for (Map.Entry entry : callbacks.entrySet()) { + validateExternalCallback(entry.getValue(), entry.getKey()); + } + } + } + + /** + * Validates and registers the given callback method. + * + * @param method + * the callback method + * @param callbackType + * the callback type + */ + private void validateExternalCallback(Method method, CallbackType callbackType) { + Class[] parameters = method.getParameterTypes(); + if (!parameters[0].isAssignableFrom(entityClass)) { + String message = String.format("Method %s in class %s is not valid for entity %s", + method.getName(), method.getDeclaringClass().getName(), entityClass.getName()); + throw new EntityManagerException(message); + } + CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.EXTERNAL, + callbackType, method); + metadata.put(callbackType, callbackMetadata); + } + + /** + * Introspects the entity class hierarchy for any internal callback methods and updates the + * metadata. + */ + private void processInternalListeners() { + List> internalListeners = getAllInternalListeners(); + for (Class internalListener : internalListeners) { + processInternalListener(internalListener); + } + } + + /** + * Traverses up the entity class hierarchy and returns the list of all classes that may + * potentially have callback listeners. + * + * @return all internal callback listeners + */ + private List> getAllInternalListeners() { + Class clazz = entityClass; + List> allListeners = new ArrayList<>(); + boolean stop = false; + while (!stop) { + allListeners.add(0, clazz); + boolean excludeSuperClassListeners = clazz + .isAnnotationPresent(ExcludeSuperclassListeners.class); + clazz = clazz.getSuperclass(); + stop = excludeSuperClassListeners || clazz == null + || !clazz.isAnnotationPresent(MappedSuperClass.class); + } + return allListeners; + + } + + /** + * Processes the given class and finds any internal callbacks. + * + * @param listenerClass + * the class to introspect + */ + private void processInternalListener(Class listenerClass) { + InternalListenerMetadata listenerMetadata = InternalListenerIntrospector + .introspect(listenerClass); + Map callbacks = listenerMetadata.getCallbacks(); + if (callbacks != null) { + for (Map.Entry entry : callbacks.entrySet()) { + CallbackType callbackType = entry.getKey(); + Method callbackMethod = entry.getValue(); + CallbackMetadata callbackMetadata = new CallbackMetadata(EntityListenerType.INTERNAL, + callbackType, callbackMethod); + metadata.put(callbackType, callbackMetadata); + } + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java index 621892e..004bcea 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java @@ -29,129 +29,126 @@ */ public class EntityListenersMetadata { - /** - * The entity class to which this metadata belongs to. - */ - private final Class entityClass; - - /** - * A map containing all {@link CallbackMetadata} by the callback type, - * Lazily loaded. - */ - private Map> callbacks; - - /** - * Whether or not to exclude global listeners. - */ - private boolean excludeDefaultListeners; - - /** - * Whether or not to exclude super class listeners (this is really not - * needed as we exclude them from the callbacks map). - */ - private boolean excludeSuperClassListeners; - - /** - * Creates a new instance of EntityListenersMetadata. - * - * @param entityClass - * the entity class - */ - public EntityListenersMetadata(Class entityClass) { - this.entityClass = entityClass; - excludeDefaultListeners = false; - excludeSuperClassListeners = false; - } - - /** - * Returns the entity class to which this metadata belongs. - * - * @return the entityClass the entity class to which this metadata belongs. - */ - public Class getEntityClass() { - return entityClass; - } - - /** - * Tells whether or not the default (aka global) listeners should be - * excluded. - * - * @return true, if global listeners should be excluded; - * false, otherwise. - */ - public boolean isExcludeDefaultListeners() { - return excludeDefaultListeners; - } - - /** - * Sets whether or not to exclude the default (aka global) listeners. - * - * @param excludeGlobalListeners - * whether or not to exclude the global listeners - */ - public void setExcludeDefaultListeners(boolean excludeGlobalListeners) { - this.excludeDefaultListeners = excludeGlobalListeners; - } - - /** - * Tells whether or not to exclude the listeners defined in the super - * classes of the entity. - * - * @return true, if super class listeners should be excluded; - * false, otherwise. - */ - public boolean isExcludeSuperClassListeners() { - return excludeSuperClassListeners; - } - - /** - * Sets whether or not to exclude the super class listeners. - * - * @param excludeSuperClassListeners - * whether or not to exclude the super class listeners - */ - public void setExcludeSuperClassListeners(boolean excludeSuperClassListeners) { - this.excludeSuperClassListeners = excludeSuperClassListeners; - } - - /** - * Adds the given CallbackEventMetadata. - * - * @param callbackType - * the callback type - * @param callbackMetadata - * the metadata of the callback - */ - public void put(CallbackType callbackType, CallbackMetadata callbackMetadata) { - if (callbacks == null) { - callbacks = new EnumMap<>(CallbackType.class); - } - List callbackMetadataList = callbacks.get(callbackType); - if (callbackMetadataList == null) { - callbackMetadataList = new ArrayList<>(); - callbacks.put(callbackType, callbackMetadataList); - } - callbackMetadataList.add(callbackMetadata); - } - - /** - * Returns the callbacks for the given callback type. - * - * @param callbackType - * the callback type - * @return the list of callbacks for the given callback type - */ - public List getCallbacks(CallbackType callbackType) { - return callbacks == null ? null : callbacks.get(callbackType); - } - - /** - * Returns all callbacks. - * - * @return All call backs. - */ - public Map> getCallbacks() { - return callbacks; - } + /** + * The entity class to which this metadata belongs to. + */ + private final Class entityClass; + + /** + * A map containing all {@link CallbackMetadata} by the callback type, Lazily loaded. + */ + private Map> callbacks; + + /** + * Whether or not to exclude global listeners. + */ + private boolean excludeDefaultListeners; + + /** + * Whether or not to exclude super class listeners (this is really not needed as we exclude them + * from the callbacks map). + */ + private boolean excludeSuperClassListeners; + + /** + * Creates a new instance of EntityListenersMetadata. + * + * @param entityClass + * the entity class + */ + public EntityListenersMetadata(Class entityClass) { + this.entityClass = entityClass; + excludeDefaultListeners = false; + excludeSuperClassListeners = false; + } + + /** + * Returns the entity class to which this metadata belongs. + * + * @return the entityClass the entity class to which this metadata belongs. + */ + public Class getEntityClass() { + return entityClass; + } + + /** + * Tells whether or not the default (aka global) listeners should be excluded. + * + * @return true, if global listeners should be excluded; false, + * otherwise. + */ + public boolean isExcludeDefaultListeners() { + return excludeDefaultListeners; + } + + /** + * Sets whether or not to exclude the default (aka global) listeners. + * + * @param excludeGlobalListeners + * whether or not to exclude the global listeners + */ + public void setExcludeDefaultListeners(boolean excludeGlobalListeners) { + this.excludeDefaultListeners = excludeGlobalListeners; + } + + /** + * Tells whether or not to exclude the listeners defined in the super classes of the entity. + * + * @return true, if super class listeners should be excluded; false, + * otherwise. + */ + public boolean isExcludeSuperClassListeners() { + return excludeSuperClassListeners; + } + + /** + * Sets whether or not to exclude the super class listeners. + * + * @param excludeSuperClassListeners + * whether or not to exclude the super class listeners + */ + public void setExcludeSuperClassListeners(boolean excludeSuperClassListeners) { + this.excludeSuperClassListeners = excludeSuperClassListeners; + } + + /** + * Adds the given CallbackEventMetadata. + * + * @param callbackType + * the callback type + * @param callbackMetadata + * the metadata of the callback + */ + public void put(CallbackType callbackType, CallbackMetadata callbackMetadata) { + if (callbacks == null) { + callbacks = new EnumMap<>(CallbackType.class); + } + List callbackMetadataList = callbacks.get(callbackType); + if (callbackMetadataList == null) { + callbackMetadataList = new ArrayList<>(); + callbacks.put(callbackType, callbackMetadataList); + } + callbackMetadataList.add(callbackMetadata); + } + + /** + * Returns the callbacks for the given callback type. + * + * @param callbackType + * the callback type + * @return the list of callbacks for the given callback type + */ + public List getCallbacks(CallbackType callbackType) { + return callbacks == null ? null : callbacks.get(callbackType); + } + + /** + * Returns all callbacks. + * + * @return All call backs. + */ + public Map> getCallbacks() { + return callbacks; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/EntityMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/EntityMetadata.java index 53a7774..cf634ad 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/EntityMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/EntityMetadata.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.annotation.Annotation; @@ -31,430 +32,424 @@ import com.jmethods.catatumbo.Version; /** - * Objects of this class hold metadata information about an entity. Metadata - * includes all the information that is needed to map Java objects to the Cloud - * Datastore and vice versa. + * Objects of this class hold metadata information about an entity. Metadata includes all the + * information that is needed to map Java objects to the Cloud Datastore and vice versa. * * * @author Sai Pullabhotla */ public class EntityMetadata extends MetadataBase { - /** - * Entity class to which this metadata belongs - */ - private Class entityClass; - - /** - * Whether or not this metadata belongs to a ProjectedEntity - */ - private boolean projectedEntity; - - /** - * Entity kind - */ - private String kind; - - /** - * Metadata about the entity's identifier - */ - private IdentifierMetadata identifierMetadata; - - /** - * Metadata of the full key, including any ancestor keys. - */ - private KeyMetadata keyMetadata; - - /** - * Metadata of the parent key. - */ - private ParentKeyMetadata parentKeyMetadata; - - /** - * Metadata of the field that is used for optimistic locking/entity - * versioning - */ - private PropertyMetadata versionMetadata; - - /** - * Metadata of the field that is used to store the creation timestamp of an - * entity. - */ - private PropertyMetadata createdTimestampMetadata; - - /** - * Metadata of the field that is used to store the modification timestamp of - * an entity. - */ - private PropertyMetadata updatedTimestampMetadata; - - /** - * Property overrides for embedded fields of the entity. The key is the - * override name that uniquely identifies a primitive property in the entity - * tree. - */ - private Map propertyOverrideMap; - - /** - * Master list of properties, used for detecting duplicate property names. - * Key is the mapped name (or property name in the datastore) and value is - * the qualified name of the field to report in the exception. - */ - private Map masterPropertyMetadataMap; - - /** - * Metadata of various entity listeners - */ - private EntityListenersMetadata entityListenersMetadata; - - /** - * Creates a new instance of EntityMetadata. - * - * @param entityClass - * the entity class - * @param kind - * the entity kind - */ - public EntityMetadata(Class entityClass, String kind) { - this(entityClass, kind, false); - } - - /** - * Creates a new instance of EntityMetadata. - * - * @param entityClass - * the entity class - * @param kind - * the entity kind - * @param projectedEntity - * whether or not the entity is a projected entity - */ - public EntityMetadata(Class entityClass, String kind, boolean projectedEntity) { - super(entityClass); - this.entityClass = entityClass; - this.kind = kind; - this.projectedEntity = projectedEntity; - propertyOverrideMap = new HashMap<>(); - masterPropertyMetadataMap = new HashMap<>(); - } - - /** - * Returns the entity class to which this metadata belongs. - * - * @return the entity class to which this metadata belongs. - */ - public Class getEntityClass() { - return entityClass; - } - - /** - * Tells whether or not this metadata belongs to a {@link ProjectedEntity}. - * - * @return true, if this metadata belongs to a - * {@link ProjectedEntity}; false, otherwise. - */ - public boolean isProjectedEntity() { - return projectedEntity; - } - - /** - * Returns the entity kind. - * - * @return the entity kind. - */ - public String getKind() { - return kind; - } - - /** - * Returns the metadata of the identifier. - * - * @return the metadata of the identifier. - */ - public IdentifierMetadata getIdentifierMetadata() { - return identifierMetadata; - } - - /** - * Sets the metadata of the identifier. An exception will be thrown if there - * is an IdentifierMetadata already set. - * - * @param identifierMetadata - * the metadata of the identifier. - */ - public void setIdentifierMetadata(IdentifierMetadata identifierMetadata) { - if (this.identifierMetadata != null) { - String format = "Class %s has at least two fields, %s and %s, marked with %s annotation. Only one field can be marked as an identifier. "; - String message = String.format(format, entityClass.getName(), this.identifierMetadata.getName(), - identifierMetadata.getName(), Identifier.class.getName()); - throw new EntityManagerException(message); - } - this.identifierMetadata = identifierMetadata; - } - - /** - * Returns the metadata of the entity's full key. - * - * @return the metadata of the entity's full key. May return - * null, if the entity does not have a field annotated - * with @Key. - */ - public KeyMetadata getKeyMetadata() { - return keyMetadata; - } - - /** - * Sets the metadata of the Key field. - * - * @param keyMetadata - * the key metadata. - */ - public void setKeyMetadata(KeyMetadata keyMetadata) { - if (this.keyMetadata != null) { - String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one field can be marked as Key. "; - String message = String.format(format, entityClass.getName(), this.keyMetadata.getName(), - keyMetadata.getName(), Key.class.getName()); - throw new EntityManagerException(message); - - } - this.keyMetadata = keyMetadata; - } - - /** - * Returns the metadata of the Parent Key. - * - * @return the metadata of the Parent Key.May return null. - */ - public ParentKeyMetadata getParentKeyMetadata() { - return parentKeyMetadata; - } - - /** - * Sets the metadata about the parent key. - * - * @param parentKeyMetadata - * the parent key metadata. - */ - public void setParentKetMetadata(ParentKeyMetadata parentKeyMetadata) { - if (this.parentKeyMetadata != null) { - String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one field can be marked as ParentKey. "; - String message = String.format(format, entityClass.getName(), this.parentKeyMetadata.getName(), - parentKeyMetadata.getName(), ParentKey.class.getName()); - throw new EntityManagerException(message); - - } - this.parentKeyMetadata = parentKeyMetadata; - } - - /** - * Returns the metadata of the field that is used for optimistic locking. - * - * @return the versionMetadata the metadata of the field that is used for - * optimistic locking. - */ - public PropertyMetadata getVersionMetadata() { - return versionMetadata; - } - - /** - * Sets the metadata of the field that is used for optimistic locking. - * - * @param versionMetadata - * metadata of the field that is used for optimistic locking. - */ - public void setVersionMetadata(PropertyMetadata versionMetadata) { - if (this.versionMetadata != null) { - throwDuplicateAnnotationException(entityClass, Version.class, this.versionMetadata, versionMetadata); - } - this.versionMetadata = versionMetadata; - } - - /** - * Returns the metadata of the field that was marked with - * {@link CreatedTimestamp} annotation. - * - * @return the metadata of the field that was marked with - * {@link CreatedTimestamp} annotation. The returned value may be - * null, if the entity does not have a field with - * {@link CreatedTimestamp} annotation. - */ - public PropertyMetadata getCreatedTimestampMetadata() { - return createdTimestampMetadata; - } - - /** - * Sets the created timestamp metadata to the given value. - * - * @param createdTimestampMetadata - * the created timestamp metadata - */ - public void setCreatedTimestampMetadata(PropertyMetadata createdTimestampMetadata) { - if (this.createdTimestampMetadata != null) { - throwDuplicateAnnotationException(entityClass, CreatedTimestamp.class, this.createdTimestampMetadata, - createdTimestampMetadata); - } - this.createdTimestampMetadata = createdTimestampMetadata; - } - - /** - * Returns the metadata of the field that was marked with - * {@link UpdatedTimestamp} annotation. - * - * @return the metadata of the field that was marked with - * {@link UpdatedTimestamp} annotation. The returned value may be - * null, if the entity does not have a field with - * {@link UpdatedTimestamp} annotation. - */ - public PropertyMetadata getUpdatedTimestampMetadata() { - return updatedTimestampMetadata; - } - - /** - * @param updatedTimestampMetadata - * the updatedTimestampMetadata to set - */ - public void setUpdatedTimestampMetadata(PropertyMetadata updatedTimestampMetadata) { - if (this.updatedTimestampMetadata != null) { - throwDuplicateAnnotationException(entityClass, UpdatedTimestamp.class, this.updatedTimestampMetadata, - updatedTimestampMetadata); - } - this.updatedTimestampMetadata = updatedTimestampMetadata; - } - - /** - * Puts/adds the given property override. - * - * @param propertyOverride - * the property override - */ - public void putPropertyOverride(PropertyOverride propertyOverride) { - propertyOverrideMap.put(propertyOverride.name(), propertyOverride.property()); - } - - /** - * Returns the property override, if any for the given name. May return - * null if there is no override exists for the given name. - * - * @param name - * the name of the property - * @return the property override for the given property name. May return - * null. - */ - public Property getPropertyOverride(String name) { - return propertyOverrideMap.get(name); - } - - /** - * Updates the master property metadata map with the given property - * metadata. - * - * @param mappedName - * the mapped name (or property name in the datastore) - * @param qualifiedName - * the qualified name of the field - * - * @throws EntityManagerException - * if a property with the same mapped name already exists. - */ - public void updateMasterPropertyMetadataMap(String mappedName, String qualifiedName) { - String old = masterPropertyMetadataMap.put(mappedName, qualifiedName); - if (old != null) { - String message = "Duplicate property %s in entity %s. Check fields %s and %s"; - throw new EntityManagerException( - String.format(message, mappedName, entityClass.getName(), old, qualifiedName)); - } - - } - - /** - * Returns the metadata of the entity listeners. - * - * @return the metadata of the entity listeners. - */ - public EntityListenersMetadata getEntityListenersMetadata() { - return entityListenersMetadata; - } - - /** - * Sets the metadata of the entity listeners. - * - * @param entityListenersMetadata - * the metadata of the entity listeners. - */ - public void setEntityListenersMetadata(EntityListenersMetadata entityListenersMetadata) { - this.entityListenersMetadata = entityListenersMetadata; - } - - /** - * Cleans up this metadata by clearing unnecessary data. - */ - public void cleanup() { - propertyOverrideMap.clear(); - masterPropertyMetadataMap.clear(); - } - - /** - * Validates this metadata to ensure there are no duplicate property names - * defined in this entity/embedded objects. - */ - public void ensureUniqueProperties() { - masterPropertyMetadataMap.clear(); - for (PropertyMetadata propertyMetadata : getPropertyMetadataCollection()) { - updateMasterPropertyMetadataMap(propertyMetadata.getMappedName(), propertyMetadata.getName()); - } - // top level embedded objects - for (EmbeddedMetadata embeddedMetadata : getEmbeddedMetadataCollection()) { - ensureUniqueProperties(embeddedMetadata, embeddedMetadata.getStorageStrategy()); - } - } - - /** - * Validates the embedded field represented by the given metadata to ensure - * there are no duplicate property names defined across the entity. - * - * @param embeddedMetadata - * the metadata of the embedded field - * @param storageStrategy - * the storage strategy of the embedded field - */ - private void ensureUniqueProperties(EmbeddedMetadata embeddedMetadata, StorageStrategy storageStrategy) { - if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { - for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { - updateMasterPropertyMetadataMap(propertyMetadata.getMappedName(), - embeddedMetadata.getField().getQualifiedName() + "." + propertyMetadata.getName()); - } - // Run through the nested embedded objects recursively - for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { - ensureUniqueProperties(embeddedMetadata2, storageStrategy); - } - } else { - // IMPLODED storage strategy... we don't have to check the - // individual properties or nested embeddables - updateMasterPropertyMetadataMap(embeddedMetadata.getMappedName(), - embeddedMetadata.getField().getQualifiedName()); - } - } - - /** - * Raises an exception with a detailed message reporting that the entity has - * more than one field that has a specific annotation. - * - * @param entityClass - * the entity class - * @param annotationClass - * the annotation class - * @param metadata1 - * the metadata of the first field - * @param metadata2 - * the metadata of the second field that conflicts with the first - */ - private static void throwDuplicateAnnotationException(Class entityClass, - Class annotationClass, PropertyMetadata metadata1, PropertyMetadata metadata2) { - String format = "Class %s has at least two fields, %s and %s, with an annotation of %s. A given entity " - + "can have at most one field with this annotation. "; - String message = String.format(format, entityClass.getName(), metadata1.getName(), metadata2.getName(), - annotationClass.getName()); - throw new EntityManagerException(message); - } + /** + * Entity class to which this metadata belongs + */ + private Class entityClass; + + /** + * Whether or not this metadata belongs to a ProjectedEntity + */ + private boolean projectedEntity; + + /** + * Entity kind + */ + private String kind; + + /** + * Metadata about the entity's identifier + */ + private IdentifierMetadata identifierMetadata; + + /** + * Metadata of the full key, including any ancestor keys. + */ + private KeyMetadata keyMetadata; + + /** + * Metadata of the parent key. + */ + private ParentKeyMetadata parentKeyMetadata; + + /** + * Metadata of the field that is used for optimistic locking/entity versioning + */ + private PropertyMetadata versionMetadata; + + /** + * Metadata of the field that is used to store the creation timestamp of an entity. + */ + private PropertyMetadata createdTimestampMetadata; + + /** + * Metadata of the field that is used to store the modification timestamp of an entity. + */ + private PropertyMetadata updatedTimestampMetadata; + + /** + * Property overrides for embedded fields of the entity. The key is the override name that + * uniquely identifies a primitive property in the entity tree. + */ + private Map propertyOverrideMap; + + /** + * Master list of properties, used for detecting duplicate property names. Key is the mapped name + * (or property name in the datastore) and value is the qualified name of the field to report in + * the exception. + */ + private Map masterPropertyMetadataMap; + + /** + * Metadata of various entity listeners + */ + private EntityListenersMetadata entityListenersMetadata; + + /** + * Creates a new instance of EntityMetadata. + * + * @param entityClass + * the entity class + * @param kind + * the entity kind + */ + public EntityMetadata(Class entityClass, String kind) { + this(entityClass, kind, false); + } + + /** + * Creates a new instance of EntityMetadata. + * + * @param entityClass + * the entity class + * @param kind + * the entity kind + * @param projectedEntity + * whether or not the entity is a projected entity + */ + public EntityMetadata(Class entityClass, String kind, boolean projectedEntity) { + super(entityClass); + this.entityClass = entityClass; + this.kind = kind; + this.projectedEntity = projectedEntity; + propertyOverrideMap = new HashMap<>(); + masterPropertyMetadataMap = new HashMap<>(); + } + + /** + * Returns the entity class to which this metadata belongs. + * + * @return the entity class to which this metadata belongs. + */ + public Class getEntityClass() { + return entityClass; + } + + /** + * Tells whether or not this metadata belongs to a {@link ProjectedEntity}. + * + * @return true, if this metadata belongs to a {@link ProjectedEntity}; + * false, otherwise. + */ + public boolean isProjectedEntity() { + return projectedEntity; + } + + /** + * Returns the entity kind. + * + * @return the entity kind. + */ + public String getKind() { + return kind; + } + + /** + * Returns the metadata of the identifier. + * + * @return the metadata of the identifier. + */ + public IdentifierMetadata getIdentifierMetadata() { + return identifierMetadata; + } + + /** + * Sets the metadata of the identifier. An exception will be thrown if there is an + * IdentifierMetadata already set. + * + * @param identifierMetadata + * the metadata of the identifier. + */ + public void setIdentifierMetadata(IdentifierMetadata identifierMetadata) { + if (this.identifierMetadata != null) { + String format = "Class %s has at least two fields, %s and %s, marked with %s annotation. " + + "Only one field can be marked as an identifier. "; + String message = String.format(format, entityClass.getName(), + this.identifierMetadata.getName(), identifierMetadata.getName(), + Identifier.class.getName()); + throw new EntityManagerException(message); + } + this.identifierMetadata = identifierMetadata; + } + + /** + * Returns the metadata of the entity's full key. + * + * @return the metadata of the entity's full key. May return null, if the entity does + * not have a field annotated with @Key. + */ + public KeyMetadata getKeyMetadata() { + return keyMetadata; + } + + /** + * Sets the metadata of the Key field. + * + * @param keyMetadata + * the key metadata. + */ + public void setKeyMetadata(KeyMetadata keyMetadata) { + if (this.keyMetadata != null) { + String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one " + + "field can be marked as Key. "; + String message = String.format(format, entityClass.getName(), this.keyMetadata.getName(), + keyMetadata.getName(), Key.class.getName()); + throw new EntityManagerException(message); + + } + this.keyMetadata = keyMetadata; + } + + /** + * Returns the metadata of the Parent Key. + * + * @return the metadata of the Parent Key.May return null. + */ + public ParentKeyMetadata getParentKeyMetadata() { + return parentKeyMetadata; + } + + /** + * Sets the metadata about the parent key. + * + * @param parentKeyMetadata + * the parent key metadata. + */ + public void setParentKetMetadata(ParentKeyMetadata parentKeyMetadata) { + if (this.parentKeyMetadata != null) { + String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one " + + "field can be marked as ParentKey. "; + String message = String.format(format, entityClass.getName(), + this.parentKeyMetadata.getName(), parentKeyMetadata.getName(), ParentKey.class.getName()); + throw new EntityManagerException(message); + + } + this.parentKeyMetadata = parentKeyMetadata; + } + + /** + * Returns the metadata of the field that is used for optimistic locking. + * + * @return the versionMetadata the metadata of the field that is used for optimistic locking. + */ + public PropertyMetadata getVersionMetadata() { + return versionMetadata; + } + + /** + * Sets the metadata of the field that is used for optimistic locking. + * + * @param versionMetadata + * metadata of the field that is used for optimistic locking. + */ + public void setVersionMetadata(PropertyMetadata versionMetadata) { + if (this.versionMetadata != null) { + throwDuplicateAnnotationException(entityClass, Version.class, this.versionMetadata, + versionMetadata); + } + this.versionMetadata = versionMetadata; + } + + /** + * Returns the metadata of the field that was marked with {@link CreatedTimestamp} annotation. + * + * @return the metadata of the field that was marked with {@link CreatedTimestamp} annotation. The + * returned value may be null, if the entity does not have a field with + * {@link CreatedTimestamp} annotation. + */ + public PropertyMetadata getCreatedTimestampMetadata() { + return createdTimestampMetadata; + } + + /** + * Sets the created timestamp metadata to the given value. + * + * @param createdTimestampMetadata + * the created timestamp metadata + */ + public void setCreatedTimestampMetadata(PropertyMetadata createdTimestampMetadata) { + if (this.createdTimestampMetadata != null) { + throwDuplicateAnnotationException(entityClass, CreatedTimestamp.class, + this.createdTimestampMetadata, createdTimestampMetadata); + } + this.createdTimestampMetadata = createdTimestampMetadata; + } + + /** + * Returns the metadata of the field that was marked with {@link UpdatedTimestamp} annotation. + * + * @return the metadata of the field that was marked with {@link UpdatedTimestamp} annotation. The + * returned value may be null, if the entity does not have a field with + * {@link UpdatedTimestamp} annotation. + */ + public PropertyMetadata getUpdatedTimestampMetadata() { + return updatedTimestampMetadata; + } + + /** + * @param updatedTimestampMetadata + * the updatedTimestampMetadata to set + */ + public void setUpdatedTimestampMetadata(PropertyMetadata updatedTimestampMetadata) { + if (this.updatedTimestampMetadata != null) { + throwDuplicateAnnotationException(entityClass, UpdatedTimestamp.class, + this.updatedTimestampMetadata, updatedTimestampMetadata); + } + this.updatedTimestampMetadata = updatedTimestampMetadata; + } + + /** + * Puts/adds the given property override. + * + * @param propertyOverride + * the property override + */ + public void putPropertyOverride(PropertyOverride propertyOverride) { + propertyOverrideMap.put(propertyOverride.name(), propertyOverride.property()); + } + + /** + * Returns the property override, if any for the given name. May return null if there + * is no override exists for the given name. + * + * @param name + * the name of the property + * @return the property override for the given property name. May return null. + */ + public Property getPropertyOverride(String name) { + return propertyOverrideMap.get(name); + } + + /** + * Updates the master property metadata map with the given property metadata. + * + * @param mappedName + * the mapped name (or property name in the datastore) + * @param qualifiedName + * the qualified name of the field + * + * @throws EntityManagerException + * if a property with the same mapped name already exists. + */ + public void updateMasterPropertyMetadataMap(String mappedName, String qualifiedName) { + String old = masterPropertyMetadataMap.put(mappedName, qualifiedName); + if (old != null) { + String message = "Duplicate property %s in entity %s. Check fields %s and %s"; + throw new EntityManagerException( + String.format(message, mappedName, entityClass.getName(), old, qualifiedName)); + } + + } + + /** + * Returns the metadata of the entity listeners. + * + * @return the metadata of the entity listeners. + */ + public EntityListenersMetadata getEntityListenersMetadata() { + return entityListenersMetadata; + } + + /** + * Sets the metadata of the entity listeners. + * + * @param entityListenersMetadata + * the metadata of the entity listeners. + */ + public void setEntityListenersMetadata(EntityListenersMetadata entityListenersMetadata) { + this.entityListenersMetadata = entityListenersMetadata; + } + + /** + * Cleans up this metadata by clearing unnecessary data. + */ + public void cleanup() { + propertyOverrideMap.clear(); + masterPropertyMetadataMap.clear(); + } + + /** + * Validates this metadata to ensure there are no duplicate property names defined in this + * entity/embedded objects. + */ + public void ensureUniqueProperties() { + masterPropertyMetadataMap.clear(); + for (PropertyMetadata propertyMetadata : getPropertyMetadataCollection()) { + updateMasterPropertyMetadataMap(propertyMetadata.getMappedName(), propertyMetadata.getName()); + } + // top level embedded objects + for (EmbeddedMetadata embeddedMetadata : getEmbeddedMetadataCollection()) { + ensureUniqueProperties(embeddedMetadata, embeddedMetadata.getStorageStrategy()); + } + } + + /** + * Validates the embedded field represented by the given metadata to ensure there are no duplicate + * property names defined across the entity. + * + * @param embeddedMetadata + * the metadata of the embedded field + * @param storageStrategy + * the storage strategy of the embedded field + */ + private void ensureUniqueProperties(EmbeddedMetadata embeddedMetadata, + StorageStrategy storageStrategy) { + if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { + for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { + updateMasterPropertyMetadataMap(propertyMetadata.getMappedName(), + embeddedMetadata.getField().getQualifiedName() + "." + propertyMetadata.getName()); + } + // Run through the nested embedded objects recursively + for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { + ensureUniqueProperties(embeddedMetadata2, storageStrategy); + } + } else { + // IMPLODED storage strategy... we don't have to check the + // individual properties or nested embeddables + updateMasterPropertyMetadataMap(embeddedMetadata.getMappedName(), + embeddedMetadata.getField().getQualifiedName()); + } + } + + /** + * Raises an exception with a detailed message reporting that the entity has more than one field + * that has a specific annotation. + * + * @param entityClass + * the entity class + * @param annotationClass + * the annotation class + * @param metadata1 + * the metadata of the first field + * @param metadata2 + * the metadata of the second field that conflicts with the first + */ + private static void throwDuplicateAnnotationException(Class entityClass, + Class annotationClass, PropertyMetadata metadata1, + PropertyMetadata metadata2) { + String format = "Class %s has at least two fields, %s and %s, with an annotation of %s. " + + "A given entity can have at most one field with this annotation. "; + String message = String.format(format, entityClass.getName(), metadata1.getName(), + metadata2.getName(), annotationClass.getName()); + throw new EntityManagerException(message); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospector.java index 4a18fee..d86dda2 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospector.java @@ -30,117 +30,118 @@ */ public class ExternalListenerIntrospector { - /** - * EntityListener class - */ - private Class listenerClass; + /** + * EntityListener class + */ + private Class listenerClass; - /** - * Metadata of the listener class - */ - private ExternalListenerMetadata metadata; + /** + * Metadata of the listener class + */ + private ExternalListenerMetadata metadata; - /** - * A cache of previously processed listener classes - */ - private static Cache, ExternalListenerMetadata> cache = new Cache<>(); + /** + * A cache of previously processed listener classes + */ + private static Cache, ExternalListenerMetadata> cache = new Cache<>(); - /** - * Creates a new instance of EntityListenerIntrospector. - * - * @param listenerClass - * the listener class to introspect - */ - private ExternalListenerIntrospector(Class listenerClass) { - this.listenerClass = listenerClass; - } + /** + * Creates a new instance of EntityListenerIntrospector. + * + * @param listenerClass + * the listener class to introspect + */ + private ExternalListenerIntrospector(Class listenerClass) { + this.listenerClass = listenerClass; + } - /** - * Introspects the given entity listener class and returns its metadata. - * - * @param listenerClass - * the entity listener class - * @return the entity listener metadata - */ - public static ExternalListenerMetadata introspect(Class listenerClass) { - ExternalListenerMetadata cachedMetadata = cache.get(listenerClass); - if (cachedMetadata != null) { - return cachedMetadata; - } - synchronized (listenerClass) { - cachedMetadata = cache.get(listenerClass); - if (cachedMetadata != null) { - return cachedMetadata; - } - ExternalListenerIntrospector introspector = new ExternalListenerIntrospector(listenerClass); - introspector.introspect(); - cache.put(listenerClass, introspector.metadata); - return introspector.metadata; - } - } + /** + * Introspects the given entity listener class and returns its metadata. + * + * @param listenerClass + * the entity listener class + * @return the entity listener metadata + */ + public static ExternalListenerMetadata introspect(Class listenerClass) { + ExternalListenerMetadata cachedMetadata = cache.get(listenerClass); + if (cachedMetadata != null) { + return cachedMetadata; + } + synchronized (listenerClass) { + cachedMetadata = cache.get(listenerClass); + if (cachedMetadata != null) { + return cachedMetadata; + } + ExternalListenerIntrospector introspector = new ExternalListenerIntrospector(listenerClass); + introspector.introspect(); + cache.put(listenerClass, introspector.metadata); + return introspector.metadata; + } + } - /** - * Introspects the listener class and creates the metadata. - */ - private void introspect() { - if (!listenerClass.isAnnotationPresent(EntityListener.class)) { - String message = String.format("Class %s must have %s annotation to be used as an EntityListener", - listenerClass.getName(), EntityListener.class.getName()); - throw new EntityManagerException(message); - } - metadata = new ExternalListenerMetadata(listenerClass); - processMethods(); - } + /** + * Introspects the listener class and creates the metadata. + */ + private void introspect() { + if (!listenerClass.isAnnotationPresent(EntityListener.class)) { + String message = String.format( + "Class %s must have %s annotation to be used as an EntityListener", + listenerClass.getName(), EntityListener.class.getName()); + throw new EntityManagerException(message); + } + metadata = new ExternalListenerMetadata(listenerClass); + processMethods(); + } - /** - * Processes the methods in the listener class and updates the metadata for - * any valid methods found. - */ - private void processMethods() { - Method[] methods = listenerClass.getMethods(); - for (Method method : methods) { - for (CallbackType callbackType : CallbackType.values()) { - if (method.isAnnotationPresent(callbackType.getAnnotationClass())) { - validateMethod(method, callbackType); - metadata.putListener(callbackType, method); - } - } - } - } + /** + * Processes the methods in the listener class and updates the metadata for any valid methods + * found. + */ + private void processMethods() { + Method[] methods = listenerClass.getMethods(); + for (Method method : methods) { + for (CallbackType callbackType : CallbackType.values()) { + if (method.isAnnotationPresent(callbackType.getAnnotationClass())) { + validateMethod(method, callbackType); + metadata.putListener(callbackType, method); + } + } + } + } - /** - * Validates the given method to ensure if it is a valid callback method for - * the given event type. - * - * @param method - * the method to validate - * @param callbackType - * the callback type - */ - private void validateMethod(Method method, CallbackType callbackType) { - int modifiers = method.getModifiers(); - if (Modifier.isStatic(modifiers)) { - String message = String.format("Method %s in class %s must not be static", method.getName(), - method.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - if (Modifier.isAbstract(modifiers)) { - String message = String.format("Method %s in class %s must not be abstract", method.getName(), - method.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - Class[] parameters = method.getParameterTypes(); - if (parameters.length != 1) { - String message = String.format( - "Method %s in class %s is not a valid %s callback method. Method must have one parameter. ", - method.getName(), method.getDeclaringClass().getName(), callbackType); - throw new EntityManagerException(message); - } - if (method.getReturnType() != void.class) { - String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), - method.getDeclaringClass().getName(), void.class.getName()); - throw new EntityManagerException(message); - } - } + /** + * Validates the given method to ensure if it is a valid callback method for the given event type. + * + * @param method + * the method to validate + * @param callbackType + * the callback type + */ + private void validateMethod(Method method, CallbackType callbackType) { + int modifiers = method.getModifiers(); + if (Modifier.isStatic(modifiers)) { + String message = String.format("Method %s in class %s must not be static", method.getName(), + method.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + if (Modifier.isAbstract(modifiers)) { + String message = String.format("Method %s in class %s must not be abstract", method.getName(), + method.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + Class[] parameters = method.getParameterTypes(); + if (parameters.length != 1) { + String pattern = "Method %s in class %s is not a valid %s callback method. Method must have " + + "one parameter. "; + String message = String.format(pattern, method.getName(), + method.getDeclaringClass().getName(), callbackType); + throw new EntityManagerException(message); + } + if (method.getReturnType() != void.class) { + String message = String.format("Method %s in class %s must have a return type of %s", + method.getName(), method.getDeclaringClass().getName(), void.class.getName()); + throw new EntityManagerException(message); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerMetadata.java index 5fd6aa2..79bd5b2 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ExternalListenerMetadata.java @@ -24,14 +24,14 @@ */ public class ExternalListenerMetadata extends AbstractListenerMetadata { - /** - * Creates a new instance of ExternalListenerMetadata. - * - * @param listenerClass - * the listener class to which this metadata belongs. - */ - public ExternalListenerMetadata(Class listenerClass) { - super(listenerClass); - } + /** + * Creates a new instance of ExternalListenerMetadata. + * + * @param listenerClass + * the listener class to which this metadata belongs. + */ + public ExternalListenerMetadata(Class listenerClass) { + super(listenerClass); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/FieldMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/FieldMetadata.java index af9e646..a0099bf 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/FieldMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/FieldMetadata.java @@ -13,91 +13,92 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.invoke.MethodHandle; import java.lang.reflect.Field; /** - * Base class for holding the metadata about an entity's or embedded object's - * field (e.g. identifier, key or property). + * Base class for holding the metadata about an entity's or embedded object's field (e.g. + * identifier, key or property). * * @author Sai Pullabhotla */ public abstract class FieldMetadata { - /** - * Reference to the field - */ - protected final Field field; + /** + * Reference to the field + */ + protected final Field field; - /** - * Read method (or getter method) for this field - */ - protected final MethodHandle readMethod; + /** + * Read method (or getter method) for this field + */ + protected final MethodHandle readMethod; - /** - * Write method (or setter method) for this field - */ - protected final MethodHandle writeMethod; + /** + * Write method (or setter method) for this field + */ + protected final MethodHandle writeMethod; - /** - * Creates a new instance of FieldMetadata. - * - * @param field - * the field - * - */ - public FieldMetadata(Field field) { - this.field = field; - this.readMethod = IntrospectionUtils.findReadMethodHandle(this.field); - this.writeMethod = IntrospectionUtils.findWriteMethodHandle(this.field); - } + /** + * Creates a new instance of FieldMetadata. + * + * @param field + * the field + * + */ + public FieldMetadata(Field field) { + this.field = field; + this.readMethod = IntrospectionUtils.findReadMethodHandle(this.field); + this.writeMethod = IntrospectionUtils.findWriteMethodHandle(this.field); + } - /** - * Returns the field. - * - * @return the field. - */ - public Field getField() { - return field; - } + /** + * Returns the field. + * + * @return the field. + */ + public Field getField() { + return field; + } - /** - * Returns the field name. - * - * @return the field name. - */ - public String getName() { - return field.getName(); - } + /** + * Returns the field name. + * + * @return the field name. + */ + public String getName() { + return field.getName(); + } - /** - * Returns the read method (or getter method) for this field. - * - * @return the read method (or getter method) for this field. - */ - public MethodHandle getReadMethod() { - return readMethod; - } + /** + * Returns the read method (or getter method) for this field. + * + * @return the read method (or getter method) for this field. + */ + public MethodHandle getReadMethod() { + return readMethod; + } - /** - * Returns the write method (or setter method). - * - * @return the write method (or setter method). - */ - public MethodHandle getWriteMethod() { - return writeMethod; - } + /** + * Returns the write method (or setter method). + * + * @return the write method (or setter method). + */ + public MethodHandle getWriteMethod() { + return writeMethod; + } - /** - * Returns the declared type of the field to which this metadata belongs. - * - * @return the declared type of the field to which this metadata belongs. - */ - @SuppressWarnings("rawtypes") - public Class getDeclaredType() { - return field.getType(); - } + /** + * Returns the declared type of the field to which this metadata belongs. + * + * @return the declared type of the field to which this metadata belongs. + */ + @SuppressWarnings("rawtypes") + public Class getDeclaredType() { + return field.getType(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java index b3b8482..ed87d1f 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java @@ -32,111 +32,112 @@ */ public class IdClassMetadata { - /** - * Name of the method for reading the underlying ID - */ - private static final String READ_METHOD_NAME = "getValue"; - - /** - * ID Class - */ - private final Class clazz; - - /** - * Method Handle for reading the real ID - */ - private final MethodHandle readMethod; - - /** - * Method Handle for the constructor to instantiate and setting the real ID. - */ - private final MethodHandle constructor; - - /** - * Creates a new instance of the IdClassMetadata. - * - * @param clazz - * the ID class to which this metadata belongs to. - */ - public IdClassMetadata(Class clazz) { - this.clazz = clazz; - this.readMethod = findIdReadMethod(); - this.constructor = findConstructor(); - } - - /** - * Returns the MethodHandle for reading the underlying ID. - * - * @return the MethodHandle for reading the underlying ID. - */ - public MethodHandle getReadMethod() { - return readMethod; - } - - /** - * Returns the constructor for instantiating the setting the underlying ID. - * - * @return the constructor for instantiating the setting the underlying ID. - */ - public MethodHandle getConstructor() { - return constructor; - } - - /** - * Returns the Class to which this metadata belongs. - * - * @return the Class to which this metadata belongs. - */ - public Class getClazz() { - return clazz; - } - - /** - * Returns the underlying type of the ID. - * - * @return the underlying type of the ID. - */ - public Class getIdType() { - return readMethod.type().returnType(); - } - - /** - * Creates and returns the MethodHandle for reading the underlying ID. - * - * @return the MethodHandle for reading the underlying ID. - */ - private MethodHandle findIdReadMethod() { - try { - Method readMethod = clazz.getMethod(READ_METHOD_NAME); - Class dataClass = readMethod.getReturnType(); - DataType dataType = IdentifierMetadata.DataType.forClass(dataClass); - if (dataType == null) { - String pattern = "Method %s in class %s must have a return type of long, Long or String"; - String error = String.format(pattern, READ_METHOD_NAME, clazz.getName()); - throw new EntityManagerException(error); - } - return MethodHandles.lookup().unreflect(readMethod); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException exp) { - String error = String.format("Class %s must have a public %s method", clazz.getName(), READ_METHOD_NAME); - throw new EntityManagerException(error, exp); - } - } - - /** - * Creates and returns the MethodHandle for the constructor. - * - * @return the MethodHandle for the constructor. - */ - private MethodHandle findConstructor() { - try { - MethodHandle mh = MethodHandles.publicLookup().findConstructor(clazz, - MethodType.methodType(void.class, getIdType())); - return mh; - } catch (NoSuchMethodException | IllegalAccessException exp) { - String pattern = "Class %s requires a public constructor with one parameter of type %s"; - String error = String.format(pattern, clazz.getName(), getIdType()); - throw new EntityManagerException(error, exp); - } - } + /** + * Name of the method for reading the underlying ID + */ + private static final String READ_METHOD_NAME = "getValue"; + + /** + * ID Class + */ + private final Class clazz; + + /** + * Method Handle for reading the real ID + */ + private final MethodHandle readMethod; + + /** + * Method Handle for the constructor to instantiate and setting the real ID. + */ + private final MethodHandle constructor; + + /** + * Creates a new instance of the IdClassMetadata. + * + * @param clazz + * the ID class to which this metadata belongs to. + */ + public IdClassMetadata(Class clazz) { + this.clazz = clazz; + this.readMethod = findIdReadMethod(); + this.constructor = findConstructor(); + } + + /** + * Returns the MethodHandle for reading the underlying ID. + * + * @return the MethodHandle for reading the underlying ID. + */ + public MethodHandle getReadMethod() { + return readMethod; + } + + /** + * Returns the constructor for instantiating the setting the underlying ID. + * + * @return the constructor for instantiating the setting the underlying ID. + */ + public MethodHandle getConstructor() { + return constructor; + } + + /** + * Returns the Class to which this metadata belongs. + * + * @return the Class to which this metadata belongs. + */ + public Class getClazz() { + return clazz; + } + + /** + * Returns the underlying type of the ID. + * + * @return the underlying type of the ID. + */ + public Class getIdType() { + return readMethod.type().returnType(); + } + + /** + * Creates and returns the MethodHandle for reading the underlying ID. + * + * @return the MethodHandle for reading the underlying ID. + */ + private MethodHandle findIdReadMethod() { + try { + Method readMethod = clazz.getMethod(READ_METHOD_NAME); + Class dataClass = readMethod.getReturnType(); + DataType dataType = IdentifierMetadata.DataType.forClass(dataClass); + if (dataType == null) { + String pattern = "Method %s in class %s must have a return type of long, Long or String"; + String error = String.format(pattern, READ_METHOD_NAME, clazz.getName()); + throw new EntityManagerException(error); + } + return MethodHandles.lookup().unreflect(readMethod); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException exp) { + String error = String.format("Class %s must have a public %s method", clazz.getName(), + READ_METHOD_NAME); + throw new EntityManagerException(error, exp); + } + } + + /** + * Creates and returns the MethodHandle for the constructor. + * + * @return the MethodHandle for the constructor. + */ + private MethodHandle findConstructor() { + try { + MethodHandle mh = MethodHandles.publicLookup().findConstructor(clazz, + MethodType.methodType(void.class, getIdType())); + return mh; + } catch (NoSuchMethodException | IllegalAccessException exp) { + String pattern = "Class %s requires a public constructor with one parameter of type %s"; + String error = String.format(pattern, clazz.getName(), getIdType()); + throw new EntityManagerException(error, exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/IdentifierMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/IdentifierMetadata.java index 9c164e6..06076f9 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/IdentifierMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/IdentifierMetadata.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Field; @@ -26,138 +27,135 @@ */ public class IdentifierMetadata extends FieldMetadata { - /** - * Valid identifier types. - * - * @author Sai Pullabhotla - * - */ - public enum DataType { - /** - * Primitive long - */ - LONG(long.class), - /** - * Wrapper Long - */ - LONG_OBJECT(Long.class), - /** - * String - */ - STRING(String.class); - - /** - * Data class - */ - private final Class dataClass; - - /** - * Creates a new instance of DataType. - * - * @param dataClass - * the type/class for the data type - */ - private DataType(Class dataClass) { - this.dataClass = dataClass; - } - - /** - * Returns the DataType for the given class. - * - * @param dataClass - * the class - * @return the DataType for the given class. - */ - public static DataType forClass(Class dataClass) { - for (DataType dataType : DataType.values()) { - if (dataType.dataClass.equals(dataClass)) { - return dataType; - } - } - return null; - } - } - - /** - * If identifier is to be auto generated or not - */ - private boolean autoGenerated; - - /** - * Data type of the identifier - */ - private final DataType dataType; - - /** - * Metadata of the ID Class - */ - private final IdClassMetadata idClassMetadata; - - /** - * Creates a new instance of IdentifierMetadata. - * - * @param field - * the field - * @param autoGenerated - * if the identifier is to be generated automatically - */ - public IdentifierMetadata(Field field, boolean autoGenerated) { - super(field); - this.autoGenerated = autoGenerated; - DataType dataType = DataType.forClass(field.getType()); - if (dataType == null) { - idClassMetadata = new IdClassMetadata(getDeclaredType()); - dataType = DataType.forClass(idClassMetadata.getIdType()); - } else { - idClassMetadata = null; - } - if (dataType == null) { - String message = String.format("Invalid identifier type %s for field %s in class %s", - field.getType().getName(), field.getName(), field.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - this.dataType = dataType; - } - - /** - * Tells whether or not the identifier is to be generated automatically. - * - * @return true, if the identifier is to be generated automatically; false, - * otherwise. - */ - public boolean isAutoGenerated() { - return autoGenerated; - } - - /** - * Sets whether or not the identifier is to be generated automatically. - * - * @param autoGenerated - * whether or not the identifier is to be generated - * automatically. - */ - public void setAutoGenerated(boolean autoGenerated) { - this.autoGenerated = autoGenerated; - } - - /** - * Returns the type of the ID. - * - * @return the type of the ID. - */ - public DataType getDataType() { - return dataType; - } - - /** - * Returns the metadata of the ID class, if any. - * - * @return the idClassMetadata the metadata of the ID class, if any. Returns - * null, if the Entity has a simple ID (long, Long or - * String). - */ - public IdClassMetadata getIdClassMetadata() { - return idClassMetadata; - } + /** + * Valid identifier types. + * + * @author Sai Pullabhotla + * + */ + public enum DataType { + /** + * Primitive long + */ + LONG(long.class), + /** + * Wrapper Long + */ + LONG_OBJECT(Long.class), + /** + * String + */ + STRING(String.class); + + /** + * Data class + */ + private final Class dataClass; + + /** + * Creates a new instance of DataType. + * + * @param dataClass + * the type/class for the data type + */ + private DataType(Class dataClass) { + this.dataClass = dataClass; + } + + /** + * Returns the DataType for the given class. + * + * @param dataClass + * the class + * @return the DataType for the given class. + */ + public static DataType forClass(Class dataClass) { + for (DataType dataType : DataType.values()) { + if (dataType.dataClass.equals(dataClass)) { + return dataType; + } + } + return null; + } + } + + /** + * If identifier is to be auto generated or not + */ + private boolean autoGenerated; + + /** + * Data type of the identifier + */ + private final DataType dataType; + + /** + * Metadata of the ID Class + */ + private final IdClassMetadata idClassMetadata; + + /** + * Creates a new instance of IdentifierMetadata. + * + * @param field + * the field + * @param autoGenerated + * if the identifier is to be generated automatically + */ + public IdentifierMetadata(Field field, boolean autoGenerated) { + super(field); + this.autoGenerated = autoGenerated; + DataType dataType = DataType.forClass(field.getType()); + if (dataType == null) { + idClassMetadata = new IdClassMetadata(getDeclaredType()); + dataType = DataType.forClass(idClassMetadata.getIdType()); + } else { + idClassMetadata = null; + } + if (dataType == null) { + String message = String.format("Invalid identifier type %s for field %s in class %s", + field.getType().getName(), field.getName(), field.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + this.dataType = dataType; + } + + /** + * Tells whether or not the identifier is to be generated automatically. + * + * @return true, if the identifier is to be generated automatically; false, otherwise. + */ + public boolean isAutoGenerated() { + return autoGenerated; + } + + /** + * Sets whether or not the identifier is to be generated automatically. + * + * @param autoGenerated + * whether or not the identifier is to be generated automatically. + */ + public void setAutoGenerated(boolean autoGenerated) { + this.autoGenerated = autoGenerated; + } + + /** + * Returns the type of the ID. + * + * @return the type of the ID. + */ + public DataType getDataType() { + return dataType; + } + + /** + * Returns the metadata of the ID class, if any. + * + * @return the idClassMetadata the metadata of the ID class, if any. Returns null, if + * the Entity has a simple ID (long, Long or String). + */ + public IdClassMetadata getIdClassMetadata() { + return idClassMetadata; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java b/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java index f9588e5..e04d2f4 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java +++ b/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java @@ -29,118 +29,117 @@ */ public class InternalListenerIntrospector { - /** - * EntityListener class - */ - private Class listenerClass; + /** + * EntityListener class + */ + private Class listenerClass; - /** - * Metadata of the listener class - */ - private InternalListenerMetadata metadata; + /** + * Metadata of the listener class + */ + private InternalListenerMetadata metadata; - /** - * A cache of previously processed listener classes - */ - private static Cache, InternalListenerMetadata> cache = new Cache<>(); + /** + * A cache of previously processed listener classes + */ + private static Cache, InternalListenerMetadata> cache = new Cache<>(); - /** - * Creates a new instance of InternalListenerIntrospector. - * - * @param listenerClass - * the listener class to introspect - */ - private InternalListenerIntrospector(Class listenerClass) { - this.listenerClass = listenerClass; - } + /** + * Creates a new instance of InternalListenerIntrospector. + * + * @param listenerClass + * the listener class to introspect + */ + private InternalListenerIntrospector(Class listenerClass) { + this.listenerClass = listenerClass; + } - /** - * Introspects the given class for any defined listeners and returns the - * metadata. - * - * @param listenerClass - * the entity listener class - * @return the entity listener metadata - */ - public static InternalListenerMetadata introspect(Class listenerClass) { - InternalListenerMetadata cachedMetadata = cache.get(listenerClass); - if (cachedMetadata != null) { - return cachedMetadata; - } - synchronized (listenerClass) { - cachedMetadata = cache.get(listenerClass); - if (cachedMetadata != null) { - return cachedMetadata; - } - InternalListenerIntrospector introspector = new InternalListenerIntrospector(listenerClass); - introspector.introspect(); - cache.put(listenerClass, introspector.metadata); - return introspector.metadata; - } - } + /** + * Introspects the given class for any defined listeners and returns the metadata. + * + * @param listenerClass + * the entity listener class + * @return the entity listener metadata + */ + public static InternalListenerMetadata introspect(Class listenerClass) { + InternalListenerMetadata cachedMetadata = cache.get(listenerClass); + if (cachedMetadata != null) { + return cachedMetadata; + } + synchronized (listenerClass) { + cachedMetadata = cache.get(listenerClass); + if (cachedMetadata != null) { + return cachedMetadata; + } + InternalListenerIntrospector introspector = new InternalListenerIntrospector(listenerClass); + introspector.introspect(); + cache.put(listenerClass, introspector.metadata); + return introspector.metadata; + } + } - /** - * Introspects the listener class and creates the metadata. - */ - private void introspect() { - metadata = new InternalListenerMetadata(listenerClass); - processMethods(); - } + /** + * Introspects the listener class and creates the metadata. + */ + private void introspect() { + metadata = new InternalListenerMetadata(listenerClass); + processMethods(); + } - /** - * Processes the methods in the listener class and updates the metadata for - * any valid methods found. - */ - private void processMethods() { - Method[] methods = listenerClass.getDeclaredMethods(); - for (Method method : methods) { - for (CallbackType callbackType : CallbackType.values()) { - if (method.isAnnotationPresent(callbackType.getAnnotationClass())) { - validateMethod(method, callbackType); - metadata.putListener(callbackType, method); - } - } - } - } + /** + * Processes the methods in the listener class and updates the metadata for any valid methods + * found. + */ + private void processMethods() { + Method[] methods = listenerClass.getDeclaredMethods(); + for (Method method : methods) { + for (CallbackType callbackType : CallbackType.values()) { + if (method.isAnnotationPresent(callbackType.getAnnotationClass())) { + validateMethod(method, callbackType); + metadata.putListener(callbackType, method); + } + } + } + } - /** - * Validates the given method to ensure if it is a valid callback method for - * the given event type. - * - * @param method - * the method to validate - * @param callbackType - * the callback type - */ - private void validateMethod(Method method, CallbackType callbackType) { - int modifiers = method.getModifiers(); - if (!Modifier.isPublic(modifiers)) { - String message = String.format("Method %s in class %s must be public", method.getName(), - method.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - if (Modifier.isStatic(modifiers)) { - String message = String.format("Method %s in class %s must not be static", method.getName(), - method.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - if (Modifier.isAbstract(modifiers)) { - String message = String.format("Method %s in class %s must not be abstract", method.getName(), - method.getDeclaringClass().getName()); - throw new EntityManagerException(message); - } - Class[] parameters = method.getParameterTypes(); - if (parameters.length != 0) { - String message = String.format( - "Method %s in class %s is not a valid %s callback method. Method must not have any parameters. ", - method.getName(), method.getDeclaringClass().getName(), callbackType); - throw new EntityManagerException(message); - } - if (method.getReturnType() != void.class) { - String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), - method.getDeclaringClass().getName(), void.class.getName()); - throw new EntityManagerException(message); - } - } + /** + * Validates the given method to ensure if it is a valid callback method for the given event type. + * + * @param method + * the method to validate + * @param callbackType + * the callback type + */ + private void validateMethod(Method method, CallbackType callbackType) { + int modifiers = method.getModifiers(); + if (!Modifier.isPublic(modifiers)) { + String message = String.format("Method %s in class %s must be public", method.getName(), + method.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + if (Modifier.isStatic(modifiers)) { + String message = String.format("Method %s in class %s must not be static", method.getName(), + method.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + if (Modifier.isAbstract(modifiers)) { + String message = String.format("Method %s in class %s must not be abstract", method.getName(), + method.getDeclaringClass().getName()); + throw new EntityManagerException(message); + } + Class[] parameters = method.getParameterTypes(); + if (parameters.length != 0) { + String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + + "have any parameters. "; + String message = String.format(pattern, method.getName(), + method.getDeclaringClass().getName(), callbackType); + throw new EntityManagerException(message); + } + if (method.getReturnType() != void.class) { + String message = String.format("Method %s in class %s must have a return type of %s", + method.getName(), method.getDeclaringClass().getName(), void.class.getName()); + throw new EntityManagerException(message); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/InternalListenerMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/InternalListenerMetadata.java index 14626ff..f826a0a 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/InternalListenerMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/InternalListenerMetadata.java @@ -24,14 +24,14 @@ */ public class InternalListenerMetadata extends AbstractListenerMetadata { - /** - * Creates a new instance of InternalListenerMetadata. - * - * @param listenerClass - * the listener class to which this metadata belongs. - */ - public InternalListenerMetadata(Class listenerClass) { - super(listenerClass); - } + /** + * Creates a new instance of InternalListenerMetadata. + * + * @param listenerClass + * the listener class to which this metadata belongs. + */ + public InternalListenerMetadata(Class listenerClass) { + super(listenerClass); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java b/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java index df07a75..0da232b 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java +++ b/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java @@ -41,450 +41,439 @@ */ public class IntrospectionUtils { - /** - * Hide the default constructor. - */ - private IntrospectionUtils() { - // Do nothing - } - - /** - * Valid/Supported prefixes for mutator methods of a Builder class. Methods - * will be searched in the order. - */ - private static final String[] WRITE_METHOD_PREFIXES = { "set", "with", null }; - - /** - * Creates and returns a new instance of a persistence class for the given - * metadata. The returned object will be an instance of the primary - * persistence class or its Builder. - * - * @param metadata - * the metadata of the class - * @return a new instance of the of the Class to which the given metadata - * belongs. - * @throws EntityManagerException - * if any error occurs during instantiation. - */ - public static Object instantiate(MetadataBase metadata) { - try { - return metadata.getConstructorMetadata().getConstructorMethodHandle().invoke(); - } catch (Throwable t) { - throw new EntityManagerException(t); - } - } - - /** - * Returns the metadata for the given field. - * - * @param field - * the field whose metadata has to be prepared - * @return metadata of the given field. - */ - public static PropertyMetadata getPropertyMetadata(Field field) { - Property property = field.getAnnotation(Property.class); - // For fields that have @Property annotation, we expect both setter and - // getter methods. For all other fields, we only treat them as - // persistable if we find valid getter and setter methods. - try { - PropertyMetadata propertyMetadata = new PropertyMetadata(field); - return propertyMetadata; - } catch (NoAccessorMethodException | NoMutatorMethodException exp) { - if (property != null) { - throw exp; - } - } - return null; - } - - /** - * Finds and returns a {@link MethodHandle} that can be used to read the - * field represented by the given metadata. - * - * @param field - * the field - * - * @return the {@link MethodHandle} for reading the field's value - * @throws EntityManagerException - * if no read method exists - */ - public static MethodHandle findReadMethodHandle(Field field) { - String readMethodName; - MethodHandle mh = null; - if (boolean.class.equals(field.getType())) { - readMethodName = IntrospectionUtils.getReadMethodNameForBoolean(field); - mh = findInstanceMethod(field.getDeclaringClass(), readMethodName, field.getType()); - } - if (mh == null) { - readMethodName = getReadMethodName(field); - mh = findInstanceMethod(field.getDeclaringClass(), readMethodName, field.getType()); - } - if (mh == null) { - String pattern = "Class %s requires a public accessor method for field %s"; - throw new NoAccessorMethodException( - String.format(pattern, field.getDeclaringClass().getName(), field.getName())); - } - return mh; - } - - /** - * Finds and returns a {@link MethodHandle} that can be used to update a - * field represented by the given metadata. - * - * @param field - * the field - * - * @return the {@link MethodHandle} to update the field - * @throws NoMutatorMethodException - * if no matching method exists - */ - public static MethodHandle findWriteMethodHandle(Field field) { - ConstructorMetadata constructorMetadata = ConstructorIntrospector.introspect(field.getDeclaringClass()); - Class containerClass; - MethodHandle mh = null; - if (constructorMetadata.isBuilderConstructionStrategy()) { - containerClass = constructorMetadata.getBuilderClass(); - for (String prefix : WRITE_METHOD_PREFIXES) { - mh = findInstanceMethod(containerClass, getWriteMethodName(field, prefix), null, field.getType()); - if (mh != null) { - break; - } - } - } else { - containerClass = field.getDeclaringClass(); - mh = findInstanceMethod(containerClass, getWriteMethodName(field), null, field.getType()); - } - if (mh == null) { - String pattern = "Class %s requires a public mutator method for field %s"; - throw new NoMutatorMethodException(String.format(pattern, containerClass.getName(), field.getName())); - } - return mh; - } - - /** - * Returns all potentially persistable fields that were declared in the - * specified class. This method filters out the static fields and any fields - * that have an annotation of {@link Ignore}, and returns the rest of the - * declared fields. - * - * @param clazz - * the class - * @return all potentially persistable fields that were declared in the - * specified class. - */ - public static List getPersistableFields(Class clazz) { - Field[] fields = clazz.getDeclaredFields(); - List output = new ArrayList<>(fields.length); - for (Field field : fields) { - if (!(field.isAnnotationPresent(Ignore.class) || isStatic(field))) { - output.add(field); - } - } - return output; - } - - /** - * Returns the name of the method that can be used to read the given field. - * - * @param field - * the field - * @return the name of the read method, - */ - public static String getReadMethodName(Field field) { - return "get" + getCapitalizedName(field.getName()); - - } - - /** - * Returns the name of the method that can be used to read the given boolean - * field. - * - * @param field - * the field name - * @return the name of the read method. - */ - public static String getReadMethodNameForBoolean(Field field) { - return "is" + getCapitalizedName(field.getName()); - - } - - /** - * Returns the name of the method that can be used to write (or set) the - * given field. - * - * @param field - * the name of the field - * @return the name of the write method. - */ - public static String getWriteMethodName(Field field) { - return "set" + getCapitalizedName(field.getName()); - - } - - /** - * Returns the name of the method that can be used to write (or set) the - * given field. - * - * @param field - * the name of the field - * @param prefix - * the prefix for the write method (e.g. set, with, etc.). - * @return the name of the write method. - */ - public static String getWriteMethodName(Field field, String prefix) { - return prefix == null ? field.getName() : (prefix + getCapitalizedName(field.getName())); - - } - - /** - * Capitalizes the given field name. - * - * @param fieldName - * the field name - * @return capitalized field name. - */ - public static String getCapitalizedName(String fieldName) { - if (fieldName.length() > 1 && Character.isUpperCase(fieldName.charAt(1))) { - return fieldName; - } - return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); - } - - /** - * Creates a new object of given class by invoking the class' default public - * constructor. - * - * @param clazz - * the class whose instance needs to be created - * @return a new instance of the given class - * @throws EntityManagerException - * if any error occurs - */ - public static Object instantiateObject(Class clazz) { - try { - Constructor constructor = clazz.getConstructor(); - return constructor.newInstance(); - } catch (Exception exp) { - throw new EntityManagerException(exp); - } - - } - - /** - * Examines the given Collection type (List and Set) and returns the Class - * and Parameterized type, if any. - * - * @param type - * the Collection type - * @return an array of Class objects with two elements. The first element - * will contain the raw type of the collection and the second will - * contain the parameterized type. If the collection declaration is - * not parameterized, the second element in the array is set to - * null. - */ - public static Class[] resolveCollectionType(Type type) { - Class[] output = new Class[2]; - if (type instanceof Class) { - output[0] = (Class) type; - } else if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - Type[] argTypes = parameterizedType.getActualTypeArguments(); - output[0] = (Class) parameterizedType.getRawType(); - if (argTypes != null && argTypes.length == 1 && argTypes[0] instanceof Class) { - output[1] = (Class) argTypes[0]; - } - } else { - throw new IllegalArgumentException( - String.format("Type %s is neither a Class nor a ParameterizedType", type)); - } - return output; - } - - /** - * Examines the given Map type and returns the raw type, type of keys, type - * of values in the map. - * - * @param type - * the type of map - * @return an array containing three elements: - *
    - *
  • Raw type of Map
  • - *
  • Type of Keys, may be null
  • - *
  • Type of Values, may be null
  • - *
- */ - public static Class[] resolveMapType(Type type) { - Class[] output = new Class[3]; - if (type instanceof Class) { - output[0] = (Class) type; - } else if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - output[0] = (Class) parameterizedType.getRawType(); - Type[] argTypes = parameterizedType.getActualTypeArguments(); - if (argTypes != null && argTypes.length == 2) { - if (argTypes[0] instanceof Class) { - output[1] = (Class) argTypes[0]; - } - if (argTypes[1] instanceof Class) { - output[2] = (Class) argTypes[1]; - } - } - } else { - throw new IllegalArgumentException( - String.format("Type %s is neither a Class nor a ParameterizedType", type)); - } - return output; - } - - /** - * Returns a public constructor of the given class with the given parameter - * types. Returns null, if there is no matching constructor. - * - * @param clazz - * the class - * @param parameterTypes - * expected types of parameters - * @return the matching public constructor or null, if there is - * no matching constructor. - */ - public static Constructor getConstructor(Class clazz, Class... parameterTypes) { - try { - if (parameterTypes != null && parameterTypes.length > 0) { - return clazz.getConstructor(parameterTypes); - } else { - return clazz.getConstructor(); - } - } catch (Exception exp) { - return null; - } - } - - /** - * Checks to see if the given field is a static field. - * - * @param field - * the field to test - * @return true, if the given field is static; - * false, otherwise. - */ - public static boolean isStatic(Field field) { - int modifiers = field.getModifiers(); - return Modifier.isStatic(modifiers); - } - - /** - * Returns the value of the field represented by the given metadata. - * - * @param fieldMetadata - * the metadata of the field - * @param target - * the target object to which the field belongs. - * @return the value of the field. - */ - public static Object getFieldValue(FieldMetadata fieldMetadata, Object target) { - MethodHandle readMethod = fieldMetadata.getReadMethod(); - try { - return readMethod.invoke(target); - } catch (Throwable t) { - throw new EntityManagerException(t.getMessage(), t); - } - } - - /** - * Finds and returns a MethodHandle for the default constructor of the given - * class, {@code clazz}. - * - * @param clazz - * the class - * @return a MethodHandle for the default constructor. Returns {@code null} - * if the class does not have a public no-argument constructor. - */ - public static MethodHandle findDefaultConstructor(Class clazz) { - MethodHandle methodHandle = null; - try { - Constructor constructor = clazz.getConstructor(); - methodHandle = MethodHandles.publicLookup().unreflectConstructor(constructor); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) { - // No default constructor - } - return methodHandle; - } - - /** - * Finds and returns a MethodHandle for a public static method. - * - * @param clazz - * the class to search - * @param methodName - * the name of the method - * @param expectedReturnType - * the expected return type. If {@code null}, any return type is - * treated as valid. - * @param expectedParameterTypes - * expected parameter types - * @return a MethodHandle for the specified criteria. Returns {@code null} - * if no method exists with the specified criteria. - */ - public static MethodHandle findStaticMethod(Class clazz, String methodName, Class expectedReturnType, - Class... expectedParameterTypes) { - return findMethod(clazz, methodName, true, expectedReturnType, expectedParameterTypes); - } - - /** - * Finds and returns a MethodHandle for a public instance method. - * - * @param clazz - * the class to search - * @param methodName - * the name of the method - * @param expectedReturnType - * the expected return type. If {@code null}, any return type is - * treated as valid. - * @param expectedParameterTypes - * expected parameter types - * @return a MethodHandle for the specified criteria. Returns {@code null} - * if no method exists with the specified criteria. - */ - public static MethodHandle findInstanceMethod(Class clazz, String methodName, Class expectedReturnType, - Class... expectedParameterTypes) { - return findMethod(clazz, methodName, false, expectedReturnType, expectedParameterTypes); - } - - /** - * Finds and returns a method handle for the given criteria. - * - * @param clazz - * the class to search - * @param methodName - * the name of the method - * @param staticMethod - * whether the method is static or not - * @param expectedReturnType - * expected return type - * @param expectedParameterTypes - * expected parameter types - * @return a methodHandle for the specified criteria. Returns {@code null} - * if no method exists with the specified criteria. - */ - private static MethodHandle findMethod(Class clazz, String methodName, boolean staticMethod, - Class expectedReturnType, Class... expectedParameterTypes) { - MethodHandle methodHandle = null; - try { - Method method = clazz.getMethod(methodName, expectedParameterTypes); - int modifiers = method.getModifiers(); - Class returnType = method.getReturnType(); - if (Modifier.isStatic(modifiers) != staticMethod) { - throw new NoSuchMethodException(); - } - if (expectedReturnType != null && !expectedReturnType.isAssignableFrom(returnType)) { - throw new NoSuchMethodException(); - } - methodHandle = MethodHandles.publicLookup().unreflect(method); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) { - // Method not found - } - return methodHandle; - - } + /** + * Hide the default constructor. + */ + private IntrospectionUtils() { + // Do nothing + } + + /** + * Valid/Supported prefixes for mutator methods of a Builder class. Methods will be searched in + * the order. + */ + private static final String[] WRITE_METHOD_PREFIXES = { "set", "with", null }; + + /** + * Creates and returns a new instance of a persistence class for the given metadata. The returned + * object will be an instance of the primary persistence class or its Builder. + * + * @param metadata + * the metadata of the class + * @return a new instance of the of the Class to which the given metadata belongs. + * @throws EntityManagerException + * if any error occurs during instantiation. + */ + public static Object instantiate(MetadataBase metadata) { + try { + return metadata.getConstructorMetadata().getConstructorMethodHandle().invoke(); + } catch (Throwable t) { + throw new EntityManagerException(t); + } + } + + /** + * Returns the metadata for the given field. + * + * @param field + * the field whose metadata has to be prepared + * @return metadata of the given field. + */ + public static PropertyMetadata getPropertyMetadata(Field field) { + Property property = field.getAnnotation(Property.class); + // For fields that have @Property annotation, we expect both setter and + // getter methods. For all other fields, we only treat them as + // persistable if we find valid getter and setter methods. + try { + PropertyMetadata propertyMetadata = new PropertyMetadata(field); + return propertyMetadata; + } catch (NoAccessorMethodException | NoMutatorMethodException exp) { + if (property != null) { + throw exp; + } + } + return null; + } + + /** + * Finds and returns a {@link MethodHandle} that can be used to read the field represented by the + * given metadata. + * + * @param field + * the field + * + * @return the {@link MethodHandle} for reading the field's value + * @throws EntityManagerException + * if no read method exists + */ + public static MethodHandle findReadMethodHandle(Field field) { + String readMethodName; + MethodHandle mh = null; + if (boolean.class.equals(field.getType())) { + readMethodName = IntrospectionUtils.getReadMethodNameForBoolean(field); + mh = findInstanceMethod(field.getDeclaringClass(), readMethodName, field.getType()); + } + if (mh == null) { + readMethodName = getReadMethodName(field); + mh = findInstanceMethod(field.getDeclaringClass(), readMethodName, field.getType()); + } + if (mh == null) { + String pattern = "Class %s requires a public accessor method for field %s"; + throw new NoAccessorMethodException( + String.format(pattern, field.getDeclaringClass().getName(), field.getName())); + } + return mh; + } + + /** + * Finds and returns a {@link MethodHandle} that can be used to update a field represented by the + * given metadata. + * + * @param field + * the field + * + * @return the {@link MethodHandle} to update the field + * @throws NoMutatorMethodException + * if no matching method exists + */ + public static MethodHandle findWriteMethodHandle(Field field) { + ConstructorMetadata constructorMetadata = ConstructorIntrospector + .introspect(field.getDeclaringClass()); + Class containerClass; + MethodHandle mh = null; + if (constructorMetadata.isBuilderConstructionStrategy()) { + containerClass = constructorMetadata.getBuilderClass(); + for (String prefix : WRITE_METHOD_PREFIXES) { + mh = findInstanceMethod(containerClass, getWriteMethodName(field, prefix), null, + field.getType()); + if (mh != null) { + break; + } + } + } else { + containerClass = field.getDeclaringClass(); + mh = findInstanceMethod(containerClass, getWriteMethodName(field), null, field.getType()); + } + if (mh == null) { + String pattern = "Class %s requires a public mutator method for field %s"; + throw new NoMutatorMethodException( + String.format(pattern, containerClass.getName(), field.getName())); + } + return mh; + } + + /** + * Returns all potentially persistable fields that were declared in the specified class. This + * method filters out the static fields and any fields that have an annotation of {@link Ignore}, + * and returns the rest of the declared fields. + * + * @param clazz + * the class + * @return all potentially persistable fields that were declared in the specified class. + */ + public static List getPersistableFields(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + List output = new ArrayList<>(fields.length); + for (Field field : fields) { + if (!(field.isAnnotationPresent(Ignore.class) || isStatic(field))) { + output.add(field); + } + } + return output; + } + + /** + * Returns the name of the method that can be used to read the given field. + * + * @param field + * the field + * @return the name of the read method, + */ + public static String getReadMethodName(Field field) { + return "get" + getCapitalizedName(field.getName()); + + } + + /** + * Returns the name of the method that can be used to read the given boolean field. + * + * @param field + * the field name + * @return the name of the read method. + */ + public static String getReadMethodNameForBoolean(Field field) { + return "is" + getCapitalizedName(field.getName()); + + } + + /** + * Returns the name of the method that can be used to write (or set) the given field. + * + * @param field + * the name of the field + * @return the name of the write method. + */ + public static String getWriteMethodName(Field field) { + return "set" + getCapitalizedName(field.getName()); + + } + + /** + * Returns the name of the method that can be used to write (or set) the given field. + * + * @param field + * the name of the field + * @param prefix + * the prefix for the write method (e.g. set, with, etc.). + * @return the name of the write method. + */ + public static String getWriteMethodName(Field field, String prefix) { + return prefix == null ? field.getName() : (prefix + getCapitalizedName(field.getName())); + + } + + /** + * Capitalizes the given field name. + * + * @param fieldName + * the field name + * @return capitalized field name. + */ + public static String getCapitalizedName(String fieldName) { + if (fieldName.length() > 1 && Character.isUpperCase(fieldName.charAt(1))) { + return fieldName; + } + return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); + } + + /** + * Creates a new object of given class by invoking the class' default public constructor. + * + * @param clazz + * the class whose instance needs to be created + * @return a new instance of the given class + * @throws EntityManagerException + * if any error occurs + */ + public static Object instantiateObject(Class clazz) { + try { + Constructor constructor = clazz.getConstructor(); + return constructor.newInstance(); + } catch (Exception exp) { + throw new EntityManagerException(exp); + } + + } + + /** + * Examines the given Collection type (List and Set) and returns the Class and Parameterized type, + * if any. + * + * @param type + * the Collection type + * @return an array of Class objects with two elements. The first element will contain the raw + * type of the collection and the second will contain the parameterized type. If the + * collection declaration is not parameterized, the second element in the array is set to + * null. + */ + public static Class[] resolveCollectionType(Type type) { + Class[] output = new Class[2]; + if (type instanceof Class) { + output[0] = (Class) type; + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Type[] argTypes = parameterizedType.getActualTypeArguments(); + output[0] = (Class) parameterizedType.getRawType(); + if (argTypes != null && argTypes.length == 1 && argTypes[0] instanceof Class) { + output[1] = (Class) argTypes[0]; + } + } else { + throw new IllegalArgumentException( + String.format("Type %s is neither a Class nor a ParameterizedType", type)); + } + return output; + } + + /** + * Examines the given Map type and returns the raw type, type of keys, type of values in the map. + * + * @param type + * the type of map + * @return an array containing three elements: + *
    + *
  • Raw type of Map
  • + *
  • Type of Keys, may be null
  • + *
  • Type of Values, may be null
  • + *
+ */ + public static Class[] resolveMapType(Type type) { + Class[] output = new Class[3]; + if (type instanceof Class) { + output[0] = (Class) type; + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + output[0] = (Class) parameterizedType.getRawType(); + Type[] argTypes = parameterizedType.getActualTypeArguments(); + if (argTypes != null && argTypes.length == 2) { + if (argTypes[0] instanceof Class) { + output[1] = (Class) argTypes[0]; + } + if (argTypes[1] instanceof Class) { + output[2] = (Class) argTypes[1]; + } + } + } else { + throw new IllegalArgumentException( + String.format("Type %s is neither a Class nor a ParameterizedType", type)); + } + return output; + } + + /** + * Returns a public constructor of the given class with the given parameter types. Returns + * null, if there is no matching constructor. + * + * @param clazz + * the class + * @param parameterTypes + * expected types of parameters + * @return the matching public constructor or null, if there is no matching + * constructor. + */ + public static Constructor getConstructor(Class clazz, Class... parameterTypes) { + try { + if (parameterTypes != null && parameterTypes.length > 0) { + return clazz.getConstructor(parameterTypes); + } else { + return clazz.getConstructor(); + } + } catch (Exception exp) { + return null; + } + } + + /** + * Checks to see if the given field is a static field. + * + * @param field + * the field to test + * @return true, if the given field is static; false, otherwise. + */ + public static boolean isStatic(Field field) { + int modifiers = field.getModifiers(); + return Modifier.isStatic(modifiers); + } + + /** + * Returns the value of the field represented by the given metadata. + * + * @param fieldMetadata + * the metadata of the field + * @param target + * the target object to which the field belongs. + * @return the value of the field. + */ + public static Object getFieldValue(FieldMetadata fieldMetadata, Object target) { + MethodHandle readMethod = fieldMetadata.getReadMethod(); + try { + return readMethod.invoke(target); + } catch (Throwable t) { + throw new EntityManagerException(t.getMessage(), t); + } + } + + /** + * Finds and returns a MethodHandle for the default constructor of the given class, {@code clazz}. + * + * @param clazz + * the class + * @return a MethodHandle for the default constructor. Returns {@code null} if the class does not + * have a public no-argument constructor. + */ + public static MethodHandle findDefaultConstructor(Class clazz) { + MethodHandle methodHandle = null; + try { + Constructor constructor = clazz.getConstructor(); + methodHandle = MethodHandles.publicLookup().unreflectConstructor(constructor); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) { + // No default constructor + } + return methodHandle; + } + + /** + * Finds and returns a MethodHandle for a public static method. + * + * @param clazz + * the class to search + * @param methodName + * the name of the method + * @param expectedReturnType + * the expected return type. If {@code null}, any return type is treated as valid. + * @param expectedParameterTypes + * expected parameter types + * @return a MethodHandle for the specified criteria. Returns {@code null} if no method exists + * with the specified criteria. + */ + public static MethodHandle findStaticMethod(Class clazz, String methodName, + Class expectedReturnType, Class... expectedParameterTypes) { + return findMethod(clazz, methodName, true, expectedReturnType, expectedParameterTypes); + } + + /** + * Finds and returns a MethodHandle for a public instance method. + * + * @param clazz + * the class to search + * @param methodName + * the name of the method + * @param expectedReturnType + * the expected return type. If {@code null}, any return type is treated as valid. + * @param expectedParameterTypes + * expected parameter types + * @return a MethodHandle for the specified criteria. Returns {@code null} if no method exists + * with the specified criteria. + */ + public static MethodHandle findInstanceMethod(Class clazz, String methodName, + Class expectedReturnType, Class... expectedParameterTypes) { + return findMethod(clazz, methodName, false, expectedReturnType, expectedParameterTypes); + } + + /** + * Finds and returns a method handle for the given criteria. + * + * @param clazz + * the class to search + * @param methodName + * the name of the method + * @param staticMethod + * whether the method is static or not + * @param expectedReturnType + * expected return type + * @param expectedParameterTypes + * expected parameter types + * @return a methodHandle for the specified criteria. Returns {@code null} if no method exists + * with the specified criteria. + */ + private static MethodHandle findMethod(Class clazz, String methodName, boolean staticMethod, + Class expectedReturnType, Class... expectedParameterTypes) { + MethodHandle methodHandle = null; + try { + Method method = clazz.getMethod(methodName, expectedParameterTypes); + int modifiers = method.getModifiers(); + Class returnType = method.getReturnType(); + if (Modifier.isStatic(modifiers) != staticMethod) { + throw new NoSuchMethodException(); + } + if (expectedReturnType != null && !expectedReturnType.isAssignableFrom(returnType)) { + throw new NoSuchMethodException(); + } + methodHandle = MethodHandles.publicLookup().unreflect(method); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) { + // Method not found + } + return methodHandle; + + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/KeyMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/KeyMetadata.java index aa86079..96353f8 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/KeyMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/KeyMetadata.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Field; @@ -24,14 +25,14 @@ */ public class KeyMetadata extends FieldMetadata { - /** - * Creates a new instance of KeyMetadata. - * - * @param field - * the field. - */ - public KeyMetadata(Field field) { - super(field); - } + /** + * Creates a new instance of KeyMetadata. + * + * @param field + * the field. + */ + public KeyMetadata(Field field) { + super(field); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/LRUCache.java b/src/main/java/com/jmethods/catatumbo/impl/LRUCache.java index c1d7657..d5a711b 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/LRUCache.java +++ b/src/main/java/com/jmethods/catatumbo/impl/LRUCache.java @@ -13,126 +13,126 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.util.LinkedHashMap; import java.util.Map; /** - * A simple LRU (Least Recently Used) cache that limits the maximum size of - * cache to the specified capacity. When new entries are placed in the cache, - * the oldest accessed entry is removed. + * A simple LRU (Least Recently Used) cache that limits the maximum size of cache to the specified + * capacity. When new entries are placed in the cache, the oldest accessed entry is removed. * * @author Sai Pullabhotla * @param - * Key + * Key * @param - * Value + * Value */ public class LRUCache { - /** - * Cache store - */ - private LinkedHashMap map; + /** + * Cache store + */ + private LinkedHashMap map; - /** - * Maximum capacity - */ - private int maxCapacity; + /** + * Maximum capacity + */ + private int maxCapacity; - /** - * Creates a new instance of LRUCache. - * - * @param initialCapacity - * initial capacity - * @param maxCapacity - * maximum capacity - */ - public LRUCache(final int initialCapacity, int maxCapacity) { - setMaxCapacity(maxCapacity); - map = new LinkedHashMap(initialCapacity, 0.75f, true) { - /** - * Serial version UID - */ - private static final long serialVersionUID = 7959078771128286844L; + /** + * Creates a new instance of LRUCache. + * + * @param initialCapacity + * initial capacity + * @param maxCapacity + * maximum capacity + */ + public LRUCache(final int initialCapacity, int maxCapacity) { + setMaxCapacity(maxCapacity); + map = new LinkedHashMap(initialCapacity, 0.75f, true) { + /** + * Serial version UID + */ + private static final long serialVersionUID = 7959078771128286844L; - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > LRUCache.this.maxCapacity; - } - }; + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > LRUCache.this.maxCapacity; + } + }; - } + } - /** - * Returns the maximum capacity. - * - * @return the maximum capacity. - */ - public int getMaxCapacity() { - return maxCapacity; - } + /** + * Returns the maximum capacity. + * + * @return the maximum capacity. + */ + public int getMaxCapacity() { + return maxCapacity; + } - /** - * Sets the maximum capacity. - * - * @param maxCapacity - * the maximum capacity - */ - public void setMaxCapacity(int maxCapacity) { - if (maxCapacity < 1) { - throw new IllegalArgumentException("maxCapacity must not be less than 1"); - } - this.maxCapacity = maxCapacity; - } + /** + * Sets the maximum capacity. + * + * @param maxCapacity + * the maximum capacity + */ + public void setMaxCapacity(int maxCapacity) { + if (maxCapacity < 1) { + throw new IllegalArgumentException("maxCapacity must not be less than 1"); + } + this.maxCapacity = maxCapacity; + } - /** - * Returns the cached object associated the given key. - * - * @param key - * the key - * @return the cached object associated the given key. - */ - public synchronized V get(K key) { - return map.get(key); - } + /** + * Returns the cached object associated the given key. + * + * @param key + * the key + * @return the cached object associated the given key. + */ + public synchronized V get(K key) { + return map.get(key); + } - /** - * Adds the given key and value to this cache. - * - * @param key - * the key - * @param value - * the value - * @return old value associated with the given key, if any. - */ - public synchronized V put(K key, V value) { - return map.put(key, value); - } + /** + * Adds the given key and value to this cache. + * + * @param key + * the key + * @param value + * the value + * @return old value associated with the given key, if any. + */ + public synchronized V put(K key, V value) { + return map.put(key, value); + } - /** - * Checks to see if the given key exists in this cache. - * - * @param key - * the key - * @return true, if the given key exists in this cache; false, otherwise. - */ - public synchronized boolean containsKey(K key) { - return map.containsKey(key); - } + /** + * Checks to see if the given key exists in this cache. + * + * @param key + * the key + * @return true, if the given key exists in this cache; false, otherwise. + */ + public synchronized boolean containsKey(K key) { + return map.containsKey(key); + } - /** - * Returns the current size of this cache. - * - * @return the current size of this cache. - */ - public int size() { - return map.size(); - } + /** + * Returns the current size of this cache. + * + * @return the current size of this cache. + */ + public int size() { + return map.size(); + } - @Override - public String toString() { - return map.toString(); - } + @Override + public String toString() { + return map.toString(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ListenerFactory.java b/src/main/java/com/jmethods/catatumbo/impl/ListenerFactory.java index 7f4d438..dcd08e2 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ListenerFactory.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ListenerFactory.java @@ -19,73 +19,72 @@ import com.jmethods.catatumbo.EntityListeners; /** - * A factory for creating instances of classes that are marked with - * {@link EntityListeners} annotation. This factory ensures that there exists - * only one instance of a given listener. Instance is created the first time it - * is needed and then cached for subsequent uses. + * A factory for creating instances of classes that are marked with {@link EntityListeners} + * annotation. This factory ensures that there exists only one instance of a given listener. + * Instance is created the first time it is needed and then cached for subsequent uses. * * @author Sai Pullabhotla * */ public class ListenerFactory { - /** - * A cache of listener class and the corresponding listener instance. - */ - private Cache, Object> listeners; + /** + * A cache of listener class and the corresponding listener instance. + */ + private Cache, Object> listeners; - /** - * Singleton instance of this class - */ - private static final ListenerFactory INSTANCE = new ListenerFactory(); + /** + * Singleton instance of this class + */ + private static final ListenerFactory INSTANCE = new ListenerFactory(); - /** - * Creates a new instance of ListenerFactory. - */ - private ListenerFactory() { - listeners = new Cache<>(); - } + /** + * Creates a new instance of ListenerFactory. + */ + private ListenerFactory() { + listeners = new Cache<>(); + } - /** - * Returns the listener object for the given class. - * - * @param listenerClass - * the listener class - * @return the listener object for the given type - */ - public Object getListener(Class listenerClass) { - Object listener = listeners.get(listenerClass); - if (listener == null) { - listener = loadListener(listenerClass); - } - return listener; - } + /** + * Returns the listener object for the given class. + * + * @param listenerClass + * the listener class + * @return the listener object for the given type + */ + public Object getListener(Class listenerClass) { + Object listener = listeners.get(listenerClass); + if (listener == null) { + listener = loadListener(listenerClass); + } + return listener; + } - /** - * Returns the singleton instance of this class. - * - * @return the singleton instance of this class. - */ - public static ListenerFactory getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of this class. + * + * @return the singleton instance of this class. + */ + public static ListenerFactory getInstance() { + return INSTANCE; + } - /** - * Instantiates the listener of given type and caches it. - * - * @param listenerClass - * the listener type - * @return the instantiated object - */ - private Object loadListener(Class listenerClass) { - synchronized (listenerClass) { - Object listener = listeners.get(listenerClass); - if (listener == null) { - listener = IntrospectionUtils.instantiateObject(listenerClass); - listeners.put(listenerClass, listener); - } - return listener; - } - } + /** + * Instantiates the listener of given type and caches it. + * + * @param listenerClass + * the listener type + * @return the instantiated object + */ + private Object loadListener(Class listenerClass) { + synchronized (listenerClass) { + Object listener = listeners.get(listenerClass); + if (listener == null) { + listener = IntrospectionUtils.instantiateObject(listenerClass); + listeners.put(listenerClass, listener); + } + return listener; + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java b/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java index d1ec9d0..3d17a60 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java +++ b/src/main/java/com/jmethods/catatumbo/impl/Marshaller.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.time.Instant; @@ -40,640 +41,635 @@ import com.jmethods.catatumbo.impl.IdentifierMetadata.DataType; /** - * Converts application's entities (POJOs) to the format needed for the - * underlying Cloud Datastore API. + * Converts application's entities (POJOs) to the format needed for the underlying Cloud Datastore + * API. * * @author Sai Pullabhotla */ public class Marshaller { - /** - * The intent of marshalling an object. The marshalling may be different - * depending on the intended purpose. For example, if marshalling an object - * for UPDATE operation, the marshaller does not automatically generate a - * key. - * - * @author Sai Pullabhotla - * - */ - public enum Intent { - /** - * Insert - */ - INSERT(false, false), - - /** - * Update - */ - UPDATE(true, false), - - /** - * Upsert (Update or Insert) - */ - UPSERT(false, false), - - /** - * Delete - */ - DELETE(true, true), - - /** - * Batch Update - */ - BATCH_UPDATE(true, false); - - /** - * If a complete key is required for this Intent - */ - private boolean keyRequired; - - /** - * If this Intent (or operation) is valid on projected entities - */ - private boolean validOnProjectedEntities; - - /** - * Creates a new instance of Intent. - * - * @param keyRequired - * whether or not a complete key is required. - * @param validOnProjectedEntities - * whether or not this intent is valid on projected entities - */ - private Intent(boolean keyRequired, boolean validOnProjectedEntities) { - this.keyRequired = keyRequired; - this.validOnProjectedEntities = validOnProjectedEntities; - } - - /** - * Tells whether or not a complete key is required for this Intent. - * - * @return true, if a complete key is required; - * false, otherwise. - */ - public boolean isKeyRequired() { - return keyRequired; - } - - /** - * Tells whether or not this intent is valid on projected entities. - * - * @return true, if this intent is valid/supported on - * projected entities; false, otherwise. - */ - public boolean isValidOnProjectedEntities() { - return validOnProjectedEntities; - } - - } - - /** - * Reference to the EntityManager - */ - private DefaultEntityManager entityManager; - - /** - * Entity being marshaled - */ - private final Object entity; - - /** - * Metadata of the entity being marshaled - */ - private final EntityMetadata entityMetadata; - - /** - * Builder for building the Entity needed for Cloud Datastore - */ - private BaseEntity.Builder entityBuilder; - - /** - * Key - */ - private IncompleteKey key; - - /** - * The intent of marshalling - */ - private final Intent intent; - - /** - * Creates a new instance of Marshaller. - * - * @param entityManager - * reference to the entity manager - * @param entity - * the Entity to marshal - * @param intent - * the intent of marshalling - */ - private Marshaller(DefaultEntityManager entityManager, Object entity, Intent intent) { - this.entityManager = entityManager; - this.entity = entity; - this.intent = intent; - entityMetadata = EntityIntrospector.introspect(entity.getClass()); - validateIntent(); - } - - /** - * Validates if the Intent is legal for the entity being marshalled. - * - * @throws EntityManagerException - * if the Intent is not valid for the entity being marshalled - */ - private void validateIntent() { - if (entityMetadata.isProjectedEntity() && !intent.isValidOnProjectedEntities()) { - String message = String.format("Operation %s is not allowed for ProjectedEntity %s", intent, - entity.getClass().getName()); - throw new EntityManagerException(message); - } - } - - /** - * Marshals the given entity (POJO) into the format needed for the low level - * Cloud Datastore API. - * - * @param entityManager - * the entity manager - * @param entity - * the entity to marshal - * @param intent - * the intent or purpose of marshalling. Marshalling process - * varies slightly depending on the purpose. For example, if the - * purpose if INSERT or UPSERT, the marshaller would auto - * generate any keys. Where as if the purpose is UPDATE, then - * then marshaller will NOT generate any keys. - * @return the marshaled object - */ - @SuppressWarnings("rawtypes") - public static BaseEntity marshal(DefaultEntityManager entityManager, Object entity, Intent intent) { - Marshaller marshaller = new Marshaller(entityManager, entity, intent); - return marshaller.marshal(); - } - - /** - * Extracts the key from the given object, entity, and returns it. The - * entity must have its ID set. - * - * @param entityManager - * the entity manager. - * @param entity - * the entity from which key is to be extracted - * @return extracted key. - */ - public static Key marshalKey(DefaultEntityManager entityManager, Object entity) { - Marshaller marshaller = new Marshaller(entityManager, entity, Intent.DELETE); - marshaller.marshalKey(); - return (Key) marshaller.key; - } - - /** - * Marshals the given entity and and returns the equivalent Entity needed - * for the underlying Cloud Datastore API. - * - * @return A native entity that is equivalent to the POJO being marshalled. - * The returned value could either be a FullEntity or Entity. - */ - private BaseEntity marshal() { - marshalKey(); - if (key instanceof Key) { - entityBuilder = Entity.newBuilder((Key) key); - } else { - entityBuilder = FullEntity.newBuilder(key); - } - marshalFields(); - marshalAutoTimestampFields(); - if (intent == Intent.UPDATE) { - marshalVersionField(); - } - marshalEmbeddedFields(); - return entityBuilder.build(); - } - - /** - * Marshals the key. - */ - private void marshalKey() { - - Key parent = null; - - ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); - if (parentKeyMetadata != null) { - DatastoreKey parentDatastoreKey = (DatastoreKey) getFieldValue(parentKeyMetadata); - if (parentDatastoreKey != null) { - parent = parentDatastoreKey.nativeKey(); - } - } - - IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); - IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); - DataType identifierType = identifierMetadata.getDataType(); - Object idValue = getFieldValue(identifierMetadata); - - // If ID value is null, we don't have to worry about if it is a simple - // type of a complex type. Otherwise, we need to see if the ID is a - // complex type, and if it is, extract the real ID. - if (idValue != null && idClassMetadata != null) { - try { - idValue = idClassMetadata.getReadMethod().invoke(idValue); - } catch (Throwable t) { - throw new EntityManagerException(t); - } - } - - boolean validId = isValidId(idValue, identifierType); - boolean autoGenerateId = identifierMetadata.isAutoGenerated(); - - if (validId) { - if (identifierType == DataType.STRING) { - createCompleteKey(parent, (String) idValue); - } else { - createCompleteKey(parent, (long) idValue); - } - } else { - if (intent.isKeyRequired()) { - throw new EntityManagerException( - String.format("Identifier is not set or valid for entity of type %s", entity.getClass())); - } - if (!autoGenerateId) { - throw new EntityManagerException(String.format( - "Identifier is not set or valid for entity of type %s. Auto generation of ID is explicitly turned off. ", - entity.getClass())); - } else { - if (identifierType == DataType.STRING) { - createCompleteKey(parent); - } else { - createIncompleteKey(parent); - } - } - } - } - - /** - * Checks to see if the given value is a valid identifier for the given ID - * type. - * - * @param idValue - * the ID value - * @param identifierType - * the identifier type - * @return true, if the given value is a valid identifier; - * false, otherwise. For STRING type, the ID is valid - * if it it contains at least one printable character. In other - * words, if ((String) idValue).trim().length() > 0. For numeric - * types, the ID is valid if it is not null or zero. - */ - private static boolean isValidId(Object idValue, DataType identifierType) { - boolean validId = false; - if (idValue != null) { - switch (identifierType) { - case LONG: - case LONG_OBJECT: - validId = (long) idValue != 0; - break; - case STRING: - validId = ((String) idValue).trim().length() > 0; - break; - default: - // we should never get here - break; - } - } - return validId; - } - - /** - * Creates a complete key using the given parameters. - * - * @param parent - * the parent key, may be null. - * @param id - * the numeric ID - */ - private void createCompleteKey(Key parent, long id) { - String kind = entityMetadata.getKind(); - if (parent == null) { - key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); - } else { - key = Key.newBuilder(parent, kind, id).build(); - } - } - - /** - * Creates a complete key using the given parameters. - * - * @param parent - * the parent key, may be null. - * @param id - * the String ID - */ - private void createCompleteKey(Key parent, String id) { - String kind = entityMetadata.getKind(); - if (parent == null) { - key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); - } else { - key = Key.newBuilder(parent, kind, id).build(); - } - } - - /** - * Creates a CompleteKey using the given parameters. The actual ID is - * generated using UUID.randomUUID().toString(). - * - * @param parent - * the parent key, may be null. - */ - private void createCompleteKey(Key parent) { - String kind = entityMetadata.getKind(); - String id = UUID.randomUUID().toString(); - if (parent == null) { - key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); - } else { - key = Key.newBuilder(parent, kind, id).build(); - } - } - - /** - * Creates an IncompleteKey. - * - * @param parent - * the parent key, may be null. - */ - private void createIncompleteKey(Key parent) { - String kind = entityMetadata.getKind(); - if (parent == null) { - key = entityManager.newNativeKeyFactory().setKind(kind).newKey(); - } else { - key = IncompleteKey.newBuilder(parent, kind).build(); - } - } - - /** - * Marshals all the fields. - */ - private void marshalFields() { - Collection propertyMetadataCollection = entityMetadata.getPropertyMetadataCollection(); - for (PropertyMetadata propertyMetadata : propertyMetadataCollection) { - marshalField(propertyMetadata, entity); - } - } - - /** - * Marshals the field with the given property metadata. - * - * @param propertyMetadata - * the metadata of the field to be marshaled. - * @param target - * the object in which the field is defined/accessible from. - */ - private void marshalField(PropertyMetadata propertyMetadata, Object target) { - marshalField(propertyMetadata, target, entityBuilder); - } - - /** - * Marshals the field with the given property metadata. - * - * @param propertyMetadata - * the metadata of the field to be marshaled. - * @param target - * the object in which the field is defined/accessible from - * @param entityBuilder - * the native entity on which the marshaled field should be set - */ - private static void marshalField(PropertyMetadata propertyMetadata, Object target, - BaseEntity.Builder entityBuilder) { - Object fieldValue = IntrospectionUtils.getFieldValue(propertyMetadata, target); - if (fieldValue == null && propertyMetadata.isOptional()) { - return; - } - ValueBuilder valueBuilder = propertyMetadata.getMapper().toDatastore(fieldValue); - // ListValues cannot have indexing turned off. Indexing is turned on by - // default, so we don't touch excludeFromIndexes for ListValues. - if (valueBuilder.getValueType() != ValueType.LIST) { - valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); - } - Value datastoreValue = valueBuilder.build(); - entityBuilder.set(propertyMetadata.getMappedName(), datastoreValue); - Indexer indexer = propertyMetadata.getSecondaryIndexer(); - if (indexer != null) { - entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(datastoreValue)); - } - } - - /** - * Returns the value for the given field of the entity being marshaled. - * - * @param fieldMetadata - * the field's metadata - * @return the field's value - */ - private Object getFieldValue(FieldMetadata fieldMetadata) { - return IntrospectionUtils.getFieldValue(fieldMetadata, entity); - } - - /** - * Marshals the embedded fields. - */ - private void marshalEmbeddedFields() { - for (EmbeddedMetadata embeddedMetadata : entityMetadata.getEmbeddedMetadataCollection()) { - if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { - marshalWithExplodedStrategy(embeddedMetadata, entity); - } else { - ValueBuilder embeddedEntityBuilder = marshalWithImplodedStrategy(embeddedMetadata, entity); - if (embeddedEntityBuilder != null) { - entityBuilder.set(embeddedMetadata.getMappedName(), embeddedEntityBuilder.build()); - } - } - } - - } - - /** - * Marshals an embedded field represented by the given metadata. - * - * @param embeddedMetadata - * the metadata of the embedded field - * @param target - * the target object to which the embedded object belongs - */ - private void marshalWithExplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) { - try { - Object embeddedObject = initializeEmbedded(embeddedMetadata, target); - for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { - marshalField(propertyMetadata, embeddedObject); - } - for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { - marshalWithExplodedStrategy(embeddedMetadata2, embeddedObject); - } - } catch (Throwable t) { - throw new EntityManagerException(t); - } - } - - /** - * Marshals the embedded field represented by the given metadata. - * - * @param embeddedMetadata - * the metadata of the embedded field. - * @param target - * the object in which the embedded field is defined/accessible - * from. - * @return the ValueBuilder equivalent to embedded object - */ - private ValueBuilder marshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) { - try { - Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); - if (embeddedObject == null) { - if (embeddedMetadata.isOptional()) { - return null; - } - NullValue.Builder nullValueBuilder = NullValue.newBuilder(); - nullValueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); - return nullValueBuilder; - } - FullEntity.Builder embeddedEntityBuilder = FullEntity.newBuilder(); - for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { - marshalField(propertyMetadata, embeddedObject, embeddedEntityBuilder); - } - for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { - ValueBuilder embeddedEntityBuilder2 = marshalWithImplodedStrategy(embeddedMetadata2, - embeddedObject); - if (embeddedEntityBuilder2 != null) { - embeddedEntityBuilder.set(embeddedMetadata2.getMappedName(), embeddedEntityBuilder2.build()); - } - } - EntityValue.Builder valueBuilder = EntityValue.newBuilder(embeddedEntityBuilder.build()); - valueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); - return valueBuilder; - - } catch (Throwable t) { - throw new EntityManagerException(t); - } - - } - - /** - * Marshals the the automatic timestamp fields, if any. - */ - private void marshalAutoTimestampFields() { - switch (intent) { - case UPDATE: - case UPSERT: - case BATCH_UPDATE: - marshalUpdatedTimestamp(); - break; - case INSERT: - marshalCreatedAndUpdatedTimestamp(); - break; - default: - break; - } - } - - /** - * Marshals the updated timestamp field. - */ - private void marshalUpdatedTimestamp() { - PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata(); - if (updatedTimestampMetadata != null) { - applyAutoTimestamp(updatedTimestampMetadata, System.currentTimeMillis()); - } - } - - /** - * Marshals both created and updated timestamp fields. - */ - private void marshalCreatedAndUpdatedTimestamp() { - PropertyMetadata createdTimestampMetadata = entityMetadata.getCreatedTimestampMetadata(); - PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata(); - long millis = System.currentTimeMillis(); - if (createdTimestampMetadata != null) { - applyAutoTimestamp(createdTimestampMetadata, millis); - } - if (updatedTimestampMetadata != null) { - applyAutoTimestamp(updatedTimestampMetadata, millis); - } - } - - /** - * Applies the given time, millis, to the property represented - * by the given metadata. - * - * @param propertyMetadata - * the property metadata of the field - * @param millis - * the time in milliseconds - */ - private void applyAutoTimestamp(PropertyMetadata propertyMetadata, long millis) { - Object timestamp = null; - Class fieldType = propertyMetadata.getDeclaredType(); - if (Date.class.equals(fieldType)) { - timestamp = new Date(millis); - } else if (Calendar.class.equals(fieldType)) { - Calendar calendar = new Calendar.Builder().setInstant(millis).build(); - timestamp = calendar; - } else if (Long.class.equals(fieldType) || long.class.equals(fieldType)) { - timestamp = millis; - } else if (OffsetDateTime.class.equals(fieldType)) { - timestamp = OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); - } else if (ZonedDateTime.class.equals(fieldType)) { - timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); - } - ValueBuilder valueBuilder = propertyMetadata.getMapper().toDatastore(timestamp); - valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); - entityBuilder.set(propertyMetadata.getMappedName(), valueBuilder.build()); - } - - /** - * Marshals the version field, if it exists. The version will be set to one - * more than the previous value. - */ - private void marshalVersionField() { - PropertyMetadata versionMetadata = entityMetadata.getVersionMetadata(); - if (versionMetadata != null) { - long version = (long) IntrospectionUtils.getFieldValue(versionMetadata, entity); - ValueBuilder valueBuilder = versionMetadata.getMapper().toDatastore(version + 1); - valueBuilder.setExcludeFromIndexes(!versionMetadata.isIndexed()); - entityBuilder.set(versionMetadata.getMappedName(), valueBuilder.build()); - } - } - - /** - * Initializes the Embedded object represented by the given metadata. - * - * @param embeddedMetadata - * the metadata of the embedded field - * @param target - * the object in which the embedded field is declared/accessible - * from - * @return the initialized object - * @throws EntityManagerException - * if any error occurs during initialization of the embedded - * object - */ - private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { - try { - // If instantiation of Entity instantiated the embeddable, we will - // use the pre-initialized embedded object. - Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); - if (embeddedObject == null) { - // Otherwise, we will instantiate the embedded object, which - // could be a Builder - embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); - ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); - if (constructorMetadata.isBuilderConstructionStrategy()) { - // Build the Builder - embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); - } else { - // TODO we should not be doing this?? There is no equivalent - // of this for builder pattern - embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); - } - } - return embeddedObject; - } catch (Throwable t) { - throw new EntityManagerException(t); - } - } + /** + * The intent of marshalling an object. The marshalling may be different depending on the intended + * purpose. For example, if marshalling an object for UPDATE operation, the marshaller does not + * automatically generate a key. + * + * @author Sai Pullabhotla + * + */ + public enum Intent { + /** + * Insert + */ + INSERT(false, false), + + /** + * Update + */ + UPDATE(true, false), + + /** + * Upsert (Update or Insert) + */ + UPSERT(false, false), + + /** + * Delete + */ + DELETE(true, true), + + /** + * Batch Update + */ + BATCH_UPDATE(true, false); + + /** + * If a complete key is required for this Intent + */ + private boolean keyRequired; + + /** + * If this Intent (or operation) is valid on projected entities + */ + private boolean validOnProjectedEntities; + + /** + * Creates a new instance of Intent. + * + * @param keyRequired + * whether or not a complete key is required. + * @param validOnProjectedEntities + * whether or not this intent is valid on projected entities + */ + private Intent(boolean keyRequired, boolean validOnProjectedEntities) { + this.keyRequired = keyRequired; + this.validOnProjectedEntities = validOnProjectedEntities; + } + + /** + * Tells whether or not a complete key is required for this Intent. + * + * @return true, if a complete key is required; false, otherwise. + */ + public boolean isKeyRequired() { + return keyRequired; + } + + /** + * Tells whether or not this intent is valid on projected entities. + * + * @return true, if this intent is valid/supported on projected entities; + * false, otherwise. + */ + public boolean isValidOnProjectedEntities() { + return validOnProjectedEntities; + } + + } + + /** + * Reference to the EntityManager + */ + private DefaultEntityManager entityManager; + + /** + * Entity being marshaled + */ + private final Object entity; + + /** + * Metadata of the entity being marshaled + */ + private final EntityMetadata entityMetadata; + + /** + * Builder for building the Entity needed for Cloud Datastore + */ + private BaseEntity.Builder entityBuilder; + + /** + * Key + */ + private IncompleteKey key; + + /** + * The intent of marshalling + */ + private final Intent intent; + + /** + * Creates a new instance of Marshaller. + * + * @param entityManager + * reference to the entity manager + * @param entity + * the Entity to marshal + * @param intent + * the intent of marshalling + */ + private Marshaller(DefaultEntityManager entityManager, Object entity, Intent intent) { + this.entityManager = entityManager; + this.entity = entity; + this.intent = intent; + entityMetadata = EntityIntrospector.introspect(entity.getClass()); + validateIntent(); + } + + /** + * Validates if the Intent is legal for the entity being marshalled. + * + * @throws EntityManagerException + * if the Intent is not valid for the entity being marshalled + */ + private void validateIntent() { + if (entityMetadata.isProjectedEntity() && !intent.isValidOnProjectedEntities()) { + String message = String.format("Operation %s is not allowed for ProjectedEntity %s", intent, + entity.getClass().getName()); + throw new EntityManagerException(message); + } + } + + /** + * Marshals the given entity (POJO) into the format needed for the low level Cloud Datastore API. + * + * @param entityManager + * the entity manager + * @param entity + * the entity to marshal + * @param intent + * the intent or purpose of marshalling. Marshalling process varies slightly depending on + * the purpose. For example, if the purpose if INSERT or UPSERT, the marshaller would + * auto generate any keys. Where as if the purpose is UPDATE, then then marshaller will + * NOT generate any keys. + * @return the marshaled object + */ + @SuppressWarnings("rawtypes") + public static BaseEntity marshal(DefaultEntityManager entityManager, Object entity, + Intent intent) { + Marshaller marshaller = new Marshaller(entityManager, entity, intent); + return marshaller.marshal(); + } + + /** + * Marshals the given entity and and returns the equivalent Entity needed for the underlying Cloud + * Datastore API. + * + * @return A native entity that is equivalent to the POJO being marshalled. The returned value + * could either be a FullEntity or Entity. + */ + private BaseEntity marshal() { + marshalKey(); + if (key instanceof Key) { + entityBuilder = Entity.newBuilder((Key) key); + } else { + entityBuilder = FullEntity.newBuilder(key); + } + marshalFields(); + marshalAutoTimestampFields(); + if (intent == Intent.UPDATE) { + marshalVersionField(); + } + marshalEmbeddedFields(); + return entityBuilder.build(); + } + + /** + * Extracts the key from the given object, entity, and returns it. The entity must have its ID + * set. + * + * @param entityManager + * the entity manager. + * @param entity + * the entity from which key is to be extracted + * @return extracted key. + */ + public static Key marshalKey(DefaultEntityManager entityManager, Object entity) { + Marshaller marshaller = new Marshaller(entityManager, entity, Intent.DELETE); + marshaller.marshalKey(); + return (Key) marshaller.key; + } + + /** + * Marshals the key. + */ + private void marshalKey() { + + Key parent = null; + + ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); + if (parentKeyMetadata != null) { + DatastoreKey parentDatastoreKey = (DatastoreKey) getFieldValue(parentKeyMetadata); + if (parentDatastoreKey != null) { + parent = parentDatastoreKey.nativeKey(); + } + } + + IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); + IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); + DataType identifierType = identifierMetadata.getDataType(); + Object idValue = getFieldValue(identifierMetadata); + + // If ID value is null, we don't have to worry about if it is a simple + // type of a complex type. Otherwise, we need to see if the ID is a + // complex type, and if it is, extract the real ID. + if (idValue != null && idClassMetadata != null) { + try { + idValue = idClassMetadata.getReadMethod().invoke(idValue); + } catch (Throwable t) { + throw new EntityManagerException(t); + } + } + + boolean validId = isValidId(idValue, identifierType); + boolean autoGenerateId = identifierMetadata.isAutoGenerated(); + + if (validId) { + if (identifierType == DataType.STRING) { + createCompleteKey(parent, (String) idValue); + } else { + createCompleteKey(parent, (long) idValue); + } + } else { + if (intent.isKeyRequired()) { + throw new EntityManagerException(String + .format("Identifier is not set or valid for entity of type %s", entity.getClass())); + } + if (!autoGenerateId) { + String pattern = "Identifier is not set or valid for entity of type %s. Auto generation " + + "of ID is explicitly turned off. "; + throw new EntityManagerException(String.format(pattern, entity.getClass())); + } else { + if (identifierType == DataType.STRING) { + createCompleteKey(parent); + } else { + createIncompleteKey(parent); + } + } + } + } + + /** + * Checks to see if the given value is a valid identifier for the given ID type. + * + * @param idValue + * the ID value + * @param identifierType + * the identifier type + * @return true, if the given value is a valid identifier; false, + * otherwise. For STRING type, the ID is valid if it it contains at least one printable + * character. In other words, if ((String) idValue).trim().length() > 0. For numeric + * types, the ID is valid if it is not null or zero. + */ + private static boolean isValidId(Object idValue, DataType identifierType) { + boolean validId = false; + if (idValue != null) { + switch (identifierType) { + case LONG: + case LONG_OBJECT: + validId = (long) idValue != 0; + break; + case STRING: + validId = ((String) idValue).trim().length() > 0; + break; + default: + // we should never get here + break; + } + } + return validId; + } + + /** + * Creates a complete key using the given parameters. + * + * @param parent + * the parent key, may be null. + * @param id + * the numeric ID + */ + private void createCompleteKey(Key parent, long id) { + String kind = entityMetadata.getKind(); + if (parent == null) { + key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); + } else { + key = Key.newBuilder(parent, kind, id).build(); + } + } + + /** + * Creates a complete key using the given parameters. + * + * @param parent + * the parent key, may be null. + * @param id + * the String ID + */ + private void createCompleteKey(Key parent, String id) { + String kind = entityMetadata.getKind(); + if (parent == null) { + key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); + } else { + key = Key.newBuilder(parent, kind, id).build(); + } + } + + /** + * Creates a CompleteKey using the given parameters. The actual ID is generated using + * UUID.randomUUID().toString(). + * + * @param parent + * the parent key, may be null. + */ + private void createCompleteKey(Key parent) { + String kind = entityMetadata.getKind(); + String id = UUID.randomUUID().toString(); + if (parent == null) { + key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id); + } else { + key = Key.newBuilder(parent, kind, id).build(); + } + } + + /** + * Creates an IncompleteKey. + * + * @param parent + * the parent key, may be null. + */ + private void createIncompleteKey(Key parent) { + String kind = entityMetadata.getKind(); + if (parent == null) { + key = entityManager.newNativeKeyFactory().setKind(kind).newKey(); + } else { + key = IncompleteKey.newBuilder(parent, kind).build(); + } + } + + /** + * Marshals all the fields. + */ + private void marshalFields() { + Collection propertyMetadataCollection = entityMetadata + .getPropertyMetadataCollection(); + for (PropertyMetadata propertyMetadata : propertyMetadataCollection) { + marshalField(propertyMetadata, entity); + } + } + + /** + * Marshals the field with the given property metadata. + * + * @param propertyMetadata + * the metadata of the field to be marshaled. + * @param target + * the object in which the field is defined/accessible from. + */ + private void marshalField(PropertyMetadata propertyMetadata, Object target) { + marshalField(propertyMetadata, target, entityBuilder); + } + + /** + * Marshals the field with the given property metadata. + * + * @param propertyMetadata + * the metadata of the field to be marshaled. + * @param target + * the object in which the field is defined/accessible from + * @param entityBuilder + * the native entity on which the marshaled field should be set + */ + private static void marshalField(PropertyMetadata propertyMetadata, Object target, + BaseEntity.Builder entityBuilder) { + Object fieldValue = IntrospectionUtils.getFieldValue(propertyMetadata, target); + if (fieldValue == null && propertyMetadata.isOptional()) { + return; + } + ValueBuilder valueBuilder = propertyMetadata.getMapper().toDatastore(fieldValue); + // ListValues cannot have indexing turned off. Indexing is turned on by + // default, so we don't touch excludeFromIndexes for ListValues. + if (valueBuilder.getValueType() != ValueType.LIST) { + valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); + } + Value datastoreValue = valueBuilder.build(); + entityBuilder.set(propertyMetadata.getMappedName(), datastoreValue); + Indexer indexer = propertyMetadata.getSecondaryIndexer(); + if (indexer != null) { + entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(datastoreValue)); + } + } + + /** + * Returns the value for the given field of the entity being marshaled. + * + * @param fieldMetadata + * the field's metadata + * @return the field's value + */ + private Object getFieldValue(FieldMetadata fieldMetadata) { + return IntrospectionUtils.getFieldValue(fieldMetadata, entity); + } + + /** + * Marshals the embedded fields. + */ + private void marshalEmbeddedFields() { + for (EmbeddedMetadata embeddedMetadata : entityMetadata.getEmbeddedMetadataCollection()) { + if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { + marshalWithExplodedStrategy(embeddedMetadata, entity); + } else { + ValueBuilder embeddedEntityBuilder = marshalWithImplodedStrategy(embeddedMetadata, + entity); + if (embeddedEntityBuilder != null) { + entityBuilder.set(embeddedMetadata.getMappedName(), embeddedEntityBuilder.build()); + } + } + } + + } + + /** + * Marshals an embedded field represented by the given metadata. + * + * @param embeddedMetadata + * the metadata of the embedded field + * @param target + * the target object to which the embedded object belongs + */ + private void marshalWithExplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) { + try { + Object embeddedObject = initializeEmbedded(embeddedMetadata, target); + for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { + marshalField(propertyMetadata, embeddedObject); + } + for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { + marshalWithExplodedStrategy(embeddedMetadata2, embeddedObject); + } + } catch (Throwable t) { + throw new EntityManagerException(t); + } + } + + /** + * Marshals the embedded field represented by the given metadata. + * + * @param embeddedMetadata + * the metadata of the embedded field. + * @param target + * the object in which the embedded field is defined/accessible from. + * @return the ValueBuilder equivalent to embedded object + */ + private ValueBuilder marshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata, + Object target) { + try { + Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); + if (embeddedObject == null) { + if (embeddedMetadata.isOptional()) { + return null; + } + NullValue.Builder nullValueBuilder = NullValue.newBuilder(); + nullValueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); + return nullValueBuilder; + } + FullEntity.Builder embeddedEntityBuilder = FullEntity.newBuilder(); + for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { + marshalField(propertyMetadata, embeddedObject, embeddedEntityBuilder); + } + for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { + ValueBuilder embeddedEntityBuilder2 = marshalWithImplodedStrategy( + embeddedMetadata2, embeddedObject); + if (embeddedEntityBuilder2 != null) { + embeddedEntityBuilder.set(embeddedMetadata2.getMappedName(), + embeddedEntityBuilder2.build()); + } + } + EntityValue.Builder valueBuilder = EntityValue.newBuilder(embeddedEntityBuilder.build()); + valueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); + return valueBuilder; + + } catch (Throwable t) { + throw new EntityManagerException(t); + } + + } + + /** + * Marshals the the automatic timestamp fields, if any. + */ + private void marshalAutoTimestampFields() { + switch (intent) { + case UPDATE: + case UPSERT: + case BATCH_UPDATE: + marshalUpdatedTimestamp(); + break; + case INSERT: + marshalCreatedAndUpdatedTimestamp(); + break; + default: + break; + } + } + + /** + * Marshals the updated timestamp field. + */ + private void marshalUpdatedTimestamp() { + PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata(); + if (updatedTimestampMetadata != null) { + applyAutoTimestamp(updatedTimestampMetadata, System.currentTimeMillis()); + } + } + + /** + * Marshals both created and updated timestamp fields. + */ + private void marshalCreatedAndUpdatedTimestamp() { + PropertyMetadata createdTimestampMetadata = entityMetadata.getCreatedTimestampMetadata(); + PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata(); + long millis = System.currentTimeMillis(); + if (createdTimestampMetadata != null) { + applyAutoTimestamp(createdTimestampMetadata, millis); + } + if (updatedTimestampMetadata != null) { + applyAutoTimestamp(updatedTimestampMetadata, millis); + } + } + + /** + * Applies the given time, millis, to the property represented by the given metadata. + * + * @param propertyMetadata + * the property metadata of the field + * @param millis + * the time in milliseconds + */ + private void applyAutoTimestamp(PropertyMetadata propertyMetadata, long millis) { + Object timestamp = null; + Class fieldType = propertyMetadata.getDeclaredType(); + if (Date.class.equals(fieldType)) { + timestamp = new Date(millis); + } else if (Calendar.class.equals(fieldType)) { + Calendar calendar = new Calendar.Builder().setInstant(millis).build(); + timestamp = calendar; + } else if (Long.class.equals(fieldType) || long.class.equals(fieldType)) { + timestamp = millis; + } else if (OffsetDateTime.class.equals(fieldType)) { + timestamp = OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); + } else if (ZonedDateTime.class.equals(fieldType)) { + timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); + } + ValueBuilder valueBuilder = propertyMetadata.getMapper().toDatastore(timestamp); + valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); + entityBuilder.set(propertyMetadata.getMappedName(), valueBuilder.build()); + } + + /** + * Marshals the version field, if it exists. The version will be set to one more than the previous + * value. + */ + private void marshalVersionField() { + PropertyMetadata versionMetadata = entityMetadata.getVersionMetadata(); + if (versionMetadata != null) { + long version = (long) IntrospectionUtils.getFieldValue(versionMetadata, entity); + ValueBuilder valueBuilder = versionMetadata.getMapper().toDatastore(version + 1); + valueBuilder.setExcludeFromIndexes(!versionMetadata.isIndexed()); + entityBuilder.set(versionMetadata.getMappedName(), valueBuilder.build()); + } + } + + /** + * Initializes the Embedded object represented by the given metadata. + * + * @param embeddedMetadata + * the metadata of the embedded field + * @param target + * the object in which the embedded field is declared/accessible from + * @return the initialized object + * @throws EntityManagerException + * if any error occurs during initialization of the embedded object + */ + private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { + try { + // If instantiation of Entity instantiated the embeddable, we will + // use the pre-initialized embedded object. + Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); + if (embeddedObject == null) { + // Otherwise, we will instantiate the embedded object, which + // could be a Builder + embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); + ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); + if (constructorMetadata.isBuilderConstructionStrategy()) { + // Build the Builder + embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); + } else { + // TODO we should not be doing this?? There is no equivalent + // of this for builder pattern + embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); + } + } + return embeddedObject; + } catch (Throwable t) { + throw new EntityManagerException(t); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/MetadataBase.java b/src/main/java/com/jmethods/catatumbo/impl/MetadataBase.java index 8fd56bc..209f5b8 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/MetadataBase.java +++ b/src/main/java/com/jmethods/catatumbo/impl/MetadataBase.java @@ -30,132 +30,132 @@ */ public abstract class MetadataBase { - /** - * The class - */ - protected final Class clazz; - - /** - * Metadata about various properties. The keys of this map are the property - * names in the Cloud Datastore. - */ - protected Map propertyMetadataMap; - - /** - * Metadata of embedded fields - */ - protected Map embeddedMetadataMap = null; - - /** - * Constructor metadata - */ - private final ConstructorMetadata constructorMetadata; - - /** - * Creates a new instance of MetadataBase. - * - * @param clazz - * the class to which this metadata belongs (either an Entity or - * an Embeddable) - */ - public MetadataBase(Class clazz) { - this.clazz = clazz; - propertyMetadataMap = new HashMap<>(); - embeddedMetadataMap = new HashMap<>(); - this.constructorMetadata = ConstructorIntrospector.introspect(clazz); - } - - /** - * Returns the class object to which this metadata belongs. - * - * @return the class object to which this metadata belongs. - */ - public Class getClazz() { - return clazz; - } - - /** - * Returns the {@link ConstructorMetadata} of the persistence class to which - * this metadata belongs. - * - * @return the constructorMetadata the {@link ConstructorMetadata} of the - * persistence class to which this metadata belongs. - */ - public ConstructorMetadata getConstructorMetadata() { - return constructorMetadata; - } - - /** - * Puts/adds the given property metadata. - * - * @param propertyMetadata - * the property metadata - */ - public void putPropertyMetadata(PropertyMetadata propertyMetadata) { - String mappedName = propertyMetadata.getMappedName(); - PropertyMetadata old = propertyMetadataMap.put(mappedName, propertyMetadata); - if (old != null) { - String format = "Class %s has two fields, %s and %s, both mapped to the same property name, %s"; - String message = String.format(format, clazz.getName(), old.getName(), propertyMetadata.getName(), - mappedName); - throw new EntityManagerException(message); - } - } - - /** - * Returns the property metadata for the given property name. The property - * name is the name used in the Cloud Datastore. - * - * @param mappedName - * the property name in the Cloud Datastore - * @return the property metadata - */ - public PropertyMetadata getPropertyMetadata(String mappedName) { - return propertyMetadataMap.get(mappedName); - } - - /** - * Returns the collection of PropertyMetadata. - * - * @return the collection of property metadata. - */ - public Collection getPropertyMetadataCollection() { - return propertyMetadataMap.values(); - } - - /** - * Returns a map of property names and their metadata. - * - * @return a map of property names and their metadata. - */ - public Map getPropertyMetadataMap() { - return propertyMetadataMap; - } - - /** - * Puts/adds the given embedded metadata. - * - * @param embeddedMetadata - * the embedded metadata. - */ - public void putEmbeddedMetadata(EmbeddedMetadata embeddedMetadata) { - embeddedMetadataMap.put(embeddedMetadata.getField(), embeddedMetadata); - } - - /** - * Returns a collection of the embedded metadata. - * - * @return a collection of the embedded metadata. - */ - public Collection getEmbeddedMetadataCollection() { - return embeddedMetadataMap.values(); - } - - /** - * @return the embeddedMetadataMap - */ - public Map getEmbeddedMetadataMap() { - return embeddedMetadataMap; - } + /** + * The class + */ + protected final Class clazz; + + /** + * Metadata about various properties. The keys of this map are the property names in the Cloud + * Datastore. + */ + protected Map propertyMetadataMap; + + /** + * Metadata of embedded fields + */ + protected Map embeddedMetadataMap = null; + + /** + * Constructor metadata + */ + private final ConstructorMetadata constructorMetadata; + + /** + * Creates a new instance of MetadataBase. + * + * @param clazz + * the class to which this metadata belongs (either an Entity or an Embeddable) + */ + public MetadataBase(Class clazz) { + this.clazz = clazz; + propertyMetadataMap = new HashMap<>(); + embeddedMetadataMap = new HashMap<>(); + this.constructorMetadata = ConstructorIntrospector.introspect(clazz); + } + + /** + * Returns the class object to which this metadata belongs. + * + * @return the class object to which this metadata belongs. + */ + public Class getClazz() { + return clazz; + } + + /** + * Returns the {@link ConstructorMetadata} of the persistence class to which this metadata + * belongs. + * + * @return the constructorMetadata the {@link ConstructorMetadata} of the persistence class to + * which this metadata belongs. + */ + public ConstructorMetadata getConstructorMetadata() { + return constructorMetadata; + } + + /** + * Puts/adds the given property metadata. + * + * @param propertyMetadata + * the property metadata + */ + public void putPropertyMetadata(PropertyMetadata propertyMetadata) { + String mappedName = propertyMetadata.getMappedName(); + PropertyMetadata old = propertyMetadataMap.put(mappedName, propertyMetadata); + if (old != null) { + String format = "Class %s has two fields, %s and %s, both mapped to the same property " + + "name, %s"; + String message = String.format(format, clazz.getName(), old.getName(), + propertyMetadata.getName(), mappedName); + throw new EntityManagerException(message); + } + } + + /** + * Returns the property metadata for the given property name. The property name is the name used + * in the Cloud Datastore. + * + * @param mappedName + * the property name in the Cloud Datastore + * @return the property metadata + */ + public PropertyMetadata getPropertyMetadata(String mappedName) { + return propertyMetadataMap.get(mappedName); + } + + /** + * Returns the collection of PropertyMetadata. + * + * @return the collection of property metadata. + */ + public Collection getPropertyMetadataCollection() { + return propertyMetadataMap.values(); + } + + /** + * Returns a map of property names and their metadata. + * + * @return a map of property names and their metadata. + */ + public Map getPropertyMetadataMap() { + return propertyMetadataMap; + } + + /** + * Puts/adds the given embedded metadata. + * + * @param embeddedMetadata + * the embedded metadata. + */ + public void putEmbeddedMetadata(EmbeddedMetadata embeddedMetadata) { + embeddedMetadataMap.put(embeddedMetadata.getField(), embeddedMetadata); + } + + /** + * Returns a collection of the embedded metadata. + * + * @return a collection of the embedded metadata. + */ + public Collection getEmbeddedMetadataCollection() { + return embeddedMetadataMap.values(); + } + + /** + * @return the embeddedMetadataMap + */ + public Map getEmbeddedMetadataMap() { + return embeddedMetadataMap; + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/ParentKeyMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/ParentKeyMetadata.java index 5febbd5..130b371 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/ParentKeyMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/ParentKeyMetadata.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Field; @@ -24,14 +25,14 @@ */ public class ParentKeyMetadata extends KeyMetadata { - /** - * Creates a new instance of ParentKeyMetadata. - * - * @param field - * the field - */ - public ParentKeyMetadata(Field field) { - super(field); - } + /** + * Creates a new instance of ParentKeyMetadata. + * + * @param field + * the field + */ + public ParentKeyMetadata(Field field) { + super(field); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/PropertyMetadata.java b/src/main/java/com/jmethods/catatumbo/impl/PropertyMetadata.java index 3935d44..ab8d980 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/PropertyMetadata.java +++ b/src/main/java/com/jmethods/catatumbo/impl/PropertyMetadata.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.reflect.Field; @@ -37,221 +38,219 @@ */ public class PropertyMetadata extends FieldMetadata { - /** - * Default prefix for secondary index name. - */ - private static final String DEFAULT_SECONDARY_INDEX_PREFIX = "$"; + /** + * Default prefix for secondary index name. + */ + private static final String DEFAULT_SECONDARY_INDEX_PREFIX = "$"; - /** - * The property name, in the Cloud Datastore, to which a field is mapped - */ - private String mappedName; + /** + * The property name, in the Cloud Datastore, to which a field is mapped + */ + private String mappedName; - /** - * If the property is indexed or not - */ - private boolean indexed; + /** + * If the property is indexed or not + */ + private boolean indexed; - /** - * If this property is optional - */ - protected boolean optional; + /** + * If this property is optional + */ + protected boolean optional; - /** - * Secondary indexer for this property - */ - private Indexer secondaryIndexer; + /** + * Secondary indexer for this property + */ + private Indexer secondaryIndexer; - /** - * Secondary index name - */ - private String secondaryIndexName; + /** + * Secondary index name + */ + private String secondaryIndexName; - /** - * Mapper for the field represented by this metadata - */ - protected final Mapper mapper; + /** + * Mapper for the field represented by this metadata + */ + protected final Mapper mapper; - /** - * Creates an instance of PropertyMetadata. - * - * @param field - * the field - */ - public PropertyMetadata(Field field) { - super(field); - String mappedName = field.getName(); - boolean indexed = true; - boolean optional = false; - Property propertyAnnotation = field.getAnnotation(Property.class); - if (propertyAnnotation != null) { - String temp = propertyAnnotation.name(); - if (!Utility.isNullOrEmpty(temp)) { - mappedName = temp; - } - indexed = propertyAnnotation.indexed(); - optional = propertyAnnotation.optional(); - } - this.mappedName = mappedName; - this.indexed = indexed; - setOptional(optional); - initializeSecondaryIndexer(); - this.mapper = initializeMapper(); - } + /** + * Creates an instance of PropertyMetadata. + * + * @param field + * the field + */ + public PropertyMetadata(Field field) { + super(field); + String mappedName = field.getName(); + boolean indexed = true; + boolean optional = false; + Property propertyAnnotation = field.getAnnotation(Property.class); + if (propertyAnnotation != null) { + String temp = propertyAnnotation.name(); + if (!Utility.isNullOrEmpty(temp)) { + mappedName = temp; + } + indexed = propertyAnnotation.indexed(); + optional = propertyAnnotation.optional(); + } + this.mappedName = mappedName; + this.indexed = indexed; + setOptional(optional); + initializeSecondaryIndexer(); + this.mapper = initializeMapper(); + } - /** - * Creates a new instance of PropertyMetadata. - * - * @param field - * the field - * @param mappedName - * name of the property in the Datastore - * @param indexed - * whether or not the property is indexed - * @param optional - * whether or not the property is optional - */ - public PropertyMetadata(Field field, String mappedName, boolean indexed, boolean optional) { - super(field); - this.mappedName = mappedName; - this.indexed = indexed; - setOptional(optional); - initializeSecondaryIndexer(); - this.mapper = initializeMapper(); - } + /** + * Creates a new instance of PropertyMetadata. + * + * @param field + * the field + * @param mappedName + * name of the property in the Datastore + * @param indexed + * whether or not the property is indexed + * @param optional + * whether or not the property is optional + */ + public PropertyMetadata(Field field, String mappedName, boolean indexed, boolean optional) { + super(field); + this.mappedName = mappedName; + this.indexed = indexed; + setOptional(optional); + initializeSecondaryIndexer(); + this.mapper = initializeMapper(); + } - /** - * Returns the mapped name. - * - * @return the mapped name. - */ - public String getMappedName() { - return mappedName; - } + /** + * Returns the mapped name. + * + * @return the mapped name. + */ + public String getMappedName() { + return mappedName; + } - /** - * Sets the mapped name. - * - * @param mappedName - * the mapped name. - */ - public void setMappedName(String mappedName) { - this.mappedName = mappedName; - } + /** + * Sets the mapped name. + * + * @param mappedName + * the mapped name. + */ + public void setMappedName(String mappedName) { + this.mappedName = mappedName; + } - /** - * Returns whether or not the property is indexed. - * - * @return true, if indexed; false, otherwise. - */ - public boolean isIndexed() { - return indexed; - } + /** + * Returns whether or not the property is indexed. + * + * @return true, if indexed; false, otherwise. + */ + public boolean isIndexed() { + return indexed; + } - /** - * Sets whether or not the property is indexed. - * - * @param indexed - * whether or not the property is indexed. - */ - public void setIndexed(boolean indexed) { - this.indexed = indexed; - } + /** + * Sets whether or not the property is indexed. + * + * @param indexed + * whether or not the property is indexed. + */ + public void setIndexed(boolean indexed) { + this.indexed = indexed; + } - /** - * Returns the secondary indexer associated with this property, if any. - * - * @return the secondaryIndexer the secondary indexer associated with this - * property. May be null. - */ - public Indexer getSecondaryIndexer() { - return secondaryIndexer; - } + /** + * Returns the secondary indexer associated with this property, if any. + * + * @return the secondaryIndexer the secondary indexer associated with this property. May be + * null. + */ + public Indexer getSecondaryIndexer() { + return secondaryIndexer; + } - /** - * Returns the secondary index name, if any. - * - * @return the secondary index name. May be null. - */ - public String getSecondaryIndexName() { - return secondaryIndexName; - } + /** + * Returns the secondary index name, if any. + * + * @return the secondary index name. May be null. + */ + public String getSecondaryIndexName() { + return secondaryIndexName; + } - /** - * Tells whether or not the field represented by this metadata is optional. - * - * @return true, if the field represented by this metadata is - * optional; false, otherwise. - */ - public boolean isOptional() { - return optional; - } + /** + * Tells whether or not the field represented by this metadata is optional. + * + * @return true, if the field represented by this metadata is optional; + * false, otherwise. + */ + public boolean isOptional() { + return optional; + } - /** - * Sets whether or not the field represented by this metadata is optional. - * - * @param optional - * whether or not the field represented by this metadata is - * optional. - */ - public void setOptional(boolean optional) { - if (optional) { - if (field.getType().isPrimitive() || field.isAnnotationPresent(Version.class) - || field.isAnnotationPresent(CreatedTimestamp.class) - || field.isAnnotationPresent(UpdatedTimestamp.class)) { - optional = false; - } - } - this.optional = optional; - } + /** + * Sets whether or not the field represented by this metadata is optional. + * + * @param optional + * whether or not the field represented by this metadata is optional. + */ + public void setOptional(boolean optional) { + if (field.getType().isPrimitive() || field.isAnnotationPresent(Version.class) + || field.isAnnotationPresent(CreatedTimestamp.class) + || field.isAnnotationPresent(UpdatedTimestamp.class)) { + this.optional = false; + } else { + this.optional = optional; + } + } - /** - * Initializes the secondary indexer for this property, if any. - */ - private void initializeSecondaryIndexer() { - SecondaryIndex secondaryIndexAnnotation = field.getAnnotation(SecondaryIndex.class); - if (secondaryIndexAnnotation == null) { - return; - } - String indexName = secondaryIndexAnnotation.name(); - if (indexName == null || indexName.trim().length() == 0) { - indexName = DEFAULT_SECONDARY_INDEX_PREFIX + mappedName; - } - this.secondaryIndexName = indexName; - try { - secondaryIndexer = IndexerFactory.getInstance().getIndexer(field); - } catch (Exception exp) { - String message = String.format( - "No suitable Indexer found or error occurred while creating the indexer for field %s in class %s", - field.getName(), field.getDeclaringClass().getName()); - throw new EntityManagerException(message, exp); - } + /** + * Initializes the secondary indexer for this property, if any. + */ + private void initializeSecondaryIndexer() { + SecondaryIndex secondaryIndexAnnotation = field.getAnnotation(SecondaryIndex.class); + if (secondaryIndexAnnotation == null) { + return; + } + String indexName = secondaryIndexAnnotation.name(); + if (indexName == null || indexName.trim().length() == 0) { + indexName = DEFAULT_SECONDARY_INDEX_PREFIX + mappedName; + } + this.secondaryIndexName = indexName; + try { + secondaryIndexer = IndexerFactory.getInstance().getIndexer(field); + } catch (Exception exp) { + String pattern = "No suitable Indexer found or error occurred while creating the indexer " + + "for field %s in class %s"; + String message = String.format(pattern, field.getName(), field.getDeclaringClass().getName()); + throw new EntityManagerException(message, exp); + } - } + } - /** - * Returns the {@link Mapper} associated with the field to which this - * metadata belongs. - * - * @return he {@link Mapper} associated with the field to which this - * metadata belongs. - */ - public Mapper getMapper() { - return mapper; - } + /** + * Returns the {@link Mapper} associated with the field to which this metadata belongs. + * + * @return he {@link Mapper} associated with the field to which this metadata belongs. + */ + public Mapper getMapper() { + return mapper; + } - /** - * Initializes the {@link Mapper} for this field. - */ - private Mapper initializeMapper() { - try { - return MapperFactory.getInstance().getMapper(field); - } catch (NoSuitableMapperException exp) { - String message = String.format( - "No suitable mapper found or error occurred creating a mapper for field %s in class %s", - field.getName(), field.getDeclaringClass().getName()); - throw new NoSuitableMapperException(message, exp); - } - } + /** + * Initializes the {@link Mapper} for this field. + * + * @return the {@link Mapper} for the field represented by this metadata + */ + private Mapper initializeMapper() { + try { + return MapperFactory.getInstance().getMapper(field); + } catch (NoSuitableMapperException exp) { + String message = String.format( + "No suitable mapper found or error occurred creating a mapper for field %s in class %s", + field.getName(), field.getDeclaringClass().getName()); + throw new NoSuitableMapperException(message, exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/QueryUtils.java b/src/main/java/com/jmethods/catatumbo/impl/QueryUtils.java index 2aa87b6..0cb6627 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/QueryUtils.java +++ b/src/main/java/com/jmethods/catatumbo/impl/QueryUtils.java @@ -45,203 +45,206 @@ */ public class QueryUtils { - /** - * Hide the default constructor. - */ - private QueryUtils() { - // Do nothing - } + /** + * Hide the default constructor. + */ + private QueryUtils() { + // Do nothing + } - /** - * Applies the given positional bindings to the given query builder. - * - * @param queryBuilder - * the query builder - * @param positionalBindings - * the positional bindings. - */ - static void applyPositionalBindings(GqlQuery.Builder queryBuilder, Object... positionalBindings) { - if (positionalBindings != null) { - for (Object binding : positionalBindings) { - addPositionalBinding(queryBuilder, binding); - } - } - } + /** + * Applies the given positional bindings to the given query builder. + * + * @param queryBuilder + * the query builder + * @param positionalBindings + * the positional bindings. + */ + static void applyPositionalBindings(GqlQuery.Builder queryBuilder, + Object... positionalBindings) { + if (positionalBindings != null) { + for (Object binding : positionalBindings) { + addPositionalBinding(queryBuilder, binding); + } + } + } - /** - * Applies the given positional bindings to the given query builder. - * - * @param queryBuilder - * the query builder - * @param positionalBindings - * the positional bindings. - */ - static void applyPositionalBindings(GqlQuery.Builder queryBuilder, List positionalBindings) { - if (positionalBindings != null) { - for (Object binding : positionalBindings) { - addPositionalBinding(queryBuilder, binding); - } - } - } + /** + * Applies the given positional bindings to the given query builder. + * + * @param queryBuilder + * the query builder + * @param positionalBindings + * the positional bindings. + */ + static void applyPositionalBindings(GqlQuery.Builder queryBuilder, + List positionalBindings) { + if (positionalBindings != null) { + for (Object binding : positionalBindings) { + addPositionalBinding(queryBuilder, binding); + } + } + } - /** - * Adds the given binding to the given query builder's to the list of - * positional bindings. - * - * @param queryBuilder - * the query builder - * @param binding - * the positional binding to add - */ - static void addPositionalBinding(GqlQuery.Builder queryBuilder, Object binding) { - if (binding == null) { - throw new NullPointerException("Binding cannot be null. Use IS NULL in your query"); - } - if (binding instanceof Short) { - queryBuilder.addBinding((short) binding); - } else if (binding instanceof Integer) { - queryBuilder.addBinding((int) binding); - } else if (binding instanceof Long) { - queryBuilder.addBinding((long) binding); - } else if (binding instanceof Float) { - queryBuilder.addBinding((float) binding); - } else if (binding instanceof Double) { - queryBuilder.addBinding((double) binding); - } else if (binding instanceof Boolean) { - queryBuilder.addBinding((boolean) binding); - } else if (binding instanceof Character) { - queryBuilder.addBinding(String.valueOf((char) binding)); - } else if (binding instanceof String) { - queryBuilder.addBinding((String) binding); - } else if (binding instanceof Calendar) { - queryBuilder.addBinding(toTimestamp((Calendar) binding)); - } else if (binding instanceof Date) { - queryBuilder.addBinding(toTimestamp((Date) binding)); - } else if (binding instanceof LocalDate) { - queryBuilder.addBinding(((LocalDate) binding).toString()); - } else if (binding instanceof LocalTime) { - queryBuilder.addBinding(((LocalTime) binding).format(LocalTimeMapper.FORMATTER)); - } else if (binding instanceof LocalDateTime) { - queryBuilder.addBinding(((LocalDateTime) binding).format(LocalDateTimeMapper.FORMATTER)); - } else if (binding instanceof OffsetDateTime) { - queryBuilder.addBinding(toTimestamp((OffsetDateTime) binding)); - } else if (binding instanceof ZonedDateTime) { - queryBuilder.addBinding(toTimestamp((ZonedDateTime) binding)); - } else if (binding instanceof byte[]) { - queryBuilder.addBinding(Blob.copyFrom((byte[]) binding)); - } else if (binding instanceof DatastoreKey) { - queryBuilder.addBinding(((DatastoreKey) binding).nativeKey()); - } else if (binding instanceof DatastoreCursor) { - queryBuilder.addBinding(Cursor.fromUrlSafe(((DatastoreCursor) binding).getEncoded())); - } else if (binding instanceof GeoLocation) { - // TODO no support for GeoLocation in the gcloud API - } - } + /** + * Adds the given binding to the given query builder's to the list of positional bindings. + * + * @param queryBuilder + * the query builder + * @param binding + * the positional binding to add + */ + static void addPositionalBinding(GqlQuery.Builder queryBuilder, Object binding) { + if (binding == null) { + throw new NullPointerException("Binding cannot be null. Use IS NULL in your query"); + } + if (binding instanceof Short) { + queryBuilder.addBinding((short) binding); + } else if (binding instanceof Integer) { + queryBuilder.addBinding((int) binding); + } else if (binding instanceof Long) { + queryBuilder.addBinding((long) binding); + } else if (binding instanceof Float) { + queryBuilder.addBinding((float) binding); + } else if (binding instanceof Double) { + queryBuilder.addBinding((double) binding); + } else if (binding instanceof Boolean) { + queryBuilder.addBinding((boolean) binding); + } else if (binding instanceof Character) { + queryBuilder.addBinding(String.valueOf((char) binding)); + } else if (binding instanceof String) { + queryBuilder.addBinding((String) binding); + } else if (binding instanceof Calendar) { + queryBuilder.addBinding(toTimestamp((Calendar) binding)); + } else if (binding instanceof Date) { + queryBuilder.addBinding(toTimestamp((Date) binding)); + } else if (binding instanceof LocalDate) { + queryBuilder.addBinding(((LocalDate) binding).toString()); + } else if (binding instanceof LocalTime) { + queryBuilder.addBinding(((LocalTime) binding).format(LocalTimeMapper.FORMATTER)); + } else if (binding instanceof LocalDateTime) { + queryBuilder.addBinding(((LocalDateTime) binding).format(LocalDateTimeMapper.FORMATTER)); + } else if (binding instanceof OffsetDateTime) { + queryBuilder.addBinding(toTimestamp((OffsetDateTime) binding)); + } else if (binding instanceof ZonedDateTime) { + queryBuilder.addBinding(toTimestamp((ZonedDateTime) binding)); + } else if (binding instanceof byte[]) { + queryBuilder.addBinding(Blob.copyFrom((byte[]) binding)); + } else if (binding instanceof DatastoreKey) { + queryBuilder.addBinding(((DatastoreKey) binding).nativeKey()); + } else if (binding instanceof DatastoreCursor) { + queryBuilder.addBinding(Cursor.fromUrlSafe(((DatastoreCursor) binding).getEncoded())); + } else if (binding instanceof GeoLocation) { + // TODO no support for GeoLocation in the gcloud API + } + } - /** - * Applies the given positional bindings to the given query builder. - * - * @param queryBuilder - * the query builder - * @param namedBindings - * the named bindings to apply - */ - static void applyNamedBindings(GqlQuery.Builder queryBuilder, Map namedBindings) { - if (namedBindings != null) { - for (Map.Entry entry : namedBindings.entrySet()) { - String bindingName = entry.getKey(); - Object bindingValue = entry.getValue(); - if (bindingValue instanceof Short) { - queryBuilder.setBinding(bindingName, (short) bindingValue); - } else if (bindingValue instanceof Integer) { - queryBuilder.setBinding(bindingName, (int) bindingValue); - } else if (bindingValue instanceof Long) { - queryBuilder.setBinding(bindingName, (long) bindingValue); - } else if (bindingValue instanceof Float) { - queryBuilder.setBinding(bindingName, (float) bindingValue); - } else if (bindingValue instanceof Double) { - queryBuilder.setBinding(bindingName, (double) bindingValue); - } else if (bindingValue instanceof Boolean) { - queryBuilder.setBinding(bindingName, (boolean) bindingValue); - } else if (bindingValue instanceof String) { - queryBuilder.setBinding(bindingName, (String) bindingValue); - } else if (bindingValue instanceof Calendar) { - queryBuilder.setBinding(bindingName, toTimestamp((Calendar) bindingValue)); - } else if (bindingValue instanceof Date) { - queryBuilder.setBinding(bindingName, toTimestamp((Date) bindingValue)); - } else if (bindingValue instanceof LocalDate) { - queryBuilder.setBinding(bindingName, ((LocalDate) bindingValue).toString()); - } else if (bindingValue instanceof LocalTime) { - queryBuilder.setBinding(bindingName, ((LocalTime) bindingValue).format(LocalTimeMapper.FORMATTER)); - } else if (bindingValue instanceof LocalDateTime) { - queryBuilder.setBinding(bindingName, - ((LocalDateTime) bindingValue).format(LocalDateTimeMapper.FORMATTER)); - } else if (bindingValue instanceof OffsetDateTime) { - queryBuilder.setBinding(bindingName, toTimestamp((OffsetDateTime) bindingValue)); - } else if (bindingValue instanceof ZonedDateTime) { - queryBuilder.setBinding(bindingName, toTimestamp((ZonedDateTime) bindingValue)); - } else if (bindingValue instanceof byte[]) { - queryBuilder.setBinding(bindingName, Blob.copyFrom((byte[]) bindingValue)); - } else if (bindingValue instanceof DatastoreKey) { - queryBuilder.setBinding(bindingName, ((DatastoreKey) bindingValue).nativeKey()); - } else if (bindingValue instanceof DatastoreCursor) { - queryBuilder.setBinding(bindingName, - Cursor.fromUrlSafe(((DatastoreCursor) bindingValue).getEncoded())); - } else if (bindingValue instanceof GeoLocation) { - // TODO no support for GeoLocation in the gcloud API - } - } - } - } + /** + * Applies the given positional bindings to the given query builder. + * + * @param queryBuilder + * the query builder + * @param namedBindings + * the named bindings to apply + */ + static void applyNamedBindings(GqlQuery.Builder queryBuilder, + Map namedBindings) { + if (namedBindings != null) { + for (Map.Entry entry : namedBindings.entrySet()) { + String bindingName = entry.getKey(); + Object bindingValue = entry.getValue(); + if (bindingValue instanceof Short) { + queryBuilder.setBinding(bindingName, (short) bindingValue); + } else if (bindingValue instanceof Integer) { + queryBuilder.setBinding(bindingName, (int) bindingValue); + } else if (bindingValue instanceof Long) { + queryBuilder.setBinding(bindingName, (long) bindingValue); + } else if (bindingValue instanceof Float) { + queryBuilder.setBinding(bindingName, (float) bindingValue); + } else if (bindingValue instanceof Double) { + queryBuilder.setBinding(bindingName, (double) bindingValue); + } else if (bindingValue instanceof Boolean) { + queryBuilder.setBinding(bindingName, (boolean) bindingValue); + } else if (bindingValue instanceof String) { + queryBuilder.setBinding(bindingName, (String) bindingValue); + } else if (bindingValue instanceof Calendar) { + queryBuilder.setBinding(bindingName, toTimestamp((Calendar) bindingValue)); + } else if (bindingValue instanceof Date) { + queryBuilder.setBinding(bindingName, toTimestamp((Date) bindingValue)); + } else if (bindingValue instanceof LocalDate) { + queryBuilder.setBinding(bindingName, ((LocalDate) bindingValue).toString()); + } else if (bindingValue instanceof LocalTime) { + queryBuilder.setBinding(bindingName, + ((LocalTime) bindingValue).format(LocalTimeMapper.FORMATTER)); + } else if (bindingValue instanceof LocalDateTime) { + queryBuilder.setBinding(bindingName, + ((LocalDateTime) bindingValue).format(LocalDateTimeMapper.FORMATTER)); + } else if (bindingValue instanceof OffsetDateTime) { + queryBuilder.setBinding(bindingName, toTimestamp((OffsetDateTime) bindingValue)); + } else if (bindingValue instanceof ZonedDateTime) { + queryBuilder.setBinding(bindingName, toTimestamp((ZonedDateTime) bindingValue)); + } else if (bindingValue instanceof byte[]) { + queryBuilder.setBinding(bindingName, Blob.copyFrom((byte[]) bindingValue)); + } else if (bindingValue instanceof DatastoreKey) { + queryBuilder.setBinding(bindingName, ((DatastoreKey) bindingValue).nativeKey()); + } else if (bindingValue instanceof DatastoreCursor) { + queryBuilder.setBinding(bindingName, + Cursor.fromUrlSafe(((DatastoreCursor) bindingValue).getEncoded())); + } else if (bindingValue instanceof GeoLocation) { + // TODO no support for GeoLocation in the gcloud API + } + } + } + } - /** - * Converts the given Calendar to a Timestamp. - * - * @param calendar - * the Calendar to convert - * @return Timestamp object that is equivalent to the given Calendar. - */ - private static Timestamp toTimestamp(Calendar calendar) { - return Timestamp.of(calendar.getTime()); - } + /** + * Converts the given Calendar to a Timestamp. + * + * @param calendar + * the Calendar to convert + * @return Timestamp object that is equivalent to the given Calendar. + */ + private static Timestamp toTimestamp(Calendar calendar) { + return Timestamp.of(calendar.getTime()); + } - /** - * Converts the given Date to a Timestamp. - * - * @param date - * the Date to convert - * @return Timestamp object that is equivalent to the given Date. - */ - private static Timestamp toTimestamp(Date date) { - return Timestamp.of(date); - } + /** + * Converts the given Date to a Timestamp. + * + * @param date + * the Date to convert + * @return Timestamp object that is equivalent to the given Date. + */ + private static Timestamp toTimestamp(Date date) { + return Timestamp.of(date); + } - /** - * Converts the given OffsetDateTime to a Timestamp. - * - * @param offsetDateTime - * the OffsetDateTime to convert - * @return Timestamp object that is equivalent to the given OffsetDateTime. - */ - private static Timestamp toTimestamp(OffsetDateTime offsetDateTime) { - long seconds = offsetDateTime.toEpochSecond(); - int nanos = offsetDateTime.getNano(); - long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); - return Timestamp.ofTimeMicroseconds(microseconds); - } + /** + * Converts the given OffsetDateTime to a Timestamp. + * + * @param offsetDateTime + * the OffsetDateTime to convert + * @return Timestamp object that is equivalent to the given OffsetDateTime. + */ + private static Timestamp toTimestamp(OffsetDateTime offsetDateTime) { + long seconds = offsetDateTime.toEpochSecond(); + int nanos = offsetDateTime.getNano(); + long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); + return Timestamp.ofTimeMicroseconds(microseconds); + } - /** - * Converts the given OffsetDateTime to a Timestamp. - * - * @param zonedDateTime - * the {@link ZonedDateTime} to convert - * @return Timestamp object that is equivalent to the given OffsetDateTime. - */ - private static Timestamp toTimestamp(ZonedDateTime zonedDateTime) { - long seconds = zonedDateTime.toEpochSecond(); - int nanos = zonedDateTime.getNano(); - long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); - return Timestamp.ofTimeMicroseconds(microseconds); - } + /** + * Converts the given OffsetDateTime to a Timestamp. + * + * @param zonedDateTime + * the {@link ZonedDateTime} to convert + * @return Timestamp object that is equivalent to the given OffsetDateTime. + */ + private static Timestamp toTimestamp(ZonedDateTime zonedDateTime) { + long seconds = zonedDateTime.toEpochSecond(); + int nanos = zonedDateTime.getNano(); + long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); + return Timestamp.ofTimeMicroseconds(microseconds); + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/StorageStrategy.java b/src/main/java/com/jmethods/catatumbo/impl/StorageStrategy.java index e7a64e4..e740540 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/StorageStrategy.java +++ b/src/main/java/com/jmethods/catatumbo/impl/StorageStrategy.java @@ -26,16 +26,14 @@ */ public enum StorageStrategy { - /** - * The object tree of {@link Embedded} field is exploded into individual - * properties. - */ - EXPLODED, + /** + * The object tree of {@link Embedded} field is exploded into individual properties. + */ + EXPLODED, - /** - * The object tree of {@link Embedded} field is stored in a single property - * as an Embedded Entity. - */ - IMPLODED; + /** + * The object tree of {@link Embedded} field is stored in a single property as an Embedded Entity. + */ + IMPLODED; } diff --git a/src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java b/src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java index 9299a19..5243690 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java +++ b/src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.jmethods.catatumbo.impl; import java.lang.invoke.MethodHandle; @@ -36,340 +37,333 @@ */ public class Unmarshaller { - /** - * Input - Native Entity to unmarshal, could be a ProjectionEntity or an - * Entity - */ - private final BaseEntity nativeEntity; + /** + * Input - Native Entity to unmarshal, could be a ProjectionEntity or an Entity + */ + private final BaseEntity nativeEntity; - /** - * Output - unmarshalled object - */ - private Object entity; + /** + * Output - unmarshalled object + */ + private Object entity; - /** - * Entity metadata - */ - private final EntityMetadata entityMetadata; + /** + * Entity metadata + */ + private final EntityMetadata entityMetadata; - /** - * Creates a new instance of Unmarshaller. - * - * @param nativeEntity - * the native entity to unmarshal - * @param entityClass - * the expected model type - */ - private Unmarshaller(BaseEntity nativeEntity, Class entityClass) { - this.nativeEntity = nativeEntity; - entityMetadata = EntityIntrospector.introspect(entityClass); + /** + * Creates a new instance of Unmarshaller. + * + * @param nativeEntity + * the native entity to unmarshal + * @param entityClass + * the expected model type + */ + private Unmarshaller(BaseEntity nativeEntity, Class entityClass) { + this.nativeEntity = nativeEntity; + entityMetadata = EntityIntrospector.introspect(entityClass); - } + } - /** - * Unmarshals the given native Entity into an object of given type, - * entityClass. - * - * @param - * target object type - * @param nativeEntity - * the native Entity - * @param entityClass - * the target type - * @return Object that is equivalent to the given native entity. If the - * given datastoreEntity is null, returns - * null. - */ - public static T unmarshal(Entity nativeEntity, Class entityClass) { - return unmarshalBaseEntity(nativeEntity, entityClass); - } + /** + * Unmarshals the given native Entity into an object of given type, entityClass. + * + * @param + * target object type + * @param nativeEntity + * the native Entity + * @param entityClass + * the target type + * @return Object that is equivalent to the given native entity. If the given + * datastoreEntity is null, returns null. + */ + public static T unmarshal(Entity nativeEntity, Class entityClass) { + return unmarshalBaseEntity(nativeEntity, entityClass); + } - /** - * Unmarshals the given native ProjectionEntity into an object of given - * type, entityClass. - * - * @param - * target object type - * @param nativeEntity - * the native Entity - * @param entityClass - * the target type - * @return Object that is equivalent to the given native entity. If the - * given datastoreEntity is null, returns - * null. - */ - public static T unmarshal(ProjectionEntity nativeEntity, Class entityClass) { - return unmarshalBaseEntity(nativeEntity, entityClass); - } + /** + * Unmarshals the given native ProjectionEntity into an object of given type, entityClass. + * + * @param + * target object type + * @param nativeEntity + * the native Entity + * @param entityClass + * the target type + * @return Object that is equivalent to the given native entity. If the given + * datastoreEntity is null, returns null. + */ + public static T unmarshal(ProjectionEntity nativeEntity, Class entityClass) { + return unmarshalBaseEntity(nativeEntity, entityClass); + } - /** - * Unmarshals the given BaseEntity and returns the equivalent model object. - * - * @param nativeEntity - * the native entity to unmarshal - * @param entityClass - * the target type of the model class - * @return the model object - */ - private static T unmarshalBaseEntity(BaseEntity nativeEntity, Class entityClass) { - if (nativeEntity == null) { - return null; - } - Unmarshaller unmarshaller = new Unmarshaller(nativeEntity, entityClass); - return unmarshaller.unmarshal(); - } + /** + * Unmarshals the given Datastore Entity and returns the equivalent Entity POJO. + * + * @param + * type + * @return the entity POJO + */ + @SuppressWarnings("unchecked") + private T unmarshal() { - /** - * Unmarshals the given Datastore Entity and returns the equivalent Entity - * POJO. - * - * @param - * type - * @return the entity POJO - */ - @SuppressWarnings("unchecked") - private T unmarshal() { + try { + instantiateEntity(); + unmarshalIdentifier(); + unmarshalKeyAndParentKey(); + unmarshalProperties(); + unmarshalEmbeddedFields(); + // If using Builder pattern, invoke build method on the Builder to + // get the final entity. + ConstructorMetadata constructorMetadata = entityMetadata.getConstructorMetadata(); + if (constructorMetadata.isBuilderConstructionStrategy()) { + entity = constructorMetadata.getBuildMethodHandle().invoke(entity); + } + return (T) entity; + } catch (EntityManagerException exp) { + throw exp; + } catch (Throwable t) { + throw new EntityManagerException(t.getMessage(), t); + } + } - try { - instantiateEntity(); - unmarshalIdentifier(); - unmarshalKeyAndParentKey(); - unmarshalProperties(); - unmarshalEmbeddedFields(); - // If using Builder pattern, invoke build method on the Builder to - // get the final entity. - ConstructorMetadata constructorMetadata = entityMetadata.getConstructorMetadata(); - if (constructorMetadata.isBuilderConstructionStrategy()) { - entity = constructorMetadata.getBuildMethodHandle().invoke(entity); - } - return (T) entity; - } catch (EntityManagerException exp) { - throw exp; - } catch (Throwable t) { - throw new EntityManagerException(t.getMessage(), t); - } - } + /** + * Unmarshals the given BaseEntity and returns the equivalent model object. + * + * @param nativeEntity + * the native entity to unmarshal + * @param entityClass + * the target type of the model class + * @return the model object + */ + private static T unmarshalBaseEntity(BaseEntity nativeEntity, Class entityClass) { + if (nativeEntity == null) { + return null; + } + Unmarshaller unmarshaller = new Unmarshaller(nativeEntity, entityClass); + return unmarshaller.unmarshal(); + } - /** - * Instantiates the entity. - */ - private void instantiateEntity() { - entity = IntrospectionUtils.instantiate(entityMetadata); - } + /** + * Instantiates the entity. + */ + private void instantiateEntity() { + entity = IntrospectionUtils.instantiate(entityMetadata); + } - /** - * Unamrshals the identifier. - * - * @throws Throwable - * propagated - */ - private void unmarshalIdentifier() throws Throwable { - IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); - Object id = ((Key) nativeEntity.getKey()).getNameOrId(); - // If the ID is not a simple type... - IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); - if (idClassMetadata != null) { - Object wrappedId = idClassMetadata.getConstructor().invoke(id); - id = wrappedId; - } - // Now set the ID (either simple or complex) on the Entity - MethodHandle writeMethod = identifierMetadata.getWriteMethod(); - writeMethod.invoke(entity, id); - } + /** + * Unamrshals the identifier. + * + * @throws Throwable + * propagated + */ + private void unmarshalIdentifier() throws Throwable { + IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); + Object id = ((Key) nativeEntity.getKey()).getNameOrId(); + // If the ID is not a simple type... + IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); + if (idClassMetadata != null) { + Object wrappedId = idClassMetadata.getConstructor().invoke(id); + id = wrappedId; + } + // Now set the ID (either simple or complex) on the Entity + MethodHandle writeMethod = identifierMetadata.getWriteMethod(); + writeMethod.invoke(entity, id); + } - /** - * Unamrshals the entity's key and parent key. - * - * @throws Throwable - * propagated - * - */ - private void unmarshalKeyAndParentKey() throws Throwable { - KeyMetadata keyMetadata = entityMetadata.getKeyMetadata(); - if (keyMetadata != null) { - MethodHandle writeMethod = keyMetadata.getWriteMethod(); - Key entityKey = (Key) nativeEntity.getKey(); - writeMethod.invoke(entity, new DefaultDatastoreKey(entityKey)); - } + /** + * Unamrshals the entity's key and parent key. + * + * @throws Throwable + * propagated + * + */ + private void unmarshalKeyAndParentKey() throws Throwable { + KeyMetadata keyMetadata = entityMetadata.getKeyMetadata(); + if (keyMetadata != null) { + MethodHandle writeMethod = keyMetadata.getWriteMethod(); + Key entityKey = (Key) nativeEntity.getKey(); + writeMethod.invoke(entity, new DefaultDatastoreKey(entityKey)); + } - ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); - if (parentKeyMetadata != null) { - MethodHandle writeMethod = parentKeyMetadata.getWriteMethod(); - Key parentKey = nativeEntity.getKey().getParent(); - if (parentKey != null) { - writeMethod.invoke(entity, new DefaultDatastoreKey(parentKey)); - } - } - } + ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); + if (parentKeyMetadata != null) { + MethodHandle writeMethod = parentKeyMetadata.getWriteMethod(); + Key parentKey = nativeEntity.getKey().getParent(); + if (parentKey != null) { + writeMethod.invoke(entity, new DefaultDatastoreKey(parentKey)); + } + } + } - /** - * Unmarshal all the properties. - * - * @throws Throwable - * propagated - */ - private void unmarshalProperties() throws Throwable { - Collection propertyMetadataCollection = entityMetadata.getPropertyMetadataCollection(); - for (PropertyMetadata propertyMetadata : propertyMetadataCollection) { - unmarshalProperty(propertyMetadata, entity); - } - } + /** + * Unmarshal all the properties. + * + * @throws Throwable + * propagated + */ + private void unmarshalProperties() throws Throwable { + Collection propertyMetadataCollection = entityMetadata + .getPropertyMetadataCollection(); + for (PropertyMetadata propertyMetadata : propertyMetadataCollection) { + unmarshalProperty(propertyMetadata, entity); + } + } - /** - * Unmarshals the embedded fields of this entity. - * - * @throws Throwable - * propagated - */ - private void unmarshalEmbeddedFields() throws Throwable { - for (EmbeddedMetadata embeddedMetadata : entityMetadata.getEmbeddedMetadataCollection()) { - if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { - unmarshalWithExplodedStrategy(embeddedMetadata, entity); - } else { - unmarshalWithImplodedStrategy(embeddedMetadata, entity, nativeEntity); - } - } - } + /** + * Unmarshals the embedded fields of this entity. + * + * @throws Throwable + * propagated + */ + private void unmarshalEmbeddedFields() throws Throwable { + for (EmbeddedMetadata embeddedMetadata : entityMetadata.getEmbeddedMetadataCollection()) { + if (embeddedMetadata.getStorageStrategy() == StorageStrategy.EXPLODED) { + unmarshalWithExplodedStrategy(embeddedMetadata, entity); + } else { + unmarshalWithImplodedStrategy(embeddedMetadata, entity, nativeEntity); + } + } + } - /** - * Unmarshals the embedded field represented by the given embedded metadata. - * - * @param embeddedMetadata - * the embedded metadata - * @param target - * the target object that needs to be updated - * @throws Throwable - * propagated - */ - private void unmarshalWithExplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) throws Throwable { - Object embeddedObject = initializeEmbedded(embeddedMetadata, target); - for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { - unmarshalProperty(propertyMetadata, embeddedObject); - } - for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { - unmarshalWithExplodedStrategy(embeddedMetadata2, embeddedObject); - } - ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); - if (constructorMetadata.isBuilderConstructionStrategy()) { - embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); - } - embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); - } + /** + * Unmarshals the embedded field represented by the given embedded metadata. + * + * @param embeddedMetadata + * the embedded metadata + * @param target + * the target object that needs to be updated + * @throws Throwable + * propagated + */ + private void unmarshalWithExplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) + throws Throwable { + Object embeddedObject = initializeEmbedded(embeddedMetadata, target); + for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { + unmarshalProperty(propertyMetadata, embeddedObject); + } + for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { + unmarshalWithExplodedStrategy(embeddedMetadata2, embeddedObject); + } + ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); + if (constructorMetadata.isBuilderConstructionStrategy()) { + embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); + } + embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); + } - /** - * Unmarshals the embedded field represented by the given metadata. - * - * @param embeddedMetadata - * the metadata of the field to unmarshal - * @param target - * the object in which the embedded field is declared/accessible - * from - * @param nativeEntity - * the native entity from which the embedded entity is to be - * extracted - * @throws Throwable - * propagated - */ - private static void unmarshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target, - BaseEntity nativeEntity) throws Throwable { - Object embeddedObject = null; - ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); - FullEntity nativeEmbeddedEntity = null; - String propertyName = embeddedMetadata.getMappedName(); - if (nativeEntity.contains(propertyName)) { - Value nativeValue = nativeEntity.getValue(propertyName); - if (nativeValue instanceof NullValue) { - embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); - } else { - nativeEmbeddedEntity = ((EntityValue) nativeValue).get(); - embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); - } - } - if (embeddedObject == null) { - return; - } - for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { - unmarshalProperty(propertyMetadata, embeddedObject, nativeEmbeddedEntity); - } - for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { - unmarshalWithImplodedStrategy(embeddedMetadata2, embeddedObject, nativeEmbeddedEntity); - } - if (constructorMetadata.isBuilderConstructionStrategy()) { - embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); - } - embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); - } + /** + * Unmarshals the embedded field represented by the given metadata. + * + * @param embeddedMetadata + * the metadata of the field to unmarshal + * @param target + * the object in which the embedded field is declared/accessible from + * @param nativeEntity + * the native entity from which the embedded entity is to be extracted + * @throws Throwable + * propagated + */ + private static void unmarshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata, + Object target, BaseEntity nativeEntity) throws Throwable { + Object embeddedObject = null; + ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); + FullEntity nativeEmbeddedEntity = null; + String propertyName = embeddedMetadata.getMappedName(); + if (nativeEntity.contains(propertyName)) { + Value nativeValue = nativeEntity.getValue(propertyName); + if (nativeValue instanceof NullValue) { + embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); + } else { + nativeEmbeddedEntity = ((EntityValue) nativeValue).get(); + embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); + } + } + if (embeddedObject == null) { + return; + } + for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { + unmarshalProperty(propertyMetadata, embeddedObject, nativeEmbeddedEntity); + } + for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { + unmarshalWithImplodedStrategy(embeddedMetadata2, embeddedObject, nativeEmbeddedEntity); + } + if (constructorMetadata.isBuilderConstructionStrategy()) { + embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); + } + embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); + } - /** - * Unmarshals the property represented by the given property metadata and - * updates the target object with the property value. - * - * @param propertyMetadata - * the property metadata - * @param target - * the target object to update - * @throws Throwable - * propagated - */ - private void unmarshalProperty(PropertyMetadata propertyMetadata, Object target) throws Throwable { - unmarshalProperty(propertyMetadata, target, nativeEntity); - } + /** + * Unmarshals the property represented by the given property metadata and updates the target + * object with the property value. + * + * @param propertyMetadata + * the property metadata + * @param target + * the target object to update + * @throws Throwable + * propagated + */ + private void unmarshalProperty(PropertyMetadata propertyMetadata, Object target) + throws Throwable { + unmarshalProperty(propertyMetadata, target, nativeEntity); + } - /** - * Unmarshals the property with the given metadata and sets the unmarshalled - * value on the given target object. - * - * @param propertyMetadata - * the metadata of the property - * @param target - * the target object to set the unmarshalled value on - * @param nativeEntity - * the native entity containing the source property - * @throws Throwable - * propagated - */ - private static void unmarshalProperty(PropertyMetadata propertyMetadata, Object target, BaseEntity nativeEntity) - throws Throwable { - // The datastore may not have every property that the entity class has - // defined. For example, if we are running a projection query or if the - // entity class added a new field without updating existing data...So - // make sure there is a property or else, we get an exception from the - // datastore. - if (nativeEntity.contains(propertyMetadata.getMappedName())) { - Value datastoreValue = nativeEntity.getValue(propertyMetadata.getMappedName()); - Object entityValue = propertyMetadata.getMapper().toModel(datastoreValue); - MethodHandle writeMethod = propertyMetadata.getWriteMethod(); - writeMethod.invoke(target, entityValue); - } - } + /** + * Unmarshals the property with the given metadata and sets the unmarshalled value on the given + * target object. + * + * @param propertyMetadata + * the metadata of the property + * @param target + * the target object to set the unmarshalled value on + * @param nativeEntity + * the native entity containing the source property + * @throws Throwable + * propagated + */ + private static void unmarshalProperty(PropertyMetadata propertyMetadata, Object target, + BaseEntity nativeEntity) throws Throwable { + // The datastore may not have every property that the entity class has + // defined. For example, if we are running a projection query or if the + // entity class added a new field without updating existing data...So + // make sure there is a property or else, we get an exception from the + // datastore. + if (nativeEntity.contains(propertyMetadata.getMappedName())) { + Value datastoreValue = nativeEntity.getValue(propertyMetadata.getMappedName()); + Object entityValue = propertyMetadata.getMapper().toModel(datastoreValue); + MethodHandle writeMethod = propertyMetadata.getWriteMethod(); + writeMethod.invoke(target, entityValue); + } + } - /** - * Initializes the Embedded object represented by the given metadata. - * - * @param embeddedMetadata - * the metadata of the embedded field - * @param target - * the object in which the embedded field is declared/accessible - * from - * @return the initialized object - * @throws EntityManagerException - * if any error occurs during initialization of the embedded - * object - */ - private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { - try { - ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); - Object embeddedObject = null; - if (constructorMetadata.isClassicConstructionStrategy()) { - embeddedObject = embeddedMetadata.getReadMethod().invoke(target); - } - if (embeddedObject == null) { - embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); - } - return embeddedObject; - } catch (Throwable t) { - throw new EntityManagerException(t); - } - } + /** + * Initializes the Embedded object represented by the given metadata. + * + * @param embeddedMetadata + * the metadata of the embedded field + * @param target + * the object in which the embedded field is declared/accessible from + * @return the initialized object + * @throws EntityManagerException + * if any error occurs during initialization of the embedded object + */ + private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { + try { + ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); + Object embeddedObject = null; + if (constructorMetadata.isClassicConstructionStrategy()) { + embeddedObject = embeddedMetadata.getReadMethod().invoke(target); + } + if (embeddedObject == null) { + embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); + } + return embeddedObject; + } catch (Throwable t) { + throw new EntityManagerException(t); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/impl/package-info.java b/src/main/java/com/jmethods/catatumbo/impl/package-info.java index 0b0d103..8f7b63a 100644 --- a/src/main/java/com/jmethods/catatumbo/impl/package-info.java +++ b/src/main/java/com/jmethods/catatumbo/impl/package-info.java @@ -15,9 +15,10 @@ */ /** - * This package contains the implementation classes for the Catatumbo API. All - * classes in this package are internal to the functioning of the API and you - * should never use any of these classes directly in your application's code. + * This package contains the implementation classes for the Catatumbo API. All classes in this + * package are internal to the functioning of the API and you should never use any of these classes + * directly in your application's code. * */ + package com.jmethods.catatumbo.impl; \ No newline at end of file diff --git a/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexer.java b/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexer.java index 8a4cdf3..5f04a41 100644 --- a/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexer.java +++ b/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexer.java @@ -26,26 +26,26 @@ import com.jmethods.catatumbo.IndexingException; /** - * An implementation of {@link Indexer} interface for creating indexes in lower - * case. This indexer assumes that the value being indexed is of type String. - * Any other type will result in an {@link IndexingException}. + * An implementation of {@link Indexer} interface for creating indexes in lower case. This indexer + * assumes that the value being indexed is of type String. Any other type will result in an + * {@link IndexingException}. * * @author Sai Pullabhotla * */ public class LowerCaseStringIndexer implements Indexer { - @Override - public Value index(Value input) { - if (input.getType() == ValueType.NULL) { - return NullValue.of(); - } - try { - String str = ((StringValue) input).get(); - return StringValue.of(str.toLowerCase(Locale.ENGLISH)); - } catch (Exception exp) { - throw new IndexingException(exp); - } - } + @Override + public Value index(Value input) { + if (input.getType() == ValueType.NULL) { + return NullValue.of(); + } + try { + String str = ((StringValue) input).get(); + return StringValue.of(str.toLowerCase(Locale.ENGLISH)); + } catch (Exception exp) { + throw new IndexingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexer.java b/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexer.java index 08bff3e..4e45958 100644 --- a/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexer.java +++ b/src/main/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexer.java @@ -27,36 +27,35 @@ import com.jmethods.catatumbo.IndexingException; /** - * An implementation of {@link Indexer} interface to index a List of Strings. - * Each item in the list will be converted to lower case and stored as an Array - * property in the Cloud Datastore. + * An implementation of {@link Indexer} interface to index a List of Strings. Each item in the list + * will be converted to lower case and stored as an Array property in the Cloud Datastore. * * @author Sai Pullabhotla * */ public class LowerCaseStringListIndexer implements Indexer { - /** - * Indexer for items in the list. - */ - private static final LowerCaseStringIndexer ITEM_INDEXER = IndexerFactory.getInstance() - .getIndexer(LowerCaseStringIndexer.class); + /** + * Indexer for items in the list. + */ + private static final LowerCaseStringIndexer ITEM_INDEXER = IndexerFactory.getInstance() + .getIndexer(LowerCaseStringIndexer.class); - @Override - public Value index(Value input) { - if (input.getType() == ValueType.NULL) { - return NullValue.of(); - } - try { - List> list = ((ListValue) input).get(); - ListValue.Builder builder = ListValue.newBuilder(); - for (Value item : list) { - builder.addValue(ITEM_INDEXER.index(item)); - } - return builder.build(); - } catch (Exception exp) { - throw new IndexingException(exp); - } - } + @Override + public Value index(Value input) { + if (input.getType() == ValueType.NULL) { + return NullValue.of(); + } + try { + List> list = ((ListValue) input).get(); + ListValue.Builder builder = ListValue.newBuilder(); + for (Value item : list) { + builder.addValue(ITEM_INDEXER.index(item)); + } + return builder.build(); + } catch (Exception exp) { + throw new IndexingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexer.java b/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexer.java index 238df12..f53dc68 100644 --- a/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexer.java +++ b/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexer.java @@ -26,26 +26,26 @@ import com.jmethods.catatumbo.IndexingException; /** - * An implementation of {@link Indexer} interface for creating indexes in upper - * case. This indexer assumes that the value being indexed is of type String. - * Any other type will result in ClassCastException. + * An implementation of {@link Indexer} interface for creating indexes in upper case. This indexer + * assumes that the value being indexed is of type String. Any other type will result in + * ClassCastException. * * @author Sai Pullabhotla * */ public class UpperCaseStringIndexer implements Indexer { - @Override - public Value index(Value input) { - if (input.getType() == ValueType.NULL) { - return NullValue.of(); - } - try { - String str = ((StringValue) input).get(); - return StringValue.of(str.toUpperCase(Locale.ENGLISH)); - } catch (Exception exp) { - throw new IndexingException(exp); - } - } + @Override + public Value index(Value input) { + if (input.getType() == ValueType.NULL) { + return NullValue.of(); + } + try { + String str = ((StringValue) input).get(); + return StringValue.of(str.toUpperCase(Locale.ENGLISH)); + } catch (Exception exp) { + throw new IndexingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexer.java b/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexer.java index 7e987c0..03190ec 100644 --- a/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexer.java +++ b/src/main/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexer.java @@ -27,36 +27,36 @@ import com.jmethods.catatumbo.IndexingException; /** - * An implementation of {@link Indexer} interface to create index on a list of - * Strings in upper case. Each item in the list will be converted to upper case - * and then stored as an Array property in the Cloud Datastore. + * An implementation of {@link Indexer} interface to create index on a list of Strings in upper + * case. Each item in the list will be converted to upper case and then stored as an Array property + * in the Cloud Datastore. * * @author Sai Pullabhotla * */ public class UpperCaseStringListIndexer implements Indexer { - /** - * Indexer for the items in the list - */ - private static final UpperCaseStringIndexer ITEM_INDEXER = IndexerFactory.getInstance() - .getIndexer(UpperCaseStringIndexer.class); + /** + * Indexer for the items in the list + */ + private static final UpperCaseStringIndexer ITEM_INDEXER = IndexerFactory.getInstance() + .getIndexer(UpperCaseStringIndexer.class); - @Override - public Value index(Value input) { - if (input.getType() == ValueType.NULL) { - return NullValue.of(); - } - try { - ListValue.Builder builder = ListValue.newBuilder(); - List> list = ((ListValue) input).get(); - for (Value item : list) { - builder.addValue(ITEM_INDEXER.index(item)); - } - return builder.build(); - } catch (Exception exp) { - throw new IndexingException(exp); - } - } + @Override + public Value index(Value input) { + if (input.getType() == ValueType.NULL) { + return NullValue.of(); + } + try { + ListValue.Builder builder = ListValue.newBuilder(); + List> list = ((ListValue) input).get(); + for (Value item : list) { + builder.addValue(ITEM_INDEXER.index(item)); + } + return builder.build(); + } catch (Exception exp) { + throw new IndexingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/indexers/package-info.java b/src/main/java/com/jmethods/catatumbo/indexers/package-info.java index 1ca94ea..9c6e887 100644 --- a/src/main/java/com/jmethods/catatumbo/indexers/package-info.java +++ b/src/main/java/com/jmethods/catatumbo/indexers/package-info.java @@ -17,4 +17,5 @@ /** * Contains various indexers for indexing the entity properties. */ + package com.jmethods.catatumbo.indexers; \ No newline at end of file diff --git a/src/main/java/com/jmethods/catatumbo/mappers/BigDecimalMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/BigDecimalMapper.java index ace3e6d..5dd1f10 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/BigDecimalMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/BigDecimalMapper.java @@ -25,28 +25,27 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping BigDecimal types to/from - * Cloud Datastore. + * An implementation of {@link Mapper} for mapping BigDecimal types to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class BigDecimalMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return DoubleValue.newBuilder(((BigDecimal) input).doubleValue()); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return DoubleValue.newBuilder(((BigDecimal) input).doubleValue()); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return BigDecimal.valueOf(((DoubleValue) input).get()); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return BigDecimal.valueOf(((DoubleValue) input).get()); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/BooleanMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/BooleanMapper.java index 0cb8f1b..47b8363 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/BooleanMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/BooleanMapper.java @@ -23,28 +23,28 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper boolean - * types to/from Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper boolean types to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class BooleanMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return BooleanValue.newBuilder((boolean) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return BooleanValue.newBuilder((boolean) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((BooleanValue) input).get(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((BooleanValue) input).get(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/ByteArrayMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/ByteArrayMapper.java index 2db5101..6f9ab06 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/ByteArrayMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/ByteArrayMapper.java @@ -24,28 +24,27 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping byte array types to/from - * Cloud Datastore. + * An implementation of {@link Mapper} for mapping byte array types to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class ByteArrayMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return BlobValue.newBuilder(Blob.copyFrom((byte[]) input)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return BlobValue.newBuilder(Blob.copyFrom((byte[]) input)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((BlobValue) input).get().toByteArray(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((BlobValue) input).get().toByteArray(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/CalendarMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/CalendarMapper.java index ef1ed4f..2d948b7 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/CalendarMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/CalendarMapper.java @@ -28,38 +28,39 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping Calendar type to/from Cloud - * Datastore. Calendar objects are mapped to DateTime type in the Cloud - * Datastore. The values are stored with a maximum precision of milliseconds. + * An implementation of {@link Mapper} for mapping Calendar type to/from Cloud Datastore. Calendar + * objects are mapped to DateTime type in the Cloud Datastore. The values are stored with a maximum + * precision of milliseconds. * * @author Sai Pullabhotla * */ public class CalendarMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - Calendar calendar = (Calendar) input; - return TimestampValue.newBuilder(Timestamp.of(calendar.getTime())); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + Calendar calendar = (Calendar) input; + return TimestampValue.newBuilder(Timestamp.of(calendar.getTime())); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - Timestamp ts = ((TimestampValue) input).get(); - long millis = TimeUnit.SECONDS.toMillis(ts.getSeconds()) + TimeUnit.NANOSECONDS.toMillis(ts.getNanos()); - return new Calendar.Builder().setInstant(millis).build(); - } catch (ClassCastException exp) { - String pattern = "Expecting %s, but found %s"; - throw new MappingException( - String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + Timestamp ts = ((TimestampValue) input).get(); + long millis = TimeUnit.SECONDS.toMillis(ts.getSeconds()) + + TimeUnit.NANOSECONDS.toMillis(ts.getNanos()); + return new Calendar.Builder().setInstant(millis).build(); + } catch (ClassCastException exp) { + String pattern = "Expecting %s, but found %s"; + throw new MappingException( + String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/CatchAllMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/CatchAllMapper.java index 442ca16..98d3fc1 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/CatchAllMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/CatchAllMapper.java @@ -39,100 +39,100 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping select set of - * primitive/wrapper types to the Cloud Datastore. The primary purpose if this - * mapper is to aid with mapping Lists, Sets and Maps when the collections are - * not parameterized. + * An implementation of {@link Mapper} for mapping select set of primitive/wrapper types to the + * Cloud Datastore. The primary purpose if this mapper is to aid with mapping Lists, Sets and Maps + * when the collections are not parameterized. * * @author Sai Pullabhotla * */ public class CatchAllMapper implements Mapper { - /** - * Singleton instance - */ - private static final CatchAllMapper INSTANCE = new CatchAllMapper(); + /** + * Singleton instance + */ + private static final CatchAllMapper INSTANCE = new CatchAllMapper(); - /** - * Creates a new instance of CatchAllMapper. - */ - private CatchAllMapper() { - // Do nothing - } + /** + * Creates a new instance of CatchAllMapper. + */ + private CatchAllMapper() { + // Do nothing + } - /** - * Returns the singleton instance of this mapper. - * - * @return the singleton instance of this mapper. - */ - public static Mapper getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of this mapper. + * + * @return the singleton instance of this mapper. + */ + public static Mapper getInstance() { + return INSTANCE; + } - @Override - public ValueBuilder toDatastore(Object input) { - ValueBuilder builder; - if (input == null) { - builder = NullValue.newBuilder(); - } else if (input instanceof Long) { - builder = LongValue.newBuilder((long) input); - } else if (input instanceof Double) { - builder = DoubleValue.newBuilder((double) input); - } else if (input instanceof Boolean) { - builder = BooleanValue.newBuilder((boolean) input); - } else if (input instanceof String) { - builder = StringValue.newBuilder((String) input); - } else if (input instanceof DatastoreKey) { - builder = KeyValue.newBuilder(((DatastoreKey) input).nativeKey()); - } else if (input instanceof GeoLocation) { - GeoLocation geoLocation = (GeoLocation) input; - builder = LatLngValue.newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude())); - } else if (input instanceof Map) { - @SuppressWarnings("unchecked") - Map map = (Map) input; - FullEntity.Builder entityBuilder = FullEntity.newBuilder(); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - entityBuilder.set(key, toDatastore(entry.getValue()).build()); - } - builder = EntityValue.newBuilder(entityBuilder.build()); - } else { - throw new MappingException(String.format("Unsupported type: %s", input.getClass().getName())); - } - return builder; - } + @Override + public ValueBuilder toDatastore(Object input) { + ValueBuilder builder; + if (input == null) { + builder = NullValue.newBuilder(); + } else if (input instanceof Long) { + builder = LongValue.newBuilder((long) input); + } else if (input instanceof Double) { + builder = DoubleValue.newBuilder((double) input); + } else if (input instanceof Boolean) { + builder = BooleanValue.newBuilder((boolean) input); + } else if (input instanceof String) { + builder = StringValue.newBuilder((String) input); + } else if (input instanceof DatastoreKey) { + builder = KeyValue.newBuilder(((DatastoreKey) input).nativeKey()); + } else if (input instanceof GeoLocation) { + GeoLocation geoLocation = (GeoLocation) input; + builder = LatLngValue + .newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude())); + } else if (input instanceof Map) { + @SuppressWarnings("unchecked") + Map map = (Map) input; + FullEntity.Builder entityBuilder = FullEntity.newBuilder(); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + entityBuilder.set(key, toDatastore(entry.getValue()).build()); + } + builder = EntityValue.newBuilder(entityBuilder.build()); + } else { + throw new MappingException(String.format("Unsupported type: %s", input.getClass().getName())); + } + return builder; + } - @Override - public Object toModel(Value input) { - Object javaValue; - if (input instanceof NullValue) { - javaValue = null; - } else if (input instanceof StringValue) { - javaValue = input.get(); - } else if (input instanceof LongValue) { - javaValue = input.get(); - } else if (input instanceof DoubleValue) { - javaValue = input.get(); - } else if (input instanceof BooleanValue) { - javaValue = input.get(); - } else if (input instanceof KeyValue) { - javaValue = new DefaultDatastoreKey(((KeyValue) input).get()); - } else if (input instanceof LatLngValue) { - LatLng latLong = ((LatLngValue) input).get(); - javaValue = new GeoLocation(latLong.getLatitude(), latLong.getLongitude()); - } else if (input instanceof EntityValue) { - EntityValue entityValue = (EntityValue) input; - FullEntity entity = entityValue.get(); - Map map = new HashMap<>(); - for (String property : entity.getNames()) { - map.put(property, toModel(entity.getValue(property))); - } - javaValue = map; - } else { - throw new MappingException(String.format("Unsupported type %s", input.getClass().getName())); - } - return javaValue; - } + @Override + public Object toModel(Value input) { + Object javaValue; + if (input instanceof NullValue) { + javaValue = null; + } else if (input instanceof StringValue) { + javaValue = input.get(); + } else if (input instanceof LongValue) { + javaValue = input.get(); + } else if (input instanceof DoubleValue) { + javaValue = input.get(); + } else if (input instanceof BooleanValue) { + javaValue = input.get(); + } else if (input instanceof KeyValue) { + javaValue = new DefaultDatastoreKey(((KeyValue) input).get()); + } else if (input instanceof LatLngValue) { + LatLng latLong = ((LatLngValue) input).get(); + javaValue = new GeoLocation(latLong.getLatitude(), latLong.getLongitude()); + } else if (input instanceof EntityValue) { + EntityValue entityValue = (EntityValue) input; + FullEntity entity = entityValue.get(); + Map map = new HashMap<>(); + for (String property : entity.getNames()) { + map.put(property, toModel(entity.getValue(property))); + } + javaValue = map; + } else { + throw new MappingException(String.format("Unsupported type %s", input.getClass().getName())); + } + return javaValue; + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/CharArrayMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/CharArrayMapper.java index 462f961..7692bee 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/CharArrayMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/CharArrayMapper.java @@ -23,28 +23,27 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping char arrays to/from Cloud - * Datastore. + * An implementation of {@link Mapper} for mapping char arrays to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class CharArrayMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(new String((char[]) input)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(new String((char[]) input)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((StringValue) input).get().toCharArray(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((StringValue) input).get().toCharArray(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/CharMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/CharMapper.java index 89aa6c5..0982fa4 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/CharMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/CharMapper.java @@ -24,32 +24,31 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping Char type to/from Cloud - * Datastore. + * An implementation of {@link Mapper} for mapping Char type to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class CharMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(String.valueOf((char) input)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(String.valueOf((char) input)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - String str = ((StringValue) input).get(); - if (str.length() != 1) { - throw new MappingException(String.format("Unable to convert %s to char", str)); - } - return str.charAt(0); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + String str = ((StringValue) input).get(); + if (str.length() != 1) { + throw new MappingException(String.format("Unable to convert %s to char", str)); + } + return str.charAt(0); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/CollectionMapperFactory.java b/src/main/java/com/jmethods/catatumbo/mappers/CollectionMapperFactory.java index 813c51e..d3f55b4 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/CollectionMapperFactory.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/CollectionMapperFactory.java @@ -28,119 +28,117 @@ import com.jmethods.catatumbo.impl.Cache; /** - * A factory for producing {@link Mapper} for Collections - {@link List} and - * {@link Set}. + * A factory for producing {@link Mapper} for Collections - {@link List} and {@link Set}. * * @author Sai Pullabhotla * */ public class CollectionMapperFactory { - /** - * Singleton instance - */ - private static final CollectionMapperFactory INSTANCE = new CollectionMapperFactory(); + /** + * Singleton instance + */ + private static final CollectionMapperFactory INSTANCE = new CollectionMapperFactory(); - /** - * Cache of previously produced Mappers, so they can be reused for similar - * field declarations of an entity - */ - private Cache cache; + /** + * Cache of previously produced Mappers, so they can be reused for similar field declarations of + * an entity + */ + private Cache cache; - /** - * A lock for preventing multiple threads creating Mappers simultaneously - */ - private Lock lock; + /** + * A lock for preventing multiple threads creating Mappers simultaneously + */ + private Lock lock; - /** - * Creates a new instance of CollectionMapperFactory. - */ - private CollectionMapperFactory() { - cache = new Cache<>(); - lock = new ReentrantLock(); - } + /** + * Creates a new instance of CollectionMapperFactory. + */ + private CollectionMapperFactory() { + cache = new Cache<>(); + lock = new ReentrantLock(); + } - /** - * Returns the singleton instance of this class. - * - * @return the singleton instance of this class. - */ - public static CollectionMapperFactory getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance of this class. + * + * @return the singleton instance of this class. + */ + public static CollectionMapperFactory getInstance() { + return INSTANCE; + } - /** - * Returns the Mapper for the given field. If a Mapper exists in the cache - * that can map the given field, the cached Mapper will be returned. - * Otherwise, a new Mapper is created and returned. - * - * @param field - * the field of an entity for which a Mapper is to be produced. - * @return A Mapper to handle the mapping of the field. - */ - public Mapper getMapper(Field field) { - Type genericType = field.getGenericType(); - Property propertyAnnotation = field.getAnnotation(Property.class); - boolean indexed = true; - if (propertyAnnotation != null) { - indexed = propertyAnnotation.indexed(); - } - String cacheKey = computeCacheKey(genericType, indexed); - Mapper mapper = cache.get(cacheKey); - if (mapper == null) { - mapper = createMapper(field, indexed); - } - return mapper; + /** + * Returns the Mapper for the given field. If a Mapper exists in the cache that can map the given + * field, the cached Mapper will be returned. Otherwise, a new Mapper is created and returned. + * + * @param field + * the field of an entity for which a Mapper is to be produced. + * @return A Mapper to handle the mapping of the field. + */ + public Mapper getMapper(Field field) { + Type genericType = field.getGenericType(); + Property propertyAnnotation = field.getAnnotation(Property.class); + boolean indexed = true; + if (propertyAnnotation != null) { + indexed = propertyAnnotation.indexed(); + } + String cacheKey = computeCacheKey(genericType, indexed); + Mapper mapper = cache.get(cacheKey); + if (mapper == null) { + mapper = createMapper(field, indexed); + } + return mapper; - } + } - /** - * Creates a new Mapper for the given field. - * - * @param field - * the field - * @param indexed - * whether or not the field is to be indexed - * @return the Mapper - */ - private Mapper createMapper(Field field, boolean indexed) { - lock.lock(); - try { - Mapper mapper; - Class fieldType = field.getType(); - Type genericType = field.getGenericType(); - String cacheKey = computeCacheKey(genericType, indexed); - mapper = cache.get(cacheKey); - if (mapper != null) { - return mapper; - } - if (List.class.isAssignableFrom(fieldType)) { - mapper = new ListMapper(genericType, indexed); - } else if (Set.class.isAssignableFrom(fieldType)) { - mapper = new SetMapper(genericType, indexed); - } else { - // we shouldn't be getting here - throw new IllegalArgumentException( - String.format("Field type must be List or Set, found %s", fieldType)); - } - cache.put(cacheKey, mapper); - return mapper; - } finally { - lock.unlock(); - } - } + /** + * Creates a new Mapper for the given field. + * + * @param field + * the field + * @param indexed + * whether or not the field is to be indexed + * @return the Mapper + */ + private Mapper createMapper(Field field, boolean indexed) { + lock.lock(); + try { + Mapper mapper; + Class fieldType = field.getType(); + Type genericType = field.getGenericType(); + String cacheKey = computeCacheKey(genericType, indexed); + mapper = cache.get(cacheKey); + if (mapper != null) { + return mapper; + } + if (List.class.isAssignableFrom(fieldType)) { + mapper = new ListMapper(genericType, indexed); + } else if (Set.class.isAssignableFrom(fieldType)) { + mapper = new SetMapper(genericType, indexed); + } else { + // we shouldn't be getting here + throw new IllegalArgumentException( + String.format("Field type must be List or Set, found %s", fieldType)); + } + cache.put(cacheKey, mapper); + return mapper; + } finally { + lock.unlock(); + } + } - /** - * Returns the cache key. - * - * @param type - * the type - * @param indexed - * whether or not the property is indexed - * @return the cache key - */ - private String computeCacheKey(Type type, boolean indexed) { - return type.toString() + "-" + indexed; - } + /** + * Returns the cache key. + * + * @param type + * the type + * @param indexed + * whether or not the property is indexed + * @return the cache key + */ + private static String computeCacheKey(Type type, boolean indexed) { + return type.toString() + "-" + indexed; + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/DateMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/DateMapper.java index a0df437..1ebb9b9 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/DateMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/DateMapper.java @@ -28,37 +28,38 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping Dates to/from Cloud - * Datastore. Date objects are mapped to DateTime type in the Cloud Datastore. - * The values are stored with a maximum precision of milliseconds. + * An implementation of {@link Mapper} for mapping Dates to/from Cloud Datastore. Date objects are + * mapped to DateTime type in the Cloud Datastore. The values are stored with a maximum precision of + * milliseconds. * * @author Sai Pullabhotla * */ public class DateMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return TimestampValue.newBuilder(Timestamp.of((Date) input)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return TimestampValue.newBuilder(Timestamp.of((Date) input)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - Timestamp ts = ((TimestampValue) input).get(); - long millis = TimeUnit.SECONDS.toMillis(ts.getSeconds()) + TimeUnit.NANOSECONDS.toMillis(ts.getNanos()); - return new Date(millis); - } catch (ClassCastException exp) { - String pattern = "Expecting %s, but found %s"; - throw new MappingException( - String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + Timestamp ts = ((TimestampValue) input).get(); + long millis = TimeUnit.SECONDS.toMillis(ts.getSeconds()) + + TimeUnit.NANOSECONDS.toMillis(ts.getNanos()); + return new Date(millis); + } catch (ClassCastException exp) { + String pattern = "Expecting %s, but found %s"; + throw new MappingException( + String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/DecimalMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/DecimalMapper.java index aebe5db..feb246e 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/DecimalMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/DecimalMapper.java @@ -26,121 +26,120 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} to map BigDecimal types to Integer fields - * to/from the Cloud Datastore. The primary purpose of this Mapper is to - * workaround the lack of Decimal (aka Numeric) type in Cloud Datastore. Cloud - * Datastore does support Integer and Floating Point numbers, but storing - * decimal data (e.g. Currency) as floating point would result in loss of - * precision. This Mapper takes care of this issue by mapping decimal data to an - * integer field. + * An implementation of {@link Mapper} to map BigDecimal types to Integer fields to/from the Cloud + * Datastore. The primary purpose of this Mapper is to workaround the lack of Decimal (aka Numeric) + * type in Cloud Datastore. Cloud Datastore does support Integer and Floating Point numbers, but + * storing decimal data (e.g. Currency) as floating point would result in loss of precision. This + * Mapper takes care of this issue by mapping decimal data to an integer field. * * @author Sai Pullabhotla * */ public class DecimalMapper implements Mapper { - /** - * Max precision - */ - private static final int MAX_PRECISION = 18; + /** + * Max precision + */ + private static final int MAX_PRECISION = 18; - /** - * Precision - */ - private final int precision; + /** + * Precision + */ + private final int precision; - /** - * Scale - */ - private final int scale; + /** + * Scale + */ + private final int scale; - /** - * Creates a new instance of DecimalMapper to map decimal - * values of given precision and scale. - * - * @param precision - * the precision (total number of digits before and after the - * decimal) - * @param scale - * the scale (number of digits after the decimal) - */ - public DecimalMapper(int precision, int scale) { - if (precision <= 0 || precision > MAX_PRECISION) { - throw new IllegalArgumentException(String.format("precision must be between %d and %d", 1, MAX_PRECISION)); - } - if (scale < 0 || scale > precision) { - throw new IllegalArgumentException( - String.format("scale must be between %d and precision (%d)", 0, precision)); - } - this.precision = precision; - this.scale = scale; - } + /** + * Creates a new instance of DecimalMapper to map decimal values of given precision + * and scale. + * + * @param precision + * the precision (total number of digits before and after the decimal) + * @param scale + * the scale (number of digits after the decimal) + */ + public DecimalMapper(int precision, int scale) { + if (precision <= 0 || precision > MAX_PRECISION) { + throw new IllegalArgumentException( + String.format("precision must be between %d and %d", 1, MAX_PRECISION)); + } + if (scale < 0 || scale > precision) { + throw new IllegalArgumentException( + String.format("scale must be between %d and precision (%d)", 0, precision)); + } + this.precision = precision; + this.scale = scale; + } - /** - * Returns the precision. - * - * @return the precision - */ - public int getPrecision() { - return precision; - } + /** + * Returns the precision. + * + * @return the precision + */ + public int getPrecision() { + return precision; + } - /** - * Returns the scale. - * - * @return the scale - */ - public int getScale() { - return scale; - } + /** + * Returns the scale. + * + * @return the scale + */ + public int getScale() { + return scale; + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - BigDecimal original = null; - try { - original = (BigDecimal) input; - // Ensure we fix the scale, yes we don't round anything up or down. - // It is the responsibility of the API user. We only set the scale - // to zero fill any unused fractional digits, or remove any zeroes - // from the end. This helps us validate the precision and ensure - // that the number is within the expected bounds. Any better ways? - BigDecimal n = original.setScale(scale); - if (n.precision() > precision) { - throw new MappingException(String.format("Value %s is not a valid Decimal(%d, %d)", - original.toPlainString(), precision, scale)); - } - n = n.movePointRight(scale); - return LongValue.newBuilder(n.longValueExact()); - } catch (MappingException exp) { - throw exp; - } catch (Exception exp) { - Object arg1 = original == null ? input : original.toPlainString(); - throw new MappingException(String.format("Value %s is not a valid Decimal(%d, %d)", arg1, precision, scale), - exp); - } - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + BigDecimal original = null; + try { + original = (BigDecimal) input; + // Ensure we fix the scale, yes we don't round anything up or down. + // It is the responsibility of the API user. We only set the scale + // to zero fill any unused fractional digits, or remove any zeroes + // from the end. This helps us validate the precision and ensure + // that the number is within the expected bounds. Any better ways? + BigDecimal n = original.setScale(scale); + if (n.precision() > precision) { + throw new MappingException(String.format("Value %s is not a valid Decimal(%d, %d)", + original.toPlainString(), precision, scale)); + } + n = n.movePointRight(scale); + return LongValue.newBuilder(n.longValueExact()); + } catch (MappingException exp) { + throw exp; + } catch (Exception exp) { + Object arg1 = original == null ? input : original.toPlainString(); + throw new MappingException( + String.format("Value %s is not a valid Decimal(%d, %d)", arg1, precision, scale), exp); + } + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - BigDecimal n = new BigDecimal(((LongValue) input).get()); - if (n.precision() > precision) { - throw new MappingException( - String.format("Cannot map %s to Decimal(%d, %d). Value is larger than the defined precision. ", - n.toPlainString(), precision, scale)); - } - return n.movePointLeft(scale); - } catch (MappingException exp) { - throw exp; - } catch (Exception exp) { - throw new MappingException(String.format("Cannot map %s to Decimal(%d, %d", input, precision, scale), exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + BigDecimal n = new BigDecimal(((LongValue) input).get()); + if (n.precision() > precision) { + throw new MappingException(String.format( + "Cannot map %s to Decimal(%d, %d). Value is larger than the defined precision. ", + n.toPlainString(), precision, scale)); + } + return n.movePointLeft(scale); + } catch (MappingException exp) { + throw exp; + } catch (Exception exp) { + throw new MappingException( + String.format("Cannot map %s to Decimal(%d, %d", input, precision, scale), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/DoubleMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/DoubleMapper.java index 495a3e7..65c6d22 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/DoubleMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/DoubleMapper.java @@ -23,28 +23,28 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper double - * types to/from Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper double types to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class DoubleMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return DoubleValue.newBuilder((double) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return DoubleValue.newBuilder((double) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((DoubleValue) input).get(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((DoubleValue) input).get(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/EmbeddedObjectMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/EmbeddedObjectMapper.java index f5a9626..7d13256 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/EmbeddedObjectMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/EmbeddedObjectMapper.java @@ -39,78 +39,80 @@ */ public class EmbeddedObjectMapper implements Mapper { - /** - * The Embeddable class. - */ - private final Class clazz; + /** + * The Embeddable class. + */ + private final Class clazz; - /** - * Metadata of the Embeddable class. - */ - private final EmbeddableMetadata metadata; + /** + * Metadata of the Embeddable class. + */ + private final EmbeddableMetadata metadata; - /** - * Creates a new instance of EmbeddedObjectMapper. - * - * @param clazz - * the Embeddable class - */ - public EmbeddedObjectMapper(Class clazz) { - this.clazz = clazz; - this.metadata = EmbeddableIntrospector.introspect(clazz); - } + /** + * Creates a new instance of EmbeddedObjectMapper. + * + * @param clazz + * the Embeddable class + */ + public EmbeddedObjectMapper(Class clazz) { + this.clazz = clazz; + this.metadata = EmbeddableIntrospector.introspect(clazz); + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - try { - FullEntity.Builder entityBuilder = FullEntity.newBuilder(); - for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) { - Object propertyValue = propertyMetadata.getReadMethod().invoke(input); - if (propertyValue == null && propertyMetadata.isOptional()) { - continue; - } - ValueBuilder valueBuilder = propertyMetadata.getMapper().toDatastore(propertyValue); - valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); - Value value = valueBuilder.build(); - entityBuilder.set(propertyMetadata.getMappedName(), value); - Indexer indexer = propertyMetadata.getSecondaryIndexer(); - if (indexer != null) { - entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(value)); - } - } - return EntityValue.newBuilder(entityBuilder.build()); - } catch (Throwable exp) { - throw new MappingException(exp); - } - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + try { + FullEntity.Builder entityBuilder = FullEntity.newBuilder(); + for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) { + Object propertyValue = propertyMetadata.getReadMethod().invoke(input); + if (propertyValue == null && propertyMetadata.isOptional()) { + continue; + } + ValueBuilder valueBuilder = propertyMetadata.getMapper() + .toDatastore(propertyValue); + valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); + Value value = valueBuilder.build(); + entityBuilder.set(propertyMetadata.getMappedName(), value); + Indexer indexer = propertyMetadata.getSecondaryIndexer(); + if (indexer != null) { + entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(value)); + } + } + return EntityValue.newBuilder(entityBuilder.build()); + } catch (Throwable exp) { + throw new MappingException(exp); + } + } - @Override - public Object toModel(Value input) { - if (input.getType() == ValueType.NULL) { - return null; - } - try { - FullEntity entity = ((EntityValue) input).get(); - ConstructorMetadata constructorMetadata = metadata.getConstructorMetadata(); - Object embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); - for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) { - String mappedName = propertyMetadata.getMappedName(); - if (entity.contains(mappedName)) { - Value propertyValue = entity.getValue(mappedName); - Object fieldValue = propertyMetadata.getMapper().toModel(propertyValue); - propertyMetadata.getWriteMethod().invoke(embeddedObject, fieldValue); - } - } - if (constructorMetadata.isBuilderConstructionStrategy()) { - embeddedObject = metadata.getConstructorMetadata().getBuildMethodHandle().invoke(embeddedObject); - } - return embeddedObject; - } catch (Throwable exp) { - throw new MappingException(exp); - } - } + @Override + public Object toModel(Value input) { + if (input.getType() == ValueType.NULL) { + return null; + } + try { + FullEntity entity = ((EntityValue) input).get(); + ConstructorMetadata constructorMetadata = metadata.getConstructorMetadata(); + Object embeddedObject = constructorMetadata.getConstructorMethodHandle().invoke(); + for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) { + String mappedName = propertyMetadata.getMappedName(); + if (entity.contains(mappedName)) { + Value propertyValue = entity.getValue(mappedName); + Object fieldValue = propertyMetadata.getMapper().toModel(propertyValue); + propertyMetadata.getWriteMethod().invoke(embeddedObject, fieldValue); + } + } + if (constructorMetadata.isBuilderConstructionStrategy()) { + embeddedObject = metadata.getConstructorMetadata().getBuildMethodHandle() + .invoke(embeddedObject); + } + return embeddedObject; + } catch (Throwable exp) { + throw new MappingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/EnumMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/EnumMapper.java index 835c9fd..036ce13 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/EnumMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/EnumMapper.java @@ -23,47 +23,46 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping Enum types to/from Cloud - * Datastore. + * An implementation of {@link Mapper} for mapping Enum types to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class EnumMapper implements Mapper { - /** - * Enum class - */ - @SuppressWarnings("rawtypes") - private Class enumClass; + /** + * Enum class + */ + @SuppressWarnings("rawtypes") + private Class enumClass; - /** - * Creates a new instance of EnumMapper. - * - * @param enumClass - * the enum class - */ - @SuppressWarnings("rawtypes") - public EnumMapper(Class enumClass) { - this.enumClass = enumClass; - } + /** + * Creates a new instance of EnumMapper. + * + * @param enumClass + * the enum class + */ + @SuppressWarnings("rawtypes") + public EnumMapper(Class enumClass) { + this.enumClass = enumClass; + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(input.toString()); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(input.toString()); + } - @SuppressWarnings("unchecked") - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - String value = ((StringValue) input).get(); - return Enum.valueOf(enumClass, value); - } + @SuppressWarnings("unchecked") + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + String value = ((StringValue) input).get(); + return Enum.valueOf(enumClass, value); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/FloatMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/FloatMapper.java index 0321cc7..8163512 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/FloatMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/FloatMapper.java @@ -24,33 +24,33 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper Float - * types to/from Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper Float types to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class FloatMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return DoubleValue.newBuilder((float) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return DoubleValue.newBuilder((float) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - DoubleValue value = (DoubleValue) input; - Double d = value.get(); - if (d < -Float.MAX_VALUE || d > Float.MAX_VALUE) { - throw new MappingException(String.format("Value %s is out of range for float type", d)); - } - return d.floatValue(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + DoubleValue value = (DoubleValue) input; + Double d = value.get(); + if (d < -Float.MAX_VALUE || d > Float.MAX_VALUE) { + throw new MappingException(String.format("Value %s is out of range for float type", d)); + } + return d.floatValue(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/GeoLocationMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/GeoLocationMapper.java index c04d583..8dfff18 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/GeoLocationMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/GeoLocationMapper.java @@ -25,31 +25,31 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping GeoLocation (a.k.a GeoPoint) - * type to/from Cloud Datastore. + * An implementation of {@link Mapper} for mapping GeoLocation (a.k.a GeoPoint) type to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class GeoLocationMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - GeoLocation geoLocation = (GeoLocation) input; - return LatLngValue.newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude())); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + GeoLocation geoLocation = (GeoLocation) input; + return LatLngValue.newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude())); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - LatLngValue value = (LatLngValue) input; - LatLng coordinates = value.get(); - return new GeoLocation(coordinates.getLatitude(), coordinates.getLongitude()); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + LatLngValue value = (LatLngValue) input; + LatLng coordinates = value.get(); + return new GeoLocation(coordinates.getLatitude(), coordinates.getLongitude()); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/IntegerMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/IntegerMapper.java index b03bdd0..7d56526 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/IntegerMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/IntegerMapper.java @@ -24,32 +24,32 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper integer - * types to/from Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper integer types to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class IntegerMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return LongValue.newBuilder((int) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return LongValue.newBuilder((int) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - Long l = ((LongValue) input).get(); - if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { - throw new MappingException(String.format("Value %d is out of range for integer type", l)); - } - return l.intValue(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + Long l = ((LongValue) input).get(); + if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { + throw new MappingException(String.format("Value %d is out of range for integer type", l)); + } + return l.intValue(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/KeyMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/KeyMapper.java index 3fc08aa..7962f44 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/KeyMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/KeyMapper.java @@ -25,30 +25,29 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping Key types to/from the Cloud - * Datastore. + * An implementation of {@link Mapper} for mapping Key types to/from the Cloud Datastore. * * @author Sai Pullabhotla * */ public class KeyMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - DatastoreKey datastoreKey = (DatastoreKey) input; - return KeyValue.newBuilder(datastoreKey.nativeKey()); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + DatastoreKey datastoreKey = (DatastoreKey) input; + return KeyValue.newBuilder(datastoreKey.nativeKey()); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - KeyValue keyValue = (KeyValue) input; - return new DefaultDatastoreKey(keyValue.get()); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + KeyValue keyValue = (KeyValue) input; + return new DefaultDatastoreKey(keyValue.get()); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/ListMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/ListMapper.java index 836c1de..0869fb7 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/ListMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/ListMapper.java @@ -31,102 +31,102 @@ import com.jmethods.catatumbo.impl.IntrospectionUtils; /** - * An implementation of {@link Mapper} for mapping {@link List} types to/from - * the Cloud Datastore. + * An implementation of {@link Mapper} for mapping {@link List} types to/from the Cloud Datastore. * * @author Sai Pullabhotla * */ public class ListMapper implements Mapper { - /** - * List type - could be a Class or a Parameterized type - */ - private Type listType; + /** + * List type - could be a Class or a Parameterized type + */ + private Type listType; - /** - * List class - */ - private Class listClass; + /** + * List class + */ + private Class listClass; - /** - * Class of items in the list - */ - private Class itemClass; + /** + * Class of items in the list + */ + private Class itemClass; - /** - * Mapper for mapping items in the list - */ - private Mapper itemMapper; + /** + * Mapper for mapping items in the list + */ + private Mapper itemMapper; - /** - * Whether or not the list property should be indexed. While this does not - * affect the ListProperty itself, it is applied on the items in the list. - */ - private boolean indexed; + /** + * Whether or not the list property should be indexed. While this does not affect the ListProperty + * itself, it is applied on the items in the list. + */ + private boolean indexed; - /** - * Creates a new instance of ListMapper. - * - * @param type - * the list type - * @param indexed - * whether or not the property should be indexed - */ - public ListMapper(Type type, boolean indexed) { - this.listType = type; - this.indexed = indexed; - Class[] classArray = IntrospectionUtils.resolveCollectionType(listType); - listClass = classArray[0]; - itemClass = classArray[1]; - initializeMapper(); - } + /** + * Creates a new instance of ListMapper. + * + * @param type + * the list type + * @param indexed + * whether or not the property should be indexed + */ + public ListMapper(Type type, boolean indexed) { + this.listType = type; + this.indexed = indexed; + Class[] classArray = IntrospectionUtils.resolveCollectionType(listType); + listClass = classArray[0]; + itemClass = classArray[1]; + initializeMapper(); + } - /** - * Initializes the mapper for items in the List. - */ - private void initializeMapper() { - if (itemClass == null) { - itemMapper = CatchAllMapper.getInstance(); - } else { - try { - itemMapper = MapperFactory.getInstance().getMapper(itemClass); - } catch (NoSuitableMapperException exp) { - itemMapper = CatchAllMapper.getInstance(); - } - } - } + /** + * Initializes the mapper for items in the List. + */ + private void initializeMapper() { + if (itemClass == null) { + itemMapper = CatchAllMapper.getInstance(); + } else { + try { + itemMapper = MapperFactory.getInstance().getMapper(itemClass); + } catch (NoSuitableMapperException exp) { + itemMapper = CatchAllMapper.getInstance(); + } + } + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - List list = (List) input; - ListValue.Builder listValueBuilder = ListValue.newBuilder(); - for (Object item : list) { - listValueBuilder.addValue(itemMapper.toDatastore(item).setExcludeFromIndexes(!indexed).build()); - } - return listValueBuilder; - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + List list = (List) input; + ListValue.Builder listValueBuilder = ListValue.newBuilder(); + for (Object item : list) { + listValueBuilder + .addValue(itemMapper.toDatastore(item).setExcludeFromIndexes(!indexed).build()); + } + return listValueBuilder; + } - @SuppressWarnings("unchecked") - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - List> list = ((ListValue) input).get(); - List output; - if (Modifier.isAbstract(listClass.getModifiers())) { - output = new ArrayList<>(); - } else { - output = (List) IntrospectionUtils.instantiateObject(listClass); - } - for (Value item : list) { - output.add(itemMapper.toModel(item)); - } - return output; - } + @SuppressWarnings("unchecked") + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + List> list = ((ListValue) input).get(); + List output; + if (Modifier.isAbstract(listClass.getModifiers())) { + output = new ArrayList<>(); + } else { + output = (List) IntrospectionUtils.instantiateObject(listClass); + } + for (Value item : list) { + output.add(itemMapper.toModel(item)); + } + return output; + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/LocalDateMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/LocalDateMapper.java index f8629cd..394fe10 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/LocalDateMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/LocalDateMapper.java @@ -26,35 +26,34 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping {@link LocalDate} to/from - * Cloud Datastore. {@link LocalDate} types are mapped to String type in the - * Cloud Datastore. + * An implementation of {@link Mapper} for mapping {@link LocalDate} to/from Cloud Datastore. + * {@link LocalDate} types are mapped to String type in the Cloud Datastore. * * @author Sai Pullabhotla * */ public class LocalDateMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(input.toString()); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(input.toString()); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - return LocalDate.parse(((StringValue) input).get()); - } catch (ClassCastException exp) { - String pattern = "Mapping of type %s to %s is not supported"; - throw new MappingException(String.format(pattern, input.getClass().getName(), LocalDate.class.getName()), - exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + return LocalDate.parse(((StringValue) input).get()); + } catch (ClassCastException exp) { + String pattern = "Mapping of type %s to %s is not supported"; + throw new MappingException( + String.format(pattern, input.getClass().getName(), LocalDate.class.getName()), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/LocalDateTimeMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/LocalDateTimeMapper.java index 7812e8e..ebfe417 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/LocalDateTimeMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/LocalDateTimeMapper.java @@ -29,45 +29,44 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping {@link LocalDateTime} to/from - * Cloud Datastore. {@link LocalDateTime} types are mapped to String type in the - * Cloud Datastore. {@link LocalDateTime} objects are persisted into the - * datastore with a nano-second precision in the - * uuuu-MM-dd'T'HH:mm:ss.nnnnnnnnn format. + * An implementation of {@link Mapper} for mapping {@link LocalDateTime} to/from Cloud Datastore. + * {@link LocalDateTime} types are mapped to String type in the Cloud Datastore. + * {@link LocalDateTime} objects are persisted into the datastore with a nano-second precision in + * the uuuu-MM-dd'T'HH:mm:ss.nnnnnnnnn format. * * @author Sai Pullabhotla * */ public class LocalDateTimeMapper implements Mapper { - /** - * The formatter to use for converting LocalTime to String and vice versa. - */ - public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.nnnnnnnnn", - Locale.ENGLISH); + /** + * The formatter to use for converting LocalTime to String and vice versa. + */ + public static final DateTimeFormatter FORMATTER = DateTimeFormatter + .ofPattern("uuuu-MM-dd'T'HH:mm:ss.nnnnnnnnn", Locale.ENGLISH); - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(((LocalDateTime) input).format(FORMATTER)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(((LocalDateTime) input).format(FORMATTER)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - return LocalDateTime.parse(((StringValue) input).get(), FORMATTER); - } catch (ClassCastException exp) { - String pattern = "Mapping of type %s to %s is not supported"; - throw new MappingException( - String.format(pattern, input.getClass().getName(), LocalDateTime.class.getName()), exp); - } catch (DateTimeParseException exp) { - throw new MappingException(exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + return LocalDateTime.parse(((StringValue) input).get(), FORMATTER); + } catch (ClassCastException exp) { + String pattern = "Mapping of type %s to %s is not supported"; + throw new MappingException( + String.format(pattern, input.getClass().getName(), LocalDateTime.class.getName()), exp); + } catch (DateTimeParseException exp) { + throw new MappingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/LocalTimeMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/LocalTimeMapper.java index 42452c1..5f60ad8 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/LocalTimeMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/LocalTimeMapper.java @@ -29,43 +29,44 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping {@link LocalTime} to/from - * Cloud Datastore. {@link LocalTime} types are mapped to String type in the - * Cloud Datastore. {@link LocalTime} objects are persisted into the datastore - * with a nano-second precision in the HH:mm:ss.nnnnnnnnn format. + * An implementation of {@link Mapper} for mapping {@link LocalTime} to/from Cloud Datastore. + * {@link LocalTime} types are mapped to String type in the Cloud Datastore. {@link LocalTime} + * objects are persisted into the datastore with a nano-second precision in the + * HH:mm:ss.nnnnnnnnn format. * * @author Sai Pullabhotla * */ public class LocalTimeMapper implements Mapper { - /** - * The formatter to use for converting LocalTime to String and vice versa. - */ - public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.nnnnnnnnn", Locale.ENGLISH); + /** + * The formatter to use for converting LocalTime to String and vice versa. + */ + public static final DateTimeFormatter FORMATTER = DateTimeFormatter + .ofPattern("HH:mm:ss.nnnnnnnnn", Locale.ENGLISH); - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder(((LocalTime) input).format(FORMATTER)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder(((LocalTime) input).format(FORMATTER)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - return LocalTime.parse(((StringValue) input).get(), FORMATTER); - } catch (ClassCastException exp) { - String pattern = "Mapping of type %s to %s is not supported"; - throw new MappingException(String.format(pattern, input.getClass().getName(), LocalTime.class.getName()), - exp); - } catch (DateTimeParseException exp) { - throw new MappingException(exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + return LocalTime.parse(((StringValue) input).get(), FORMATTER); + } catch (ClassCastException exp) { + String pattern = "Mapping of type %s to %s is not supported"; + throw new MappingException( + String.format(pattern, input.getClass().getName(), LocalTime.class.getName()), exp); + } catch (DateTimeParseException exp) { + throw new MappingException(exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/LongMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/LongMapper.java index 7618ba6..960041c 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/LongMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/LongMapper.java @@ -23,28 +23,28 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper and - * Long types to/from the Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper and Long types to/from the + * Cloud Datastore. * * @author Sai Pullabhotla * */ public class LongMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return LongValue.newBuilder((long) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return LongValue.newBuilder((long) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((LongValue) input).get(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((LongValue) input).get(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/MapMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/MapMapper.java index 2828efa..6cb1eb4 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/MapMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/MapMapper.java @@ -36,112 +36,113 @@ import com.jmethods.catatumbo.impl.IntrospectionUtils; /** - * An implementation of {@link Mapper} interface for mapping {@link Map} types - * to/from Cloud Datastore. + * An implementation of {@link Mapper} interface for mapping {@link Map} types to/from Cloud + * Datastore. * * @author Sai Pullabhotla * */ public class MapMapper implements Mapper { - /** - * Map Type - */ - private Type mapType; - - /** - * Class of Map - */ - private Class mapClass; - - /** - * Type of Keys in the map - */ - private Class keyClass; - - /** - * Type of Values in the Map - */ - private Class valueClass; - - /** - * A Mapper for mapping the Values of the map - */ - private Mapper valueMapper; - - /** - * Creates a new instance of MapMapper. - * - * @param type - * the type of Map - */ - public MapMapper(Type type) { - this.mapType = type; - Class[] classArray = IntrospectionUtils.resolveMapType(mapType); - mapClass = classArray[0]; - keyClass = classArray[1] == null ? String.class : classArray[1]; - if (!(keyClass.equals(String.class))) { - throw new MappingException(String.format("Unsupported type %s for Map's key. Keys must be of type %s", - keyClass.getName(), String.class.getName())); - } - valueClass = classArray[2]; - initializeMapper(); - - } - - /** - * Initializes the mapper for values in the Map. - */ - private void initializeMapper() { - if (valueClass == null) { - valueMapper = CatchAllMapper.getInstance(); - } else { - try { - valueMapper = MapperFactory.getInstance().getMapper(valueClass); - } catch (NoSuitableMapperException exp) { - valueMapper = CatchAllMapper.getInstance(); - } - - } - } - - @SuppressWarnings("unchecked") - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - Map map = (Map) input; - FullEntity.Builder entityBuilder = FullEntity.newBuilder(); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - entityBuilder.set(key, valueMapper.toDatastore(entry.getValue()).build()); - } - return EntityValue.newBuilder(entityBuilder.build()); - } - - @SuppressWarnings("unchecked") - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - EntityValue entityValue = (EntityValue) input; - FullEntity entity = entityValue.get(); - Map map; - if (Modifier.isAbstract(mapClass.getModifiers())) { - if (SortedMap.class.equals(mapClass)) { - map = new TreeMap<>(); - } else { - map = new HashMap<>(); - } - } else { - map = (Map) IntrospectionUtils.instantiateObject(mapClass); - } - for (String property : entity.getNames()) { - map.put(property, valueMapper.toModel(entity.getValue(property))); - } - return map; - } + /** + * Map Type + */ + private Type mapType; + + /** + * Class of Map + */ + private Class mapClass; + + /** + * Type of Keys in the map + */ + private Class keyClass; + + /** + * Type of Values in the Map + */ + private Class valueClass; + + /** + * A Mapper for mapping the Values of the map + */ + private Mapper valueMapper; + + /** + * Creates a new instance of MapMapper. + * + * @param type + * the type of Map + */ + public MapMapper(Type type) { + this.mapType = type; + Class[] classArray = IntrospectionUtils.resolveMapType(mapType); + mapClass = classArray[0]; + keyClass = classArray[1] == null ? String.class : classArray[1]; + if (!(keyClass.equals(String.class))) { + throw new MappingException( + String.format("Unsupported type %s for Map's key. Keys must be of type %s", + keyClass.getName(), String.class.getName())); + } + valueClass = classArray[2]; + initializeMapper(); + + } + + /** + * Initializes the mapper for values in the Map. + */ + private void initializeMapper() { + if (valueClass == null) { + valueMapper = CatchAllMapper.getInstance(); + } else { + try { + valueMapper = MapperFactory.getInstance().getMapper(valueClass); + } catch (NoSuitableMapperException exp) { + valueMapper = CatchAllMapper.getInstance(); + } + + } + } + + @SuppressWarnings("unchecked") + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + Map map = (Map) input; + FullEntity.Builder entityBuilder = FullEntity.newBuilder(); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + entityBuilder.set(key, valueMapper.toDatastore(entry.getValue()).build()); + } + return EntityValue.newBuilder(entityBuilder.build()); + } + + @SuppressWarnings("unchecked") + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + EntityValue entityValue = (EntityValue) input; + FullEntity entity = entityValue.get(); + Map map; + if (Modifier.isAbstract(mapClass.getModifiers())) { + if (SortedMap.class.equals(mapClass)) { + map = new TreeMap<>(); + } else { + map = new HashMap<>(); + } + } else { + map = (Map) IntrospectionUtils.instantiateObject(mapClass); + } + for (String property : entity.getNames()) { + map.put(property, valueMapper.toModel(entity.getValue(property))); + } + return map; + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapper.java index d010b3e..969103a 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapper.java @@ -30,43 +30,43 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping {@link OffsetDateTime} - * to/from Cloud Datastore. {@link OffsetDateTime} types are mapped to DateTime - * type in the Cloud Datastore. This maximum precision is capped to Microseconds - * to match with what the Datastore supports. + * An implementation of {@link Mapper} for mapping {@link OffsetDateTime} to/from Cloud Datastore. + * {@link OffsetDateTime} types are mapped to DateTime type in the Cloud Datastore. This maximum + * precision is capped to Microseconds to match with what the Datastore supports. * * @author Sai Pullabhotla * */ public class OffsetDateTimeMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - OffsetDateTime offsetDateTime = (OffsetDateTime) input; - long seconds = offsetDateTime.toEpochSecond(); - int nanos = offsetDateTime.getNano(); - long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); - return TimestampValue.newBuilder(Timestamp.ofTimeMicroseconds(microseconds)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + OffsetDateTime offsetDateTime = (OffsetDateTime) input; + long seconds = offsetDateTime.toEpochSecond(); + int nanos = offsetDateTime.getNano(); + long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); + return TimestampValue.newBuilder(Timestamp.ofTimeMicroseconds(microseconds)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - Timestamp ts = ((TimestampValue) input).get(); - long seconds = ts.getSeconds(); - int nanos = ts.getNanos(); - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), ZoneId.systemDefault()); - } catch (ClassCastException exp) { - String pattern = "Expecting %s, but found %s"; - throw new MappingException( - String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + Timestamp ts = ((TimestampValue) input).get(); + long seconds = ts.getSeconds(); + int nanos = ts.getNanos(); + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), + ZoneId.systemDefault()); + } catch (ClassCastException exp) { + String pattern = "Expecting %s, but found %s"; + throw new MappingException( + String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/SetMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/SetMapper.java index 5e08338..34dc5a9 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/SetMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/SetMapper.java @@ -34,106 +34,106 @@ import com.jmethods.catatumbo.impl.IntrospectionUtils; /** - * An implementation of {@link Mapper} for mapping {@link Set} types to/from - * Cloud Datastore. + * An implementation of {@link Mapper} for mapping {@link Set} types to/from Cloud Datastore. * * @author Sai Pullabhotla * */ public class SetMapper implements Mapper { - /** - * Set type - could be a Class or a Parameterized type - */ - private Type setType; + /** + * Set type - could be a Class or a Parameterized type + */ + private Type setType; - /** - * Set class - */ - private Class setClass; + /** + * Set class + */ + private Class setClass; - /** - * Class of items in the Set - */ - private Class itemClass; + /** + * Class of items in the Set + */ + private Class itemClass; - /** - * Mapper for mapping items in the Set - */ - Mapper itemMapper; + /** + * Mapper for mapping items in the Set + */ + Mapper itemMapper; - /** - * Whether or not the list property should be indexed. While this does not - * affect the ListProperty itself, it is applied on the items in the list. - */ - private boolean indexed; + /** + * Whether or not the list property should be indexed. While this does not affect the ListProperty + * itself, it is applied on the items in the list. + */ + private boolean indexed; - /** - * Creates a new instance of SetMapper. - * - * @param type - * the type of Set - * @param indexed - * whether or not the property should be indexed - */ - public SetMapper(Type type, boolean indexed) { - this.setType = type; - this.indexed = indexed; - Class[] classArray = IntrospectionUtils.resolveCollectionType(setType); - setClass = classArray[0]; - itemClass = classArray[1]; - initializeMapper(); - } + /** + * Creates a new instance of SetMapper. + * + * @param type + * the type of Set + * @param indexed + * whether or not the property should be indexed + */ + public SetMapper(Type type, boolean indexed) { + this.setType = type; + this.indexed = indexed; + Class[] classArray = IntrospectionUtils.resolveCollectionType(setType); + setClass = classArray[0]; + itemClass = classArray[1]; + initializeMapper(); + } - /** - * Initializes the mapper for the items in the Set. - */ - private void initializeMapper() { - if (itemClass == null) { - itemMapper = CatchAllMapper.getInstance(); - } else { - try { - itemMapper = MapperFactory.getInstance().getMapper(itemClass); - } catch (NoSuitableMapperException exp) { - itemMapper = CatchAllMapper.getInstance(); - } - } - } + /** + * Initializes the mapper for the items in the Set. + */ + private void initializeMapper() { + if (itemClass == null) { + itemMapper = CatchAllMapper.getInstance(); + } else { + try { + itemMapper = MapperFactory.getInstance().getMapper(itemClass); + } catch (NoSuitableMapperException exp) { + itemMapper = CatchAllMapper.getInstance(); + } + } + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - Set set = (Set) input; - ListValue.Builder listValueBuilder = ListValue.newBuilder(); - for (Object item : set) { - listValueBuilder.addValue(itemMapper.toDatastore(item).setExcludeFromIndexes(!indexed).build()); - } - return listValueBuilder; - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + Set set = (Set) input; + ListValue.Builder listValueBuilder = ListValue.newBuilder(); + for (Object item : set) { + listValueBuilder + .addValue(itemMapper.toDatastore(item).setExcludeFromIndexes(!indexed).build()); + } + return listValueBuilder; + } - @SuppressWarnings("unchecked") - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - List> list = ((ListValue) input).get(); - Set output; - if (Modifier.isAbstract(setClass.getModifiers())) { - if (SortedSet.class.isAssignableFrom(setClass)) { - output = new TreeSet<>(); - } else { - output = new HashSet<>(); - } - } else { - output = (Set) IntrospectionUtils.instantiateObject(setClass); - } - for (Value item : list) { - output.add(itemMapper.toModel(item)); - } - return output; - } + @SuppressWarnings("unchecked") + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + List> list = ((ListValue) input).get(); + Set output; + if (Modifier.isAbstract(setClass.getModifiers())) { + if (SortedSet.class.isAssignableFrom(setClass)) { + output = new TreeSet<>(); + } else { + output = new HashSet<>(); + } + } else { + output = (Set) IntrospectionUtils.instantiateObject(setClass); + } + for (Value item : list) { + output.add(itemMapper.toModel(item)); + } + return output; + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/ShortMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/ShortMapper.java index 415e593..2b286fc 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/ShortMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/ShortMapper.java @@ -24,32 +24,32 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper Short - * types to/from the Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper Short types to/from the + * Cloud Datastore. * * @author Sai Pullabhotla * */ public class ShortMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return LongValue.newBuilder((short) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return LongValue.newBuilder((short) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - Long l = ((LongValue) input).get(); - if (l < Short.MIN_VALUE || l > Short.MAX_VALUE) { - throw new MappingException(String.format("Value %d is out of range for short type", l)); - } - return l.shortValue(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + Long l = ((LongValue) input).get(); + if (l < Short.MIN_VALUE || l > Short.MAX_VALUE) { + throw new MappingException(String.format("Value %d is out of range for short type", l)); + } + return l.shortValue(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/StringMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/StringMapper.java index a05002a..0de817c 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/StringMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/StringMapper.java @@ -23,28 +23,27 @@ import com.jmethods.catatumbo.Mapper; /** - * An implementation of {@link Mapper} for mapping String types to/from the - * Cloud Datastore. + * An implementation of {@link Mapper} for mapping String types to/from the Cloud Datastore. * * @author Sai Pullabhotla * */ public class StringMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return StringValue.newBuilder((String) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return StringValue.newBuilder((String) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - return ((StringValue) input).get(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + return ((StringValue) input).get(); + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapper.java b/src/main/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapper.java index 95b9a11..e4b0c59 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapper.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapper.java @@ -30,43 +30,42 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping {@link ZonedDateTime} to/from - * Cloud Datastore. {@link ZonedDateTime} types are mapped to DateTime type in - * the Cloud Datastore. This maximum precision is capped to Microseconds to - * match with what the Datastore supports. + * An implementation of {@link Mapper} for mapping {@link ZonedDateTime} to/from Cloud Datastore. + * {@link ZonedDateTime} types are mapped to DateTime type in the Cloud Datastore. This maximum + * precision is capped to Microseconds to match with what the Datastore supports. * * @author Sai Pullabhotla * */ public class ZonedDateTimeMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - ZonedDateTime zonedDateTime = (ZonedDateTime) input; - long seconds = zonedDateTime.toEpochSecond(); - int nanos = zonedDateTime.getNano(); - long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); - return TimestampValue.newBuilder(Timestamp.ofTimeMicroseconds(microseconds)); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + ZonedDateTime zonedDateTime = (ZonedDateTime) input; + long seconds = zonedDateTime.toEpochSecond(); + int nanos = zonedDateTime.getNano(); + long microseconds = TimeUnit.SECONDS.toMicros(seconds) + TimeUnit.NANOSECONDS.toMicros(nanos); + return TimestampValue.newBuilder(Timestamp.ofTimeMicroseconds(microseconds)); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - try { - Timestamp ts = ((TimestampValue) input).get(); - long seconds = ts.getSeconds(); - int nanos = ts.getNanos(); - return ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), ZoneId.systemDefault()); - } catch (ClassCastException exp) { - String pattern = "Expecting %s, but found %s"; - throw new MappingException( - String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); - } - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + try { + Timestamp ts = ((TimestampValue) input).get(); + long seconds = ts.getSeconds(); + int nanos = ts.getNanos(); + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), ZoneId.systemDefault()); + } catch (ClassCastException exp) { + String pattern = "Expecting %s, but found %s"; + throw new MappingException( + String.format(pattern, TimestampValue.class.getName(), input.getClass().getName()), exp); + } + } } diff --git a/src/main/java/com/jmethods/catatumbo/mappers/package-info.java b/src/main/java/com/jmethods/catatumbo/mappers/package-info.java index 59a708f..c0b16ce 100644 --- a/src/main/java/com/jmethods/catatumbo/mappers/package-info.java +++ b/src/main/java/com/jmethods/catatumbo/mappers/package-info.java @@ -15,7 +15,7 @@ */ /** - * Contains various mappers for mapping model fields to entity properties and - * vice versa. + * Contains various mappers for mapping model fields to entity properties and vice versa. */ + package com.jmethods.catatumbo.mappers; \ No newline at end of file diff --git a/src/main/java/com/jmethods/catatumbo/package-info.java b/src/main/java/com/jmethods/catatumbo/package-info.java index 22c6135..4f0eda5 100644 --- a/src/main/java/com/jmethods/catatumbo/package-info.java +++ b/src/main/java/com/jmethods/catatumbo/package-info.java @@ -15,39 +15,8 @@ */ /** - * This package contains the public API for mapping and persisting model objects - * to the Google Cloud Datastore and vice versa. Catatumbo provides the - * following annotations to take away the boilerplate code that is needed for - * persisting objects to the Google Cloud Datastore and mapping the Google Cloud - * Datastore entities to your model objects: - * - *
    - *
  • {@link com.jmethods.catatumbo.Entity}
  • - *
  • {@link com.jmethods.catatumbo.Identifier}
  • - *
  • {@link com.jmethods.catatumbo.Property}
  • - *
  • {@link com.jmethods.catatumbo.Key}
  • - *
  • {@link com.jmethods.catatumbo.ParentKey}
  • - *
  • {@link com.jmethods.catatumbo.MappedSuperClass}
  • - *
  • {@link com.jmethods.catatumbo.Embeddable}
  • - *
  • {@link com.jmethods.catatumbo.Embedded}
  • - *
  • {@link com.jmethods.catatumbo.PropertyOverrides}
  • - *
  • {@link com.jmethods.catatumbo.PropertyOverride}
  • - *
  • {@link com.jmethods.catatumbo.Ignore}
  • - *
  • {@link com.jmethods.catatumbo.Version}
  • - *
  • {@link com.jmethods.catatumbo.EntityListeners}
  • - *
  • {@link com.jmethods.catatumbo.EntityListener}
  • - *
  • {@link com.jmethods.catatumbo.ExcludeDefaultListeners}
  • - *
  • {@link com.jmethods.catatumbo.ExcludeSuperclassListeners}
  • - *
  • {@link com.jmethods.catatumbo.PreInsert}
  • - *
  • {@link com.jmethods.catatumbo.PostInsert}
  • - *
  • {@link com.jmethods.catatumbo.PreUpdate}
  • - *
  • {@link com.jmethods.catatumbo.PostUpdate}
  • - *
  • {@link com.jmethods.catatumbo.PreUpsert}
  • - *
  • {@link com.jmethods.catatumbo.PostUpsert}
  • - *
  • {@link com.jmethods.catatumbo.PreDelete}
  • - *
  • {@link com.jmethods.catatumbo.PostDelete}
  • - *
  • {@link com.jmethods.catatumbo.PostLoad}
  • - *
- * + * This package contains the public API for mapping and persisting model objects to the Google Cloud + * Datastore and vice versa. */ + package com.jmethods.catatumbo; \ No newline at end of file diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatBase.java b/src/main/java/com/jmethods/catatumbo/stats/StatBase.java index 994b0e6..068a506 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatBase.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatBase.java @@ -32,114 +32,111 @@ */ @MappedSuperClass public abstract class StatBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 6745596308816079953L; - - /** - * Key of this Statistic entity - */ - @Key - private DatastoreKey key; - - /** - * number of items, typically entities - */ - @Property(name = StatConstants.PROP_COUNT) - private long count; - - /** - * Size of items - */ - @Property(name = StatConstants.PROP_BYTES) - private long bytes; - - /** - * Timestamp when the statistics were generated - */ - @Property(name = StatConstants.PROP_TIMESTAMP) - private Date timestamp; - - /** - * Returns the full key of this Statistic entity. - * - * @return the full key of this Statistic entity. - */ - public DatastoreKey getKey() { - return key; - } - - /** - * Sets the full key of this Statistic entity. - * - * @param key - * the full key of this Statistic entity. - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * Returns the number of items (typically number of entities) considered by - * the statistic. - * - * @return the count the number of items (typically number of entities) - * considered by the statistic. - */ - public long getCount() { - return count; - } - - /** - * Sets the number of items (typically number of entities) considered by the - * statistic. - * - * @param count - * the number of items (typically number of entities) considered - * by the statistic. - * - */ - public void setCount(long count) { - this.count = count; - } - - /** - * Returns the total size of the items for this statistic. - * - * @return the total size of the items for this statistic. - */ - public long getBytes() { - return bytes; - } - - /** - * Sets the total size of the items for this statistics. - * - * @param bytes - * the total size of the items for this statistic. - */ - public void setBytes(long bytes) { - this.bytes = bytes; - } - - /** - * Returns the time of the most recent update to the statistic. - * - * @return the time of the most recent update to the statistic. - */ - public Date getTimestamp() { - return timestamp; - } - - /** - * Sets the time of the most recent update to the statistic. - * - * @param timestamp - * the time of the most recent update to the statistic. - */ - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } + /** + * Serial version UID + */ + private static final long serialVersionUID = 6745596308816079953L; + + /** + * Key of this Statistic entity + */ + @Key + private DatastoreKey key; + + /** + * number of items, typically entities + */ + @Property(name = StatConstants.PROP_COUNT) + private long count; + + /** + * Size of items + */ + @Property(name = StatConstants.PROP_BYTES) + private long bytes; + + /** + * Timestamp when the statistics were generated + */ + @Property(name = StatConstants.PROP_TIMESTAMP) + private Date timestamp; + + /** + * Returns the full key of this Statistic entity. + * + * @return the full key of this Statistic entity. + */ + public DatastoreKey getKey() { + return key; + } + + /** + * Sets the full key of this Statistic entity. + * + * @param key + * the full key of this Statistic entity. + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * Returns the number of items (typically number of entities) considered by the statistic. + * + * @return the count the number of items (typically number of entities) considered by the + * statistic. + */ + public long getCount() { + return count; + } + + /** + * Sets the number of items (typically number of entities) considered by the statistic. + * + * @param count + * the number of items (typically number of entities) considered by the statistic. + * + */ + public void setCount(long count) { + this.count = count; + } + + /** + * Returns the total size of the items for this statistic. + * + * @return the total size of the items for this statistic. + */ + public long getBytes() { + return bytes; + } + + /** + * Sets the total size of the items for this statistics. + * + * @param bytes + * the total size of the items for this statistic. + */ + public void setBytes(long bytes) { + this.bytes = bytes; + } + + /** + * Returns the time of the most recent update to the statistic. + * + * @return the time of the most recent update to the statistic. + */ + public Date getTimestamp() { + return timestamp; + } + + /** + * Sets the time of the most recent update to the statistic. + * + * @param timestamp + * the time of the most recent update to the statistic. + */ + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndex.java b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndex.java index e6236c7..1998274 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndex.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndex.java @@ -29,9 +29,9 @@ @Entity(kind = StatConstants.STAT_COMPOSITE_INDEX) public class StatCompositeIndex extends StatCompositeIndexBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 7142034196925336326L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 7142034196925336326L; } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexBase.java b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexBase.java index ae9ea93..cc82571 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexBase.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexBase.java @@ -31,85 +31,84 @@ @MappedSuperClass public abstract class StatCompositeIndexBase extends StatBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -7965853149712013490L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -7965853149712013490L; - /** - * Entity ID - */ - @Identifier(autoGenerated = false) - private String id; + /** + * Entity ID + */ + @Identifier(autoGenerated = false) + private String id; - /** - * Index ID - */ - @Property(name = StatConstants.PROP_INDEX_ID) - private long indexId; + /** + * Index ID + */ + @Property(name = StatConstants.PROP_INDEX_ID) + private long indexId; - /** - * Kind name - */ - @Property(name = StatConstants.PROP_KIND_NAME) - private String kindName; + /** + * Kind name + */ + @Property(name = StatConstants.PROP_KIND_NAME) + private String kindName; - /** - * Returns the ID of this statistic entity. - * - * @return the ID of this statistic entity. - */ - public String getId() { - return id; - } + /** + * Returns the ID of this statistic entity. + * + * @return the ID of this statistic entity. + */ + public String getId() { + return id; + } - /** - * Sets the ID of this statistic entity. - * - * @param id - * the ID of this statistic entity. - */ - public void setId(String id) { - this.id = id; - } + /** + * Sets the ID of this statistic entity. + * + * @param id + * the ID of this statistic entity. + */ + public void setId(String id) { + this.id = id; + } - /** - * Returns the ID of the index to which this statistic belongs to. - * - * @return the ID of the index to which this statistic belongs to. - */ - public long getIndexId() { - return indexId; - } + /** + * Returns the ID of the index to which this statistic belongs to. + * + * @return the ID of the index to which this statistic belongs to. + */ + public long getIndexId() { + return indexId; + } - /** - * Sets the ID of the index to which this statistic belongs to. - * - * @param indexId - * the ID of the index to which this statistic belongs to. - */ - public void setIndexId(long indexId) { - this.indexId = indexId; - } + /** + * Sets the ID of the index to which this statistic belongs to. + * + * @param indexId + * the ID of the index to which this statistic belongs to. + */ + public void setIndexId(long indexId) { + this.indexId = indexId; + } - /** - * Returns the name of the Kind on which this composite index was created. - * - * @return the name of the Kind on which this composite index was created. - */ - public String getKindName() { - return kindName; - } + /** + * Returns the name of the Kind on which this composite index was created. + * + * @return the name of the Kind on which this composite index was created. + */ + public String getKindName() { + return kindName; + } - /** - * Sets the name of the Kind on which this composite index was created. - * - * @param kindName - * the name of the Kind on which this composite index was - * created. - */ - public void setKindName(String kindName) { - this.kindName = kindName; - } + /** + * Sets the name of the Kind on which this composite index was created. + * + * @param kindName + * the name of the Kind on which this composite index was created. + */ + public void setKindName(String kindName) { + this.kindName = kindName; + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexNs.java b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexNs.java index d31d29b..6816368 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexNs.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatCompositeIndexNs.java @@ -29,9 +29,9 @@ @Entity(kind = StatConstants.STAT_COMPOSITE_INDEX_NS) public class StatCompositeIndexNs extends StatCompositeIndexBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -2593351832953284028L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -2593351832953284028L; } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatConstants.java b/src/main/java/com/jmethods/catatumbo/stats/StatConstants.java index 00d7ddb..1539927 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatConstants.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatConstants.java @@ -24,106 +24,106 @@ */ public class StatConstants { - /** - * Creates a new instance of StatConstants. - */ - private StatConstants() { - // Hide the constructor - } - - /** - * Entity name for StatTotal - */ - public static final String STAT_TOTAL = "__Stat_Total__"; - - /** - * Entity name for StatTotal by Namespace - */ - public static final String STAT_TOTAL_NS = "__Stat_Ns_Total__"; - - /** - * Entity name for StatKind - */ - public static final String STAT_KIND = "__Stat_Kind__"; - - /** - * Entity name for StatKind by namespace - */ - public static final String STAT_KIND_NS = "__Stat_Ns_Kind__"; - - /** - * Entity name for StatNamespace - */ - public static final String STAT_NAMESPACE = "__Stat_Namespace__"; - - /** - * Entity name for composite index statistics - */ - public static final String STAT_COMPOSITE_INDEX = "__Stat_Kind_CompositeIndex__"; - - /** - * Entity name for composite index statistics (namespace specific) - */ - public static final String STAT_COMPOSITE_INDEX_NS = "__Stat_Ns_Kind_CompositeIndex__"; - - /** - * Property name that holds the Kind name - */ - public static final String PROP_KIND_NAME = "kind_name"; - - /** - * Property name that holds the total bytes for the statistic - */ - public static final String PROP_BYTES = "bytes"; - - /** - * Property name that holds the total count for the statistic - */ - public static final String PROP_COUNT = "count"; - - /** - * Property name that holds the timestamp of statistic - */ - public static final String PROP_TIMESTAMP = "timestamp"; - - /** - * Property name that holds the builtin index size - */ - public static final String PROP_BUILTIN_INDEX_BYTES = "builtin_index_bytes"; - - /** - * Property name that holds the builtin index count - */ - public static final String PROP_BUILTIN_INDEX_COUNT = "builtin_index_count"; - - /** - * Property name that holds that size of composite indexes - */ - public static final String PROP_COMPOSITE_INDEX_BYTES = "composite_index_bytes"; - - /** - * Property name that holds the composite index count - */ - public static final String PROP_COMPOSITE_INDEX_COUNT = "composite_index_count"; - - /** - * Property name that holds the size of entity - */ - public static final String PROP_ENTITY_BYTES = "entity_bytes"; - - /** - * Property name that holds the subject namespace - */ - public static final String PROP_SUBJECT_NAMESPACE = "subject_namespace"; - - /** - * Property name that holds the index ID. - */ - public static final String PROP_INDEX_ID = "index_id"; - - /** - * ID of StatTotal and StatTotal by namespace - */ - public static final String ID_TOTAL_ENTITY_USAGE = "total_entity_usage"; + /** + * Entity name for StatTotal + */ + public static final String STAT_TOTAL = "__Stat_Total__"; + + /** + * Entity name for StatTotal by Namespace + */ + public static final String STAT_TOTAL_NS = "__Stat_Ns_Total__"; + + /** + * Entity name for StatKind + */ + public static final String STAT_KIND = "__Stat_Kind__"; + + /** + * Entity name for StatKind by namespace + */ + public static final String STAT_KIND_NS = "__Stat_Ns_Kind__"; + + /** + * Entity name for StatNamespace + */ + public static final String STAT_NAMESPACE = "__Stat_Namespace__"; + + /** + * Entity name for composite index statistics + */ + public static final String STAT_COMPOSITE_INDEX = "__Stat_Kind_CompositeIndex__"; + + /** + * Entity name for composite index statistics (namespace specific) + */ + public static final String STAT_COMPOSITE_INDEX_NS = "__Stat_Ns_Kind_CompositeIndex__"; + + /** + * Property name that holds the Kind name + */ + public static final String PROP_KIND_NAME = "kind_name"; + + /** + * Property name that holds the total bytes for the statistic + */ + public static final String PROP_BYTES = "bytes"; + + /** + * Property name that holds the total count for the statistic + */ + public static final String PROP_COUNT = "count"; + + /** + * Property name that holds the timestamp of statistic + */ + public static final String PROP_TIMESTAMP = "timestamp"; + + /** + * Property name that holds the builtin index size + */ + public static final String PROP_BUILTIN_INDEX_BYTES = "builtin_index_bytes"; + + /** + * Property name that holds the builtin index count + */ + public static final String PROP_BUILTIN_INDEX_COUNT = "builtin_index_count"; + + /** + * Property name that holds that size of composite indexes + */ + public static final String PROP_COMPOSITE_INDEX_BYTES = "composite_index_bytes"; + + /** + * Property name that holds the composite index count + */ + public static final String PROP_COMPOSITE_INDEX_COUNT = "composite_index_count"; + + /** + * Property name that holds the size of entity + */ + public static final String PROP_ENTITY_BYTES = "entity_bytes"; + + /** + * Property name that holds the subject namespace + */ + public static final String PROP_SUBJECT_NAMESPACE = "subject_namespace"; + + /** + * Property name that holds the index ID. + */ + public static final String PROP_INDEX_ID = "index_id"; + + /** + * ID of StatTotal and StatTotal by namespace + */ + public static final String ID_TOTAL_ENTITY_USAGE = "total_entity_usage"; + + /** + * Creates a new instance of StatConstants. + */ + private StatConstants() { + // Hide the constructor + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatKind.java b/src/main/java/com/jmethods/catatumbo/stats/StatKind.java index 44fc1ad..e41230c 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatKind.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatKind.java @@ -29,9 +29,9 @@ @Entity(kind = StatConstants.STAT_KIND) public class StatKind extends StatKindBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 2549703734475617627L; + /** + * Serial version UID + */ + private static final long serialVersionUID = 2549703734475617627L; } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatKindBase.java b/src/main/java/com/jmethods/catatumbo/stats/StatKindBase.java index 7722157..285a37e 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatKindBase.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatKindBase.java @@ -31,184 +31,184 @@ @MappedSuperClass public abstract class StatKindBase extends StatBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 2440661058294008910L; - - /** - * Entity ID (same as Kind name). - */ - @Identifier(autoGenerated = false) - private String id; - - /** - * Kind name - */ - @Property(name = StatConstants.PROP_KIND_NAME) - private String kindName; - - /** - * Size of built-in indexes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) - private long builtinIndexBytes; - - /** - * Number of built-in indexes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) - private long builtinIndexCount; - - /** - * Size of composite indexes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) - private long compositeIndexBytes; - - /** - * Number of composite indexes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) - private long compositeIndexCount; - - /** - * Size of entities - */ - @Property(name = StatConstants.PROP_ENTITY_BYTES) - private long entityBytes; - - /** - * Returns the ID of this Statistic entity. - * - * @return the ID of this Statistic entity. - */ - public String getId() { - return id; - } - - /** - * Sets the ID of this Statistic entity. - * - * @param id - * the ID of this Statistic entity. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the Kind to which this statistic belongs to. - * - * @return the Kind to which this statistic belongs to. - */ - public String getKindName() { - return kindName; - } - - /** - * Sets the Kind to which this statistic belongs to. - * - * @param kindName - * the Kind to which this statistic belongs to. - */ - public void setKindName(String kindName) { - this.kindName = kindName; - } - - /** - * Returns the size of built-in indexes, in bytes. - * - * @return the size of built-in indexes, in bytes. - */ - public long getBuiltinIndexBytes() { - return builtinIndexBytes; - } - - /** - * Sets the size of built-in indexes, in bytes. - * - * @param builtinIndexBytes - * the size of built-in indexes, in bytes. - */ - public void setBuiltinIndexBytes(long builtinIndexBytes) { - this.builtinIndexBytes = builtinIndexBytes; - } - - /** - * Returns the number of built-in indexes. - * - * @return the number of built-in indexes. - */ - public long getBuiltinIndexCount() { - return builtinIndexCount; - } - - /** - * Sets the number of built-in indexes. - * - * @param builtinIndexCount - * the number of built-in indexes. - */ - public void setBuiltinIndexCount(long builtinIndexCount) { - this.builtinIndexCount = builtinIndexCount; - } - - /** - * Returns the size of composite indexes, in bytes. - * - * @return the size of composite indexes, in bytes. - */ - public long getCompositeIndexBytes() { - return compositeIndexBytes; - } - - /** - * Sets the size of composite indexes, in bytes. - * - * @param compositeIndexBytes - * the size of composite indexes, in bytes. - */ - public void setCompositeIndexBytes(long compositeIndexBytes) { - this.compositeIndexBytes = compositeIndexBytes; - } - - /** - * Returns the number of composite indexes. - * - * @return the number of composite indexes. - */ - public long getCompositeIndexCount() { - return compositeIndexCount; - } - - /** - * Sets the number of composite indexes. - * - * @param compositeIndexCount - * the number of composite indexes. - */ - public void setCompositeIndexCount(long compositeIndexCount) { - this.compositeIndexCount = compositeIndexCount; - } - - /** - * Returns the size of entities, in bytes. - * - * @return the size of entities, in bytes. - */ - public long getEntityBytes() { - return entityBytes; - } - - /** - * Sets the size of entities, in bytes. - * - * @param entityBytes - * the size of entities, in bytes. - */ - public void setEntityBytes(long entityBytes) { - this.entityBytes = entityBytes; - } + /** + * Serial version UID + */ + private static final long serialVersionUID = 2440661058294008910L; + + /** + * Entity ID (same as Kind name). + */ + @Identifier(autoGenerated = false) + private String id; + + /** + * Kind name + */ + @Property(name = StatConstants.PROP_KIND_NAME) + private String kindName; + + /** + * Size of built-in indexes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) + private long builtinIndexBytes; + + /** + * Number of built-in indexes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) + private long builtinIndexCount; + + /** + * Size of composite indexes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) + private long compositeIndexBytes; + + /** + * Number of composite indexes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) + private long compositeIndexCount; + + /** + * Size of entities + */ + @Property(name = StatConstants.PROP_ENTITY_BYTES) + private long entityBytes; + + /** + * Returns the ID of this Statistic entity. + * + * @return the ID of this Statistic entity. + */ + public String getId() { + return id; + } + + /** + * Sets the ID of this Statistic entity. + * + * @param id + * the ID of this Statistic entity. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns the Kind to which this statistic belongs to. + * + * @return the Kind to which this statistic belongs to. + */ + public String getKindName() { + return kindName; + } + + /** + * Sets the Kind to which this statistic belongs to. + * + * @param kindName + * the Kind to which this statistic belongs to. + */ + public void setKindName(String kindName) { + this.kindName = kindName; + } + + /** + * Returns the size of built-in indexes, in bytes. + * + * @return the size of built-in indexes, in bytes. + */ + public long getBuiltinIndexBytes() { + return builtinIndexBytes; + } + + /** + * Sets the size of built-in indexes, in bytes. + * + * @param builtinIndexBytes + * the size of built-in indexes, in bytes. + */ + public void setBuiltinIndexBytes(long builtinIndexBytes) { + this.builtinIndexBytes = builtinIndexBytes; + } + + /** + * Returns the number of built-in indexes. + * + * @return the number of built-in indexes. + */ + public long getBuiltinIndexCount() { + return builtinIndexCount; + } + + /** + * Sets the number of built-in indexes. + * + * @param builtinIndexCount + * the number of built-in indexes. + */ + public void setBuiltinIndexCount(long builtinIndexCount) { + this.builtinIndexCount = builtinIndexCount; + } + + /** + * Returns the size of composite indexes, in bytes. + * + * @return the size of composite indexes, in bytes. + */ + public long getCompositeIndexBytes() { + return compositeIndexBytes; + } + + /** + * Sets the size of composite indexes, in bytes. + * + * @param compositeIndexBytes + * the size of composite indexes, in bytes. + */ + public void setCompositeIndexBytes(long compositeIndexBytes) { + this.compositeIndexBytes = compositeIndexBytes; + } + + /** + * Returns the number of composite indexes. + * + * @return the number of composite indexes. + */ + public long getCompositeIndexCount() { + return compositeIndexCount; + } + + /** + * Sets the number of composite indexes. + * + * @param compositeIndexCount + * the number of composite indexes. + */ + public void setCompositeIndexCount(long compositeIndexCount) { + this.compositeIndexCount = compositeIndexCount; + } + + /** + * Returns the size of entities, in bytes. + * + * @return the size of entities, in bytes. + */ + public long getEntityBytes() { + return entityBytes; + } + + /** + * Sets the size of entities, in bytes. + * + * @param entityBytes + * the size of entities, in bytes. + */ + public void setEntityBytes(long entityBytes) { + this.entityBytes = entityBytes; + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatKindNs.java b/src/main/java/com/jmethods/catatumbo/stats/StatKindNs.java index ef3b158..3c732d7 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatKindNs.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatKindNs.java @@ -29,9 +29,9 @@ @Entity(kind = StatConstants.STAT_KIND_NS) public class StatKindNs extends StatKindBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -8766112901529363944L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -8766112901529363944L; } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatNamespace.java b/src/main/java/com/jmethods/catatumbo/stats/StatNamespace.java index 8586a58..a178d18 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatNamespace.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatNamespace.java @@ -23,8 +23,7 @@ import com.jmethods.catatumbo.Property; /** - * Base class for Summary Statistics - for the entire Datastore as well as for a - * specific namespace. + * Base class for Summary Statistics - for the entire Datastore as well as for a specific namespace. * * @author Sai Pullabhotla * @@ -32,184 +31,184 @@ @Entity(kind = StatConstants.STAT_NAMESPACE) public class StatNamespace extends StatBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -6358059154078381425L; - - /** - * ID of the statistic entity - */ - @Identifier(autoGenerated = false) - private String id; - - /** - * Size of built-in indexes, in bytes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) - private long builtinIndexBytes; - - /** - * Number of built-in indexes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) - private long builtinIndexCount; - - /** - * Size of composite indexes, in bytes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) - private long compositeIndexBytes; - - /** - * Number of composite indexes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) - private long compositeIndexCount; - - /** - * Size of entities, in bytes - */ - @Property(name = StatConstants.PROP_ENTITY_BYTES) - private long entityBytes; - - /** - * Subject namespace - */ - @Property(name = StatConstants.PROP_SUBJECT_NAMESPACE) - private String subjectNamespace; - - /** - * Returns the ID of this statistic entity. - * - * @return the ID of this statistic entity. - */ - public String getId() { - return id; - } - - /** - * Sets the ID of this statistic entity. - * - * @param id - * the ID of this statistic entity. - */ - public void setId(String id) { - this.id = id == null ? "" : id; - } - - /** - * Returns the size of built-in indexes in bytes. - * - * @return the size of built-in indexes in bytes. - */ - public long getBuiltinIndexBytes() { - return builtinIndexBytes; - } - - /** - * Sets the size of built-in indexes in bytes. - * - * @param builtinIndexBytes - * the size of built-in indexes in bytes. - */ - public void setBuiltinIndexBytes(long builtinIndexBytes) { - this.builtinIndexBytes = builtinIndexBytes; - } - - /** - * Returns the number of built-in indexes. - * - * @return the number of built-in indexes. - */ - public long getBuiltinIndexCount() { - return builtinIndexCount; - } - - /** - * Sets the number of built-in indexes. - * - * @param builtinIndexCount - * the number of built-in indexes. - */ - public void setBuiltinIndexCount(long builtinIndexCount) { - this.builtinIndexCount = builtinIndexCount; - } - - /** - * Returns the size of composite indexes in bytes. - * - * @return the size of composite indexes in bytes. - */ - public long getCompositeIndexBytes() { - return compositeIndexBytes; - } - - /** - * Sets the size of composite indexes in bytes. - * - * @param compositeIndexBytes - * the size of composite indexes in bytes. - */ - public void setCompositeIndexBytes(long compositeIndexBytes) { - this.compositeIndexBytes = compositeIndexBytes; - } - - /** - * Returns the number of composite indexes. - * - * @return the number of composite indexes. - */ - public long getCompositeIndexCount() { - return compositeIndexCount; - } - - /** - * Sets the number of composite indexes. - * - * @param compositeIndexCount - * the number of composite indexes. - */ - public void setCompositeIndexCount(long compositeIndexCount) { - this.compositeIndexCount = compositeIndexCount; - } - - /** - * Returns the size of entities in bytes. - * - * @return the size of entities in bytes. - */ - public long getEntityBytes() { - return entityBytes; - } - - /** - * Sets the size of entities in bytes. - * - * @param entityBytes - * the size of entities in bytes. - */ - public void setEntityBytes(long entityBytes) { - this.entityBytes = entityBytes; - } - - /** - * Returns the subject namespace to which these statistics belong to. - * - * @return the subject namespace to which these statistics belong to. - */ - public String getSubjectNamespace() { - return subjectNamespace; - } - - /** - * Sets the subject namespace to which these statistics belong to. - * - * @param subjectNamespace - * the subject namespace to which these statistics belong to. - */ - public void setSubjectNamespace(String subjectNamespace) { - this.subjectNamespace = subjectNamespace; - } + /** + * Serial version UID + */ + private static final long serialVersionUID = -6358059154078381425L; + + /** + * ID of the statistic entity + */ + @Identifier(autoGenerated = false) + private String id; + + /** + * Size of built-in indexes, in bytes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) + private long builtinIndexBytes; + + /** + * Number of built-in indexes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) + private long builtinIndexCount; + + /** + * Size of composite indexes, in bytes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) + private long compositeIndexBytes; + + /** + * Number of composite indexes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) + private long compositeIndexCount; + + /** + * Size of entities, in bytes + */ + @Property(name = StatConstants.PROP_ENTITY_BYTES) + private long entityBytes; + + /** + * Subject namespace + */ + @Property(name = StatConstants.PROP_SUBJECT_NAMESPACE) + private String subjectNamespace; + + /** + * Returns the ID of this statistic entity. + * + * @return the ID of this statistic entity. + */ + public String getId() { + return id; + } + + /** + * Sets the ID of this statistic entity. + * + * @param id + * the ID of this statistic entity. + */ + public void setId(String id) { + this.id = id == null ? "" : id; + } + + /** + * Returns the size of built-in indexes in bytes. + * + * @return the size of built-in indexes in bytes. + */ + public long getBuiltinIndexBytes() { + return builtinIndexBytes; + } + + /** + * Sets the size of built-in indexes in bytes. + * + * @param builtinIndexBytes + * the size of built-in indexes in bytes. + */ + public void setBuiltinIndexBytes(long builtinIndexBytes) { + this.builtinIndexBytes = builtinIndexBytes; + } + + /** + * Returns the number of built-in indexes. + * + * @return the number of built-in indexes. + */ + public long getBuiltinIndexCount() { + return builtinIndexCount; + } + + /** + * Sets the number of built-in indexes. + * + * @param builtinIndexCount + * the number of built-in indexes. + */ + public void setBuiltinIndexCount(long builtinIndexCount) { + this.builtinIndexCount = builtinIndexCount; + } + + /** + * Returns the size of composite indexes in bytes. + * + * @return the size of composite indexes in bytes. + */ + public long getCompositeIndexBytes() { + return compositeIndexBytes; + } + + /** + * Sets the size of composite indexes in bytes. + * + * @param compositeIndexBytes + * the size of composite indexes in bytes. + */ + public void setCompositeIndexBytes(long compositeIndexBytes) { + this.compositeIndexBytes = compositeIndexBytes; + } + + /** + * Returns the number of composite indexes. + * + * @return the number of composite indexes. + */ + public long getCompositeIndexCount() { + return compositeIndexCount; + } + + /** + * Sets the number of composite indexes. + * + * @param compositeIndexCount + * the number of composite indexes. + */ + public void setCompositeIndexCount(long compositeIndexCount) { + this.compositeIndexCount = compositeIndexCount; + } + + /** + * Returns the size of entities in bytes. + * + * @return the size of entities in bytes. + */ + public long getEntityBytes() { + return entityBytes; + } + + /** + * Sets the size of entities in bytes. + * + * @param entityBytes + * the size of entities in bytes. + */ + public void setEntityBytes(long entityBytes) { + this.entityBytes = entityBytes; + } + + /** + * Returns the subject namespace to which these statistics belong to. + * + * @return the subject namespace to which these statistics belong to. + */ + public String getSubjectNamespace() { + return subjectNamespace; + } + + /** + * Sets the subject namespace to which these statistics belong to. + * + * @param subjectNamespace + * the subject namespace to which these statistics belong to. + */ + public void setSubjectNamespace(String subjectNamespace) { + this.subjectNamespace = subjectNamespace; + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatTotal.java b/src/main/java/com/jmethods/catatumbo/stats/StatTotal.java index 615d8bd..c166a69 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatTotal.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatTotal.java @@ -21,8 +21,7 @@ import com.jmethods.catatumbo.Entity; /** - * Statistic entity that contains summary of the Datastore usage (all - * namespaces). + * Statistic entity that contains summary of the Datastore usage (all namespaces). * * @author Sai Pullabhotla * @@ -30,9 +29,9 @@ @Entity(kind = StatConstants.STAT_TOTAL) public class StatTotal extends StatTotalBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -8279421156053694066L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -8279421156053694066L; } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatTotalBase.java b/src/main/java/com/jmethods/catatumbo/stats/StatTotalBase.java index dcf5a79..1eef81a 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatTotalBase.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatTotalBase.java @@ -23,8 +23,7 @@ import com.jmethods.catatumbo.Property; /** - * Base class for Summary Statistics - for the entire Datastore as well as for a - * specific namespace. + * Base class for Summary Statistics - for the entire Datastore as well as for a specific namespace. * * @author Sai Pullabhotla * @@ -32,159 +31,159 @@ @MappedSuperClass public abstract class StatTotalBase extends StatBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -5629549681670703097L; - - /** - * ID of the statistic entity - */ - @Identifier(autoGenerated = false) - private String id; - - /** - * Size of built-in indexes, in bytes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) - private long builtinIndexBytes; - - /** - * Number of built-in indexes - */ - @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) - private long builtinIndexCount; - - /** - * Size of composite indexes, in bytes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) - private long compositeIndexBytes; - - /** - * Number of composite indexes - */ - @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) - private long compositeIndexCount; - - /** - * Size of entities, in bytes - */ - @Property(name = StatConstants.PROP_ENTITY_BYTES) - private long entityBytes; - - /** - * Returns the ID of this statistic entity. - * - * @return the ID of this statistic entity. - */ - public String getId() { - return id; - } - - /** - * Sets the ID of this statistic entity. - * - * @param id - * the ID of this statistic entity. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the size of built-in indexes in bytes. - * - * @return the size of built-in indexes in bytes. - */ - public long getBuiltinIndexBytes() { - return builtinIndexBytes; - } - - /** - * Sets the size of built-in indexes in bytes. - * - * @param builtinIndexBytes - * the size of built-in indexes in bytes. - */ - public void setBuiltinIndexBytes(long builtinIndexBytes) { - this.builtinIndexBytes = builtinIndexBytes; - } - - /** - * Returns the number of built-in indexes. - * - * @return the number of built-in indexes. - */ - public long getBuiltinIndexCount() { - return builtinIndexCount; - } - - /** - * Sets the number of built-in indexes. - * - * @param builtinIndexCount - * the number of built-in indexes. - */ - public void setBuiltinIndexCount(long builtinIndexCount) { - this.builtinIndexCount = builtinIndexCount; - } - - /** - * Returns the size of composite indexes in bytes. - * - * @return the size of composite indexes in bytes. - */ - public long getCompositeIndexBytes() { - return compositeIndexBytes; - } - - /** - * Sets the size of composite indexes in bytes. - * - * @param compositeIndexBytes - * the size of composite indexes in bytes. - */ - public void setCompositeIndexBytes(long compositeIndexBytes) { - this.compositeIndexBytes = compositeIndexBytes; - } - - /** - * Returns the number of composite indexes. - * - * @return the number of composite indexes. - */ - public long getCompositeIndexCount() { - return compositeIndexCount; - } - - /** - * Sets the number of composite indexes. - * - * @param compositeIndexCount - * the number of composite indexes. - */ - public void setCompositeIndexCount(long compositeIndexCount) { - this.compositeIndexCount = compositeIndexCount; - } - - /** - * Returns the size of entities in bytes. - * - * @return the size of entities in bytes. - */ - public long getEntityBytes() { - return entityBytes; - } - - /** - * Sets the size of entities in bytes. - * - * @param entityBytes - * the size of entities in bytes. - */ - public void setEntityBytes(long entityBytes) { - this.entityBytes = entityBytes; - } + /** + * Serial version UID + */ + private static final long serialVersionUID = -5629549681670703097L; + + /** + * ID of the statistic entity + */ + @Identifier(autoGenerated = false) + private String id; + + /** + * Size of built-in indexes, in bytes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_BYTES) + private long builtinIndexBytes; + + /** + * Number of built-in indexes + */ + @Property(name = StatConstants.PROP_BUILTIN_INDEX_COUNT) + private long builtinIndexCount; + + /** + * Size of composite indexes, in bytes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_BYTES) + private long compositeIndexBytes; + + /** + * Number of composite indexes + */ + @Property(name = StatConstants.PROP_COMPOSITE_INDEX_COUNT) + private long compositeIndexCount; + + /** + * Size of entities, in bytes + */ + @Property(name = StatConstants.PROP_ENTITY_BYTES) + private long entityBytes; + + /** + * Returns the ID of this statistic entity. + * + * @return the ID of this statistic entity. + */ + public String getId() { + return id; + } + + /** + * Sets the ID of this statistic entity. + * + * @param id + * the ID of this statistic entity. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns the size of built-in indexes in bytes. + * + * @return the size of built-in indexes in bytes. + */ + public long getBuiltinIndexBytes() { + return builtinIndexBytes; + } + + /** + * Sets the size of built-in indexes in bytes. + * + * @param builtinIndexBytes + * the size of built-in indexes in bytes. + */ + public void setBuiltinIndexBytes(long builtinIndexBytes) { + this.builtinIndexBytes = builtinIndexBytes; + } + + /** + * Returns the number of built-in indexes. + * + * @return the number of built-in indexes. + */ + public long getBuiltinIndexCount() { + return builtinIndexCount; + } + + /** + * Sets the number of built-in indexes. + * + * @param builtinIndexCount + * the number of built-in indexes. + */ + public void setBuiltinIndexCount(long builtinIndexCount) { + this.builtinIndexCount = builtinIndexCount; + } + + /** + * Returns the size of composite indexes in bytes. + * + * @return the size of composite indexes in bytes. + */ + public long getCompositeIndexBytes() { + return compositeIndexBytes; + } + + /** + * Sets the size of composite indexes in bytes. + * + * @param compositeIndexBytes + * the size of composite indexes in bytes. + */ + public void setCompositeIndexBytes(long compositeIndexBytes) { + this.compositeIndexBytes = compositeIndexBytes; + } + + /** + * Returns the number of composite indexes. + * + * @return the number of composite indexes. + */ + public long getCompositeIndexCount() { + return compositeIndexCount; + } + + /** + * Sets the number of composite indexes. + * + * @param compositeIndexCount + * the number of composite indexes. + */ + public void setCompositeIndexCount(long compositeIndexCount) { + this.compositeIndexCount = compositeIndexCount; + } + + /** + * Returns the size of entities in bytes. + * + * @return the size of entities in bytes. + */ + public long getEntityBytes() { + return entityBytes; + } + + /** + * Sets the size of entities in bytes. + * + * @param entityBytes + * the size of entities in bytes. + */ + public void setEntityBytes(long entityBytes) { + this.entityBytes = entityBytes; + } } diff --git a/src/main/java/com/jmethods/catatumbo/stats/StatTotalNs.java b/src/main/java/com/jmethods/catatumbo/stats/StatTotalNs.java index ec22cb9..e815ac3 100644 --- a/src/main/java/com/jmethods/catatumbo/stats/StatTotalNs.java +++ b/src/main/java/com/jmethods/catatumbo/stats/StatTotalNs.java @@ -29,9 +29,9 @@ @Entity(kind = StatConstants.STAT_TOTAL_NS) public class StatTotalNs extends StatTotalBase implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = -5834153984732391563L; + /** + * Serial version UID + */ + private static final long serialVersionUID = -5834153984732391563L; } diff --git a/src/test/java/com/jmethods/catatumbo/AllTests.java b/src/test/java/com/jmethods/catatumbo/AllTests.java index ffc62b8..15c7566 100644 --- a/src/test/java/com/jmethods/catatumbo/AllTests.java +++ b/src/test/java/com/jmethods/catatumbo/AllTests.java @@ -32,43 +32,45 @@ * */ @RunWith(Suite.class) -@SuiteClasses({ CustomTypeTest.class, DatastoreBatchTest.class, DatastoreMetadataTest.class, DatastoreStatsTest.class, - DatastoreTransactionTest.class, DecimalFieldsTest.class, DefaultAndExternalListenersTest.class, - DefaultListenerTest.class, EmbeddedCollectionTest.class, EntityManagerFactoryTest.class, - EntityManagerTest.class, ExcludeDefaultListenerTest.class, ExternalListenerTest.class, IndexerFactoryTest.class, - InternalListenerTest.class, ListenerInheritanceTest.class, MapperFactoryTest.class, OptionalFieldsTest.class, - SecondaryIndexTest.class, TenantTest.class, TwoDefaultListenersTest.class, TwoExternalListenersTest.class }) +@SuiteClasses({ CustomTypeTest.class, DatastoreBatchTest.class, DatastoreMetadataTest.class, + DatastoreStatsTest.class, DatastoreTransactionTest.class, DecimalFieldsTest.class, + DefaultAndExternalListenersTest.class, DefaultListenerTest.class, EmbeddedCollectionTest.class, + EntityManagerFactoryTest.class, EntityManagerTest.class, ExcludeDefaultListenerTest.class, + ExternalListenerTest.class, IndexerFactoryTest.class, InternalListenerTest.class, + ListenerInheritanceTest.class, MapperFactoryTest.class, OptionalFieldsTest.class, + SecondaryIndexTest.class, TenantTest.class, TwoDefaultListenersTest.class, + TwoExternalListenersTest.class }) public class AllTests { - private static EntityManager em; + private static EntityManager em; - @BeforeClass - public static void clearDatastore() throws Exception { - em = TestUtils.getEntityManager(); - em.getDatastoreMetadata().getKinds(true).forEach(em::deleteAll); - populateTasks(); - } + @BeforeClass + public static void clearDatastore() throws Exception { + em = TestUtils.getEntityManager(); + em.getDatastoreMetadata().getKinds(true).forEach(em::deleteAll); + populateTasks(); + } - private static void populateTasks() { - List tasks = new ArrayList<>(50); - Calendar today = Calendar.getInstance(); - today.set(Calendar.HOUR_OF_DAY, 0); - today.set(Calendar.MINUTE, 0); - today.set(Calendar.SECOND, 0); - today.set(Calendar.MILLISECOND, 0); - for (int i = 1; i <= 50; i++) { - Task task = new Task(); - task.setId(i); - task.setName("My Task " + i); - task.setPriority(i % 5); - task.setComplete(i % 10 == 0); - Calendar cal = (Calendar) today.clone(); - cal.add(Calendar.DATE, i % 5); - task.setCompletionDate(cal.getTime()); - tasks.add(task); - } - em.insert(tasks); - } + private static void populateTasks() { + List tasks = new ArrayList<>(50); + Calendar today = Calendar.getInstance(); + today.set(Calendar.HOUR_OF_DAY, 0); + today.set(Calendar.MINUTE, 0); + today.set(Calendar.SECOND, 0); + today.set(Calendar.MILLISECOND, 0); + for (int i = 1; i <= 50; i++) { + Task task = new Task(); + task.setId(i); + task.setName("My Task " + i); + task.setPriority(i % 5); + task.setComplete(i % 10 == 0); + Calendar cal = (Calendar) today.clone(); + cal.add(Calendar.DATE, i % 5); + task.setCompletionDate(cal.getTime()); + tasks.add(task); + } + em.insert(tasks); + } } diff --git a/src/test/java/com/jmethods/catatumbo/CustomTypeTest.java b/src/test/java/com/jmethods/catatumbo/CustomTypeTest.java index f704d57..6428773 100644 --- a/src/test/java/com/jmethods/catatumbo/CustomTypeTest.java +++ b/src/test/java/com/jmethods/catatumbo/CustomTypeTest.java @@ -31,20 +31,20 @@ public class CustomTypeTest { - private static EntityManager em = null; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - MapperFactory.getInstance().setDefaultMapper(byte.class, new ByteMapper()); - em = TestUtils.getEntityManager(); - } - - @Test - public void testInsert() { - CustomTypeEntity entity = new CustomTypeEntity(); - entity.setByteField((byte) 65); - entity = em.insert(entity); - assertEquals((byte) 65, entity.getByteField()); - } + private static EntityManager em = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + MapperFactory.getInstance().setDefaultMapper(byte.class, new ByteMapper()); + em = TestUtils.getEntityManager(); + } + + @Test + public void testInsert() { + CustomTypeEntity entity = new CustomTypeEntity(); + entity.setByteField((byte) 65); + entity = em.insert(entity); + assertEquals((byte) 65, entity.getByteField()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/DatastoreBatchTest.java b/src/test/java/com/jmethods/catatumbo/DatastoreBatchTest.java index 1567561..d633719 100644 --- a/src/test/java/com/jmethods/catatumbo/DatastoreBatchTest.java +++ b/src/test/java/com/jmethods/catatumbo/DatastoreBatchTest.java @@ -41,381 +41,381 @@ */ public class DatastoreBatchTest { - private static EntityManager em = null; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } - - @Test - public void testInsert_LongId() { - DatastoreBatch batch = em.newBatch(); - LongId entity = new LongId(); - entity.setField1("Batch Insert Test"); - LongId entity2 = batch.insert(entity); - batch.submit(); - LongId entity3 = em.load(LongId.class, entity2.getId()); - assertTrue(entity2.equals(entity3)); - } - - @Test - public void testInsert_LongId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - LongId entity = new LongId(); - entity.setField1("Batch Insert Test " + i); - entities.add(entity); - } - List insertedEntities = batch.insert(entities); - batch.submit(); - List identifiers = new ArrayList<>(); - for (LongId entity : insertedEntities) { - identifiers.add(entity.getId()); - } - List retrievedEntities = em.loadById(LongId.class, identifiers); - assertTrue(insertedEntities.equals(retrievedEntities)); - } - - @Test - public void testInsertWithDeferredIdAllocation_LongId() { - DatastoreBatch batch = em.newBatch(); - LongId entity = new LongId(); - entity.setField1("Batch Insert Test with Deferred ID Allocation"); - batch.insertWithDeferredIdAllocation(entity); - DatastoreBatch.Response response = batch.submit(); - // Leaving this call to the deprecated method - assertTrue(response.getGeneratedKeys().size() == 1); - } - - @Test - public void testInsertWithDeferredIdAllocation_LongId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - LongId entity = new LongId(); - entity.setField1("Batch Insert Test with Deferred ID Allocation " + i); - entities.add(entity); - } - batch.insertWithDeferredIdAllocation(entities); - DatastoreBatch.Response response = batch.submit(); - assertTrue(response.getGeneratedKeys().size() == 5); - } - - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_StringId() { - DatastoreBatch batch = em.newBatch(); - StringId entity = new StringId(); - entity.setGreetings("Batch Insert Test with Deferred String ID Allocation"); - batch.insertWithDeferredIdAllocation(entity); - } - - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_StringId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - StringId entity = new StringId(); - entities.add(entity); - } - batch.insertWithDeferredIdAllocation(entities); - } - - @Test - public void testUpdate() { - LongId entity = new LongId(); - entity.setField1("Test for Batch Update"); - entity = em.insert(entity); - entity = em.load(LongId.class, entity.getId()); - entity.setField1("Updated"); - DatastoreBatch batch = em.newBatch(); - entity = batch.update(entity); - batch.submit(); - LongId entity2 = em.load(LongId.class, entity.getId()); - assertTrue("Updated".equals(entity2.getField1())); - } - - @Test - public void testUpdate_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - entities.add(new LongId()); - } - entities = em.insert(entities); - for (LongId entity : entities) { - entity.setField1("Updated"); - } - DatastoreBatch batch = em.newBatch(); - entities = batch.update(entities); - batch.submit(); - List identifiers = new ArrayList<>(); - for (LongId entity : entities) { - identifiers.add(entity.getId()); - } - List entities2 = em.loadById(LongId.class, identifiers); - assertTrue(entities.equals(entities2)); - } - - @Test - public void testUpdate_OptimisticLock() { - DatastoreBatch batch = em.newBatch(); - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Batch Update Test"); - entity = em.insert(entity); - entity = em.load(OptimisticLock1.class, entity.getId()); - entity.setName("Batch Update Test - Updated"); - entity = batch.update(entity); - batch.submit(); - entity = em.load(OptimisticLock1.class, entity.getId()); - assertTrue(entity.getVersion() == 1); - } - - @Test - public void testUpsert_LongId() { - DatastoreBatch batch = em.newBatch(); - LongId entity = new LongId(); - entity.setField1("Batch Upsert Test"); - LongId entity2 = batch.upsert(entity); - batch.submit(); - LongId entity3 = em.load(LongId.class, entity2.getId()); - assertTrue(entity2.equals(entity3)); - } - - @Test - public void testUpsert_LongId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - LongId entity = new LongId(); - entity.setField1("Batch Upsert Test " + i); - entities.add(entity); - } - List insertedEntities = batch.upsert(entities); - batch.submit(); - List identifiers = new ArrayList<>(); - for (LongId entity : insertedEntities) { - identifiers.add(entity.getId()); - } - List retrievedEntities = em.loadById(LongId.class, identifiers); - assertTrue(insertedEntities.equals(retrievedEntities)); - } - - @Test - public void testUpsertWithDeferredIdAllocation_LongId() { - DatastoreBatch batch = em.newBatch(); - LongId entity = new LongId(); - entity.setField1("Batch Upsert Test with Deferred ID Allocation"); - batch.upsertWithDeferredIdAllocation(entity); - DatastoreBatch.Response response = batch.submit(); - assertTrue(response.getGeneratedKeys().size() == 1); - } - - @Test - public void testUpsertWithDeferredIdAllocation_LongId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - LongId entity = new LongId(); - entity.setField1("Batch Upsert Test with Deferred ID Allocation " + i); - entities.add(entity); - } - batch.upsertWithDeferredIdAllocation(entities); - DatastoreBatch.Response response = batch.submit(); - assertTrue(response.getGeneratedKeys().size() == 5); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertWithDeferredIdAllocation_StringId() { - DatastoreBatch batch = em.newBatch(); - StringId entity = new StringId(); - entity.setGreetings("Batch Insert Test with Deferred String ID Allocation"); - batch.upsertWithDeferredIdAllocation(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertWithDeferredIdAllocation_StringId_List() { - DatastoreBatch batch = em.newBatch(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - StringId entity = new StringId(); - entities.add(entity); - } - batch.upsertWithDeferredIdAllocation(entities); - } - - @Test - public void testDelete_Object() { - LongId entity = em.insert(new LongId()); - DatastoreBatch batch = em.newBatch(); - batch.delete(entity); - batch.submit(); - LongId retrievedEntity = em.load(LongId.class, entity.getId()); - assertNull(retrievedEntity); - } - - @Test - public void testDelete_ListOfObjects() { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - entities.add(new LongId()); - } - entities = em.insert(entities); - List identifiers = new ArrayList<>(); - for (LongId entity : entities) { - identifiers.add(entity.getId()); - } - DatastoreBatch batch = em.newBatch(); - batch.delete(entities); - batch.submit(); - List retrievedEntities = em.loadById(LongId.class, identifiers); - assertTrue( - retrievedEntities.get(0) == null && retrievedEntities.get(1) == null && retrievedEntities.get(2) == null - && retrievedEntities.get(3) == null && retrievedEntities.get(4) == null); - } - - @Test - public void testDeleteByKey() { - ParentEntity entity = new ParentEntity(); - entity = em.insert(entity); - DatastoreBatch batch = em.newBatch(); - DatastoreKey key = entity.getKey(); - batch.deleteByKey(key); - batch.submit(); - ParentEntity retrievedEntity = em.load(ParentEntity.class, entity.getId()); - assertNull(retrievedEntity); - } - - @Test - public void testDeleteByKey_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - ParentEntity entity = new ParentEntity(); - entities.add(entity); - } - entities = em.insert(entities); - List keys = new ArrayList<>(); - List identifiers = new ArrayList<>(); - for (ParentEntity entity : entities) { - keys.add(entity.getKey()); - identifiers.add(entity.getId()); - } - DatastoreBatch batch = em.newBatch(); - batch.deleteByKey(keys); - batch.submit(); - List retrievedEntities = em.loadById(ParentEntity.class, identifiers); - assertTrue(retrievedEntities.get(0) == null && retrievedEntities.get(1) == null - && retrievedEntities.get(2) == null); - } - - @Test - public void testInsertParentChild() { - DatastoreBatch batch = em.newBatch(); - ParentEntity parent = new ParentEntity(); - parent = batch.insert(parent); - ChildEntity child = new ChildEntity(); - child.setParentKey(parent.getKey()); - child = batch.insert(child); - batch.submit(); - ChildEntity child2 = em.load(ChildEntity.class, parent.getKey(), child.getId()); - System.out.println(child2.getKey().getEncoded()); - assertTrue(child2.getId() == child.getId() && child2.getParentKey().equals(parent.getKey())); - } - - @Test - public void testInsert_Upsert() { - LongId entity = new LongId(); - entity.setId(100); - em.insert(entity); - DatastoreBatch batch = em.newBatch(); - batch.delete(entity); - entity.setField1("Updated"); - batch.insert(entity); - batch.submit(); - entity = em.load(LongId.class, entity.getId()); - assertTrue(entity != null); - } - - @Test(expected = EntityManagerException.class) - public void testInactiveBatch() { - DatastoreBatch batch = em.newBatch(); - LongId entity = new LongId(); - entity.setField1("Batch Insert Test"); - LongId entity2 = batch.insert(entity); - batch.submit(); - batch.delete(entity2); - } - - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_ProjectedEntity() { - DatastoreBatch batch = em.newBatch(); - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe"); - batch.insertWithDeferredIdAllocation(entity); - } - - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_ProjectedEntityList() { - List contacts = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - ContactProjection contact = new ContactProjection(); - contact.setLastName("Doe " + i); - contacts.add(contact); - } - DatastoreBatch batch = em.newBatch(); - batch.insertWithDeferredIdAllocation(contacts); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertWithDeferredIdAllocation_ProjectedEntity() { - DatastoreBatch batch = em.newBatch(); - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe"); - batch.upsertWithDeferredIdAllocation(entity); - DatastoreBatch.Response response = batch.submit(); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertWithDeferredIdAllocation_ProjectedEntityList() { - List contacts = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - ContactProjection contact = new ContactProjection(); - contact.setLastName("Doe " + i); - contacts.add(contact); - } - DatastoreBatch batch = em.newBatch(); - batch.upsertWithDeferredIdAllocation(contacts); - } - - @Test(expected = EntityManagerException.class) - public void testUpdate_ProjectedEntity() { - Contact entity = Contact.createContact1(); - entity = em.insert(entity); - ContactProjection projectedEntity = em.load(ContactProjection.class, entity.getId()); - entity.setLastName("Doe Updated"); - DatastoreBatch batch = em.newBatch(); - projectedEntity = batch.update(projectedEntity); - batch.submit(); - } - - @Test(expected = EntityAlreadyExistsException.class) - public void testInsertDuplicateKey() { - StringField entity = new StringField(); - entity.setName("Test for Duplicate Key from Transaction"); - StringField entity2 = em.insert(entity); - DatastoreBatch batch = em.newBatch(); - try { - batch.insertWithDeferredIdAllocation(entity2); - batch.submit(); - } catch (EntityAlreadyExistsException exp) { - throw exp; - } catch (EntityManagerException exp) { - String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); - if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { - // Running on emulator that has a bug. - throw new EntityAlreadyExistsException(exp); - } - } - } + private static EntityManager em = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } + + @Test + public void testInsert_LongId() { + DatastoreBatch batch = em.newBatch(); + LongId entity = new LongId(); + entity.setField1("Batch Insert Test"); + LongId entity2 = batch.insert(entity); + batch.submit(); + LongId entity3 = em.load(LongId.class, entity2.getId()); + assertTrue(entity2.equals(entity3)); + } + + @Test + public void testInsert_LongId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + LongId entity = new LongId(); + entity.setField1("Batch Insert Test " + i); + entities.add(entity); + } + List insertedEntities = batch.insert(entities); + batch.submit(); + List identifiers = new ArrayList<>(); + for (LongId entity : insertedEntities) { + identifiers.add(entity.getId()); + } + List retrievedEntities = em.loadById(LongId.class, identifiers); + assertTrue(insertedEntities.equals(retrievedEntities)); + } + + @Test + public void testInsertWithDeferredIdAllocation_LongId() { + DatastoreBatch batch = em.newBatch(); + LongId entity = new LongId(); + entity.setField1("Batch Insert Test with Deferred ID Allocation"); + batch.insertWithDeferredIdAllocation(entity); + DatastoreBatch.Response response = batch.submit(); + // Leaving this call to the deprecated method + assertTrue(response.getGeneratedKeys().size() == 1); + } + + @Test + public void testInsertWithDeferredIdAllocation_LongId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + LongId entity = new LongId(); + entity.setField1("Batch Insert Test with Deferred ID Allocation " + i); + entities.add(entity); + } + batch.insertWithDeferredIdAllocation(entities); + DatastoreBatch.Response response = batch.submit(); + assertTrue(response.getGeneratedKeys().size() == 5); + } + + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_StringId() { + DatastoreBatch batch = em.newBatch(); + StringId entity = new StringId(); + entity.setGreetings("Batch Insert Test with Deferred String ID Allocation"); + batch.insertWithDeferredIdAllocation(entity); + } + + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_StringId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + StringId entity = new StringId(); + entities.add(entity); + } + batch.insertWithDeferredIdAllocation(entities); + } + + @Test + public void testUpdate() { + LongId entity = new LongId(); + entity.setField1("Test for Batch Update"); + entity = em.insert(entity); + entity = em.load(LongId.class, entity.getId()); + entity.setField1("Updated"); + DatastoreBatch batch = em.newBatch(); + entity = batch.update(entity); + batch.submit(); + LongId entity2 = em.load(LongId.class, entity.getId()); + assertTrue("Updated".equals(entity2.getField1())); + } + + @Test + public void testUpdate_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + entities.add(new LongId()); + } + entities = em.insert(entities); + for (LongId entity : entities) { + entity.setField1("Updated"); + } + DatastoreBatch batch = em.newBatch(); + entities = batch.update(entities); + batch.submit(); + List identifiers = new ArrayList<>(); + for (LongId entity : entities) { + identifiers.add(entity.getId()); + } + List entities2 = em.loadById(LongId.class, identifiers); + assertTrue(entities.equals(entities2)); + } + + @Test + public void testUpdate_OptimisticLock() { + DatastoreBatch batch = em.newBatch(); + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Batch Update Test"); + entity = em.insert(entity); + entity = em.load(OptimisticLock1.class, entity.getId()); + entity.setName("Batch Update Test - Updated"); + entity = batch.update(entity); + batch.submit(); + entity = em.load(OptimisticLock1.class, entity.getId()); + assertTrue(entity.getVersion() == 1); + } + + @Test + public void testUpsert_LongId() { + DatastoreBatch batch = em.newBatch(); + LongId entity = new LongId(); + entity.setField1("Batch Upsert Test"); + LongId entity2 = batch.upsert(entity); + batch.submit(); + LongId entity3 = em.load(LongId.class, entity2.getId()); + assertTrue(entity2.equals(entity3)); + } + + @Test + public void testUpsert_LongId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + LongId entity = new LongId(); + entity.setField1("Batch Upsert Test " + i); + entities.add(entity); + } + List insertedEntities = batch.upsert(entities); + batch.submit(); + List identifiers = new ArrayList<>(); + for (LongId entity : insertedEntities) { + identifiers.add(entity.getId()); + } + List retrievedEntities = em.loadById(LongId.class, identifiers); + assertTrue(insertedEntities.equals(retrievedEntities)); + } + + @Test + public void testUpsertWithDeferredIdAllocation_LongId() { + DatastoreBatch batch = em.newBatch(); + LongId entity = new LongId(); + entity.setField1("Batch Upsert Test with Deferred ID Allocation"); + batch.upsertWithDeferredIdAllocation(entity); + DatastoreBatch.Response response = batch.submit(); + assertTrue(response.getGeneratedKeys().size() == 1); + } + + @Test + public void testUpsertWithDeferredIdAllocation_LongId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + LongId entity = new LongId(); + entity.setField1("Batch Upsert Test with Deferred ID Allocation " + i); + entities.add(entity); + } + batch.upsertWithDeferredIdAllocation(entities); + DatastoreBatch.Response response = batch.submit(); + assertTrue(response.getGeneratedKeys().size() == 5); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertWithDeferredIdAllocation_StringId() { + DatastoreBatch batch = em.newBatch(); + StringId entity = new StringId(); + entity.setGreetings("Batch Insert Test with Deferred String ID Allocation"); + batch.upsertWithDeferredIdAllocation(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertWithDeferredIdAllocation_StringId_List() { + DatastoreBatch batch = em.newBatch(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + StringId entity = new StringId(); + entities.add(entity); + } + batch.upsertWithDeferredIdAllocation(entities); + } + + @Test + public void testDelete_Object() { + LongId entity = em.insert(new LongId()); + DatastoreBatch batch = em.newBatch(); + batch.delete(entity); + batch.submit(); + LongId retrievedEntity = em.load(LongId.class, entity.getId()); + assertNull(retrievedEntity); + } + + @Test + public void testDelete_ListOfObjects() { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + entities.add(new LongId()); + } + entities = em.insert(entities); + List identifiers = new ArrayList<>(); + for (LongId entity : entities) { + identifiers.add(entity.getId()); + } + DatastoreBatch batch = em.newBatch(); + batch.delete(entities); + batch.submit(); + List retrievedEntities = em.loadById(LongId.class, identifiers); + assertTrue(retrievedEntities.get(0) == null && retrievedEntities.get(1) == null + && retrievedEntities.get(2) == null && retrievedEntities.get(3) == null + && retrievedEntities.get(4) == null); + } + + @Test + public void testDeleteByKey() { + ParentEntity entity = new ParentEntity(); + entity = em.insert(entity); + DatastoreBatch batch = em.newBatch(); + DatastoreKey key = entity.getKey(); + batch.deleteByKey(key); + batch.submit(); + ParentEntity retrievedEntity = em.load(ParentEntity.class, entity.getId()); + assertNull(retrievedEntity); + } + + @Test + public void testDeleteByKey_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + ParentEntity entity = new ParentEntity(); + entities.add(entity); + } + entities = em.insert(entities); + List keys = new ArrayList<>(); + List identifiers = new ArrayList<>(); + for (ParentEntity entity : entities) { + keys.add(entity.getKey()); + identifiers.add(entity.getId()); + } + DatastoreBatch batch = em.newBatch(); + batch.deleteByKey(keys); + batch.submit(); + List retrievedEntities = em.loadById(ParentEntity.class, identifiers); + assertTrue(retrievedEntities.get(0) == null && retrievedEntities.get(1) == null + && retrievedEntities.get(2) == null); + } + + @Test + public void testInsertParentChild() { + DatastoreBatch batch = em.newBatch(); + ParentEntity parent = new ParentEntity(); + parent = batch.insert(parent); + ChildEntity child = new ChildEntity(); + child.setParentKey(parent.getKey()); + child = batch.insert(child); + batch.submit(); + ChildEntity child2 = em.load(ChildEntity.class, parent.getKey(), child.getId()); + System.out.println(child2.getKey().getEncoded()); + assertTrue(child2.getId() == child.getId() && child2.getParentKey().equals(parent.getKey())); + } + + @Test + public void testInsert_Upsert() { + LongId entity = new LongId(); + entity.setId(100); + em.insert(entity); + DatastoreBatch batch = em.newBatch(); + batch.delete(entity); + entity.setField1("Updated"); + batch.insert(entity); + batch.submit(); + entity = em.load(LongId.class, entity.getId()); + assertTrue(entity != null); + } + + @Test(expected = EntityManagerException.class) + public void testInactiveBatch() { + DatastoreBatch batch = em.newBatch(); + LongId entity = new LongId(); + entity.setField1("Batch Insert Test"); + LongId entity2 = batch.insert(entity); + batch.submit(); + batch.delete(entity2); + } + + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_ProjectedEntity() { + DatastoreBatch batch = em.newBatch(); + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe"); + batch.insertWithDeferredIdAllocation(entity); + } + + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_ProjectedEntityList() { + List contacts = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + ContactProjection contact = new ContactProjection(); + contact.setLastName("Doe " + i); + contacts.add(contact); + } + DatastoreBatch batch = em.newBatch(); + batch.insertWithDeferredIdAllocation(contacts); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertWithDeferredIdAllocation_ProjectedEntity() { + DatastoreBatch batch = em.newBatch(); + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe"); + batch.upsertWithDeferredIdAllocation(entity); + DatastoreBatch.Response response = batch.submit(); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertWithDeferredIdAllocation_ProjectedEntityList() { + List contacts = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + ContactProjection contact = new ContactProjection(); + contact.setLastName("Doe " + i); + contacts.add(contact); + } + DatastoreBatch batch = em.newBatch(); + batch.upsertWithDeferredIdAllocation(contacts); + } + + @Test(expected = EntityManagerException.class) + public void testUpdate_ProjectedEntity() { + Contact entity = Contact.createContact1(); + entity = em.insert(entity); + ContactProjection projectedEntity = em.load(ContactProjection.class, entity.getId()); + entity.setLastName("Doe Updated"); + DatastoreBatch batch = em.newBatch(); + projectedEntity = batch.update(projectedEntity); + batch.submit(); + } + + @Test(expected = EntityAlreadyExistsException.class) + public void testInsertDuplicateKey() { + StringField entity = new StringField(); + entity.setName("Test for Duplicate Key from Transaction"); + StringField entity2 = em.insert(entity); + DatastoreBatch batch = em.newBatch(); + try { + batch.insertWithDeferredIdAllocation(entity2); + batch.submit(); + } catch (EntityAlreadyExistsException exp) { + throw exp; + } catch (EntityManagerException exp) { + String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); + if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { + // Running on emulator that has a bug. + throw new EntityAlreadyExistsException(exp); + } + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/DatastoreMetadataTest.java b/src/test/java/com/jmethods/catatumbo/DatastoreMetadataTest.java index bd7fdf0..4db1cfc 100644 --- a/src/test/java/com/jmethods/catatumbo/DatastoreMetadataTest.java +++ b/src/test/java/com/jmethods/catatumbo/DatastoreMetadataTest.java @@ -36,131 +36,131 @@ */ public class DatastoreMetadataTest { - private static EntityManager em = null; - - private List createdNamespaces; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } - - @Before - public void beforeEachTest() { - createdNamespaces = new ArrayList<>(); - } - - @After - public void afterEachTest() { - String backupNamespace = Tenant.getNamespace(); - try { - for (String namespace : createdNamespaces) { - Tenant.setNamespace(namespace); - em.deleteAll(StringField.class); - } - } finally { - Tenant.setNamespace(backupNamespace); - } - } - - @Test - public void testGetNamespaces() { - long millis = System.currentTimeMillis(); - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - String namespace = String.valueOf(millis + i); - StringField entity = new StringField(); - entity.setName("I'm in namespace " + namespace); - entity = createEntity(entity, namespace); - entities.add(entity); - createdNamespaces.add(namespace); - } - DatastoreMetadata dmd = em.getDatastoreMetadata(); - List namespaces = dmd.getNamespaces(); - assertTrue(namespaces.contains(String.valueOf(millis))); - assertTrue(namespaces.contains(String.valueOf(millis + 1))); - } - - @Test - public void testGetNamespaces_Limit() { - long millis = System.currentTimeMillis(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - String namespace = String.valueOf(millis + i); - StringField entity = new StringField(); - entity.setName("I'm in namespace " + namespace); - entity = createEntity(entity, namespace); - entities.add(entity); - createdNamespaces.add(namespace); - } - DatastoreMetadata dmd = em.getDatastoreMetadata(); - List namespaces = dmd.getNamespaces(2).getResults(); - assertEquals(2, namespaces.size()); - } - - @Test - public void testGetNamespaces_FromCursor_Limit() { - long millis = System.currentTimeMillis(); - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - String namespace = String.valueOf(millis + i); - StringField entity = new StringField(); - entity.setName("I'm in namespace " + namespace); - entity = createEntity(entity, namespace); - entities.add(entity); - createdNamespaces.add(namespace); - } - DatastoreMetadata dmd = em.getDatastoreMetadata(); - QueryResponse response = dmd.getNamespaces(2); - DatastoreCursor nextPageCursor = response.getEndCursor(); - List namespaces = dmd.getNamespaces(nextPageCursor, 2).getResults(); - assertEquals(2, namespaces.size()); - } - - @Test - public void testGetKinds() { - StringField entity = new StringField(); - entity.setName("Test for getKinds()"); - entity = em.insert(entity); - DatastoreMetadata dmd = em.getDatastoreMetadata(); - List kinds = dmd.getKinds(); - assertTrue(kinds.contains(EntityIntrospector.introspect(StringField.class).getKind())); - } - - @Test - public void testGetKinds_ExcludeSystemKinds() { - StringField entity = new StringField(); - entity.setName("Test for getKinds()"); - entity = em.insert(entity); - DatastoreMetadata dmd = em.getDatastoreMetadata(); - List kinds = dmd.getKinds(true); - assertTrue(kinds.contains(EntityIntrospector.introspect(StringField.class).getKind())); - // This may give false positive (e.g. no Stat entities are yet available - // or testing with Emulator. - for (String kind : kinds) { - assertTrue(!kind.startsWith("__")); - } - } - - @Test - public void testGetProperties() { - StringField entity = new StringField(); - entity.setName("Test for getProperties()"); - em.insert(entity); - List properties = em.getDatastoreMetadata() - .getProperties(EntityIntrospector.introspect(StringField.class).getKind()); - assertEquals("name", properties.get(0).getName()); - } - - private E createEntity(E entity, String namespace) { - String backupNamespace = Tenant.getNamespace(); - try { - Tenant.setNamespace(namespace); - return em.insert(entity); - } finally { - Tenant.setNamespace(backupNamespace); - } - - } + private static EntityManager em = null; + + private List createdNamespaces; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } + + @Before + public void beforeEachTest() { + createdNamespaces = new ArrayList<>(); + } + + @After + public void afterEachTest() { + String backupNamespace = Tenant.getNamespace(); + try { + for (String namespace : createdNamespaces) { + Tenant.setNamespace(namespace); + em.deleteAll(StringField.class); + } + } finally { + Tenant.setNamespace(backupNamespace); + } + } + + @Test + public void testGetNamespaces() { + long millis = System.currentTimeMillis(); + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + String namespace = String.valueOf(millis + i); + StringField entity = new StringField(); + entity.setName("I'm in namespace " + namespace); + entity = createEntity(entity, namespace); + entities.add(entity); + createdNamespaces.add(namespace); + } + DatastoreMetadata dmd = em.getDatastoreMetadata(); + List namespaces = dmd.getNamespaces(); + assertTrue(namespaces.contains(String.valueOf(millis))); + assertTrue(namespaces.contains(String.valueOf(millis + 1))); + } + + @Test + public void testGetNamespaces_Limit() { + long millis = System.currentTimeMillis(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + String namespace = String.valueOf(millis + i); + StringField entity = new StringField(); + entity.setName("I'm in namespace " + namespace); + entity = createEntity(entity, namespace); + entities.add(entity); + createdNamespaces.add(namespace); + } + DatastoreMetadata dmd = em.getDatastoreMetadata(); + List namespaces = dmd.getNamespaces(2).getResults(); + assertEquals(2, namespaces.size()); + } + + @Test + public void testGetNamespaces_FromCursor_Limit() { + long millis = System.currentTimeMillis(); + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + String namespace = String.valueOf(millis + i); + StringField entity = new StringField(); + entity.setName("I'm in namespace " + namespace); + entity = createEntity(entity, namespace); + entities.add(entity); + createdNamespaces.add(namespace); + } + DatastoreMetadata dmd = em.getDatastoreMetadata(); + QueryResponse response = dmd.getNamespaces(2); + DatastoreCursor nextPageCursor = response.getEndCursor(); + List namespaces = dmd.getNamespaces(nextPageCursor, 2).getResults(); + assertEquals(2, namespaces.size()); + } + + @Test + public void testGetKinds() { + StringField entity = new StringField(); + entity.setName("Test for getKinds()"); + entity = em.insert(entity); + DatastoreMetadata dmd = em.getDatastoreMetadata(); + List kinds = dmd.getKinds(); + assertTrue(kinds.contains(EntityIntrospector.introspect(StringField.class).getKind())); + } + + @Test + public void testGetKinds_ExcludeSystemKinds() { + StringField entity = new StringField(); + entity.setName("Test for getKinds()"); + entity = em.insert(entity); + DatastoreMetadata dmd = em.getDatastoreMetadata(); + List kinds = dmd.getKinds(true); + assertTrue(kinds.contains(EntityIntrospector.introspect(StringField.class).getKind())); + // This may give false positive (e.g. no Stat entities are yet available + // or testing with Emulator. + for (String kind : kinds) { + assertTrue(!kind.startsWith("__")); + } + } + + @Test + public void testGetProperties() { + StringField entity = new StringField(); + entity.setName("Test for getProperties()"); + em.insert(entity); + List properties = em.getDatastoreMetadata() + .getProperties(EntityIntrospector.introspect(StringField.class).getKind()); + assertEquals("name", properties.get(0).getName()); + } + + private E createEntity(E entity, String namespace) { + String backupNamespace = Tenant.getNamespace(); + try { + Tenant.setNamespace(namespace); + return em.insert(entity); + } finally { + Tenant.setNamespace(backupNamespace); + } + + } } diff --git a/src/test/java/com/jmethods/catatumbo/DatastoreStatsTest.java b/src/test/java/com/jmethods/catatumbo/DatastoreStatsTest.java index 53f89e8..060dd0a 100644 --- a/src/test/java/com/jmethods/catatumbo/DatastoreStatsTest.java +++ b/src/test/java/com/jmethods/catatumbo/DatastoreStatsTest.java @@ -48,221 +48,232 @@ * */ public class DatastoreStatsTest { - private static EntityManager em = null; - private static DatastoreStats stats = null; - private static Datastore datastore = null; + private static EntityManager em = null; + private static DatastoreStats stats = null; + private static Datastore datastore = null; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - stats = em.getDatastoreStats(); - datastore = ((DefaultEntityManager) em).getDatastore(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + stats = em.getDatastoreStats(); + datastore = ((DefaultEntityManager) em).getDatastore(); + } - @Test - public void testGetSummary() { - StatTotal stat = stats.getSummary(); - com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace("") - .setKind(StatConstants.STAT_TOTAL).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); - assertTrue(equals(stat, nativeEntity)); - } + @Test + public void testGetSummary() { + StatTotal stat = stats.getSummary(); + com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace("") + .setKind(StatConstants.STAT_TOTAL).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); + assertTrue(equals(stat, nativeEntity)); + } - @Test - public void testGetSummaryNs() { - StatTotalNs stat = stats.getSummaryNs(); - com.google.cloud.datastore.Key key = datastore.newKeyFactory().setKind(StatConstants.STAT_TOTAL_NS) - .newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); - assertTrue(equals(stat, nativeEntity)); - } + @Test + public void testGetSummaryNs() { + StatTotalNs stat = stats.getSummaryNs(); + com.google.cloud.datastore.Key key = datastore.newKeyFactory() + .setKind(StatConstants.STAT_TOTAL_NS).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); + assertTrue(equals(stat, nativeEntity)); + } - @Test - public void testGetSummaryNs_ValidNamespace() { - final String namespace = "junit"; - StatTotalNs stat = stats.getSummaryNs(namespace); - com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace(namespace) - .setKind(StatConstants.STAT_TOTAL_NS).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); - assertTrue(equals(stat, nativeEntity)); - } + @Test + public void testGetSummaryNs_ValidNamespace() { + final String namespace = "junit"; + StatTotalNs stat = stats.getSummaryNs(namespace); + com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace(namespace) + .setKind(StatConstants.STAT_TOTAL_NS).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); + assertTrue(equals(stat, nativeEntity)); + } - @Test - public void testGetSummaryNs_InvalidNamespace() { - final String namespace = "junit9999999999"; - StatTotalNs stat = stats.getSummaryNs(namespace); - com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace(namespace) - .setKind(StatConstants.STAT_TOTAL_NS).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); - assertNull(stat); - assertNull(nativeEntity); - assertTrue(equals(stat, nativeEntity)); - } + @Test + public void testGetSummaryNs_InvalidNamespace() { + final String namespace = "junit9999999999"; + StatTotalNs stat = stats.getSummaryNs(namespace); + com.google.cloud.datastore.Key key = datastore.newKeyFactory().setNamespace(namespace) + .setKind(StatConstants.STAT_TOTAL_NS).newKey(StatConstants.ID_TOTAL_ENTITY_USAGE); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(key); + assertNull(stat); + assertNull(nativeEntity); + assertTrue(equals(stat, nativeEntity)); + } - @Test - public void testGetKinds() { - List statEntities = stats.getKinds(); - Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND).build(); - QueryResults results = datastore.run(query); - int i = 0; - while (results.hasNext()) { - StatKind statEntity = statEntities.get(i); - com.google.cloud.datastore.Entity nativeEntity = results.next(); - assertTrue(equals(statEntity, nativeEntity)); - i++; - } - } + @Test + public void testGetKinds() { + List statEntities = stats.getKinds(); + Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND) + .build(); + QueryResults results = datastore.run(query); + int i = 0; + while (results.hasNext()) { + StatKind statEntity = statEntities.get(i); + com.google.cloud.datastore.Entity nativeEntity = results.next(); + assertTrue(equals(statEntity, nativeEntity)); + i++; + } + } - @Test - public void testGetKind() { - final String kindName = "StringField"; - StatKind statEntity = stats.getKind(kindName); - Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND) - .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)).build(); - QueryResults results = datastore.run(query); - com.google.cloud.datastore.Entity nativeEntity = null; - if (results.hasNext()) { - nativeEntity = results.next(); - } - assertTrue(equals(statEntity, nativeEntity)); + @Test + public void testGetKind() { + final String kindName = "StringField"; + StatKind statEntity = stats.getKind(kindName); + Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND) + .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) + .build(); + QueryResults results = datastore.run(query); + com.google.cloud.datastore.Entity nativeEntity = null; + if (results.hasNext()) { + nativeEntity = results.next(); + } + assertTrue(equals(statEntity, nativeEntity)); - } + } - @Test - public void testGetKindsNs() { - List statEntities = stats.getKindsNs(); - Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS).build(); - QueryResults results = datastore.run(query); - int i = 0; - while (results.hasNext()) { - StatKindNs statEntity = statEntities.get(i); - com.google.cloud.datastore.Entity nativeEntity = results.next(); - assertTrue(equals(statEntity, nativeEntity)); - i++; - } - } + @Test + public void testGetKindsNs() { + List statEntities = stats.getKindsNs(); + Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS).build(); + QueryResults results = datastore.run(query); + int i = 0; + while (results.hasNext()) { + StatKindNs statEntity = statEntities.get(i); + com.google.cloud.datastore.Entity nativeEntity = results.next(); + assertTrue(equals(statEntity, nativeEntity)); + i++; + } + } - @Test - public void testGetKindNs_KindName() { - final String kindName = "StringField"; - StatKindNs statEntity = stats.getKindNs(kindName); - Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS) - .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)).build(); - QueryResults results = datastore.run(query); - com.google.cloud.datastore.Entity nativeEntity = null; - if (results.hasNext()) { - nativeEntity = results.next(); - } - assertTrue(equals(statEntity, nativeEntity)); - } + @Test + public void testGetKindNs_KindName() { + final String kindName = "StringField"; + StatKindNs statEntity = stats.getKindNs(kindName); + Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS) + .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) + .build(); + QueryResults results = datastore.run(query); + com.google.cloud.datastore.Entity nativeEntity = null; + if (results.hasNext()) { + nativeEntity = results.next(); + } + assertTrue(equals(statEntity, nativeEntity)); + } - @Test - public void testGetKindNs_Namespace_KindName() { - final String namespace = "junit"; - final String kindName = "StringField"; - StatKindNs statEntity = stats.getKindNs(namespace, kindName); - Query query = Query.newEntityQueryBuilder().setNamespace(namespace).setKind(StatConstants.STAT_KIND_NS) - .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)).build(); - QueryResults results = datastore.run(query); - com.google.cloud.datastore.Entity nativeEntity = null; - if (results.hasNext()) { - nativeEntity = results.next(); - } - assertTrue(equals(statEntity, nativeEntity)); - } + @Test + public void testGetKindNs_Namespace_KindName() { + final String namespace = "junit"; + final String kindName = "StringField"; + StatKindNs statEntity = stats.getKindNs(namespace, kindName); + Query query = Query.newEntityQueryBuilder().setNamespace(namespace) + .setKind(StatConstants.STAT_KIND_NS) + .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) + .build(); + QueryResults results = datastore.run(query); + com.google.cloud.datastore.Entity nativeEntity = null; + if (results.hasNext()) { + nativeEntity = results.next(); + } + assertTrue(equals(statEntity, nativeEntity)); + } - @Test - public void testGetCompositeIndexes() { - List statEntities = stats.getCompositeIndexes(); - Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_COMPOSITE_INDEX) - .build(); - QueryResults results = datastore.run(query); - int i = 0; - while (results.hasNext()) { - StatCompositeIndex statEntity = statEntities.get(i); - com.google.cloud.datastore.Entity nativeEntity = results.next(); - assertTrue(equals(statEntity, nativeEntity)); - i++; - } - } + @Test + public void testGetCompositeIndexes() { + List statEntities = stats.getCompositeIndexes(); + Query query = Query.newEntityQueryBuilder().setNamespace("") + .setKind(StatConstants.STAT_COMPOSITE_INDEX).build(); + QueryResults results = datastore.run(query); + int i = 0; + while (results.hasNext()) { + StatCompositeIndex statEntity = statEntities.get(i); + com.google.cloud.datastore.Entity nativeEntity = results.next(); + assertTrue(equals(statEntity, nativeEntity)); + i++; + } + } - @Test - public void testGetCompositeIndexesNs() { - List statEntities = stats.getCompositeIndexesNs(); - Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_COMPOSITE_INDEX_NS).build(); - QueryResults results = datastore.run(query); - int i = 0; - while (results.hasNext()) { - StatCompositeIndexNs statEntity = statEntities.get(i); - com.google.cloud.datastore.Entity nativeEntity = results.next(); - assertTrue(equals(statEntity, nativeEntity)); - i++; - } - } + @Test + public void testGetCompositeIndexesNs() { + List statEntities = stats.getCompositeIndexesNs(); + Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_COMPOSITE_INDEX_NS) + .build(); + QueryResults results = datastore.run(query); + int i = 0; + while (results.hasNext()) { + StatCompositeIndexNs statEntity = statEntities.get(i); + com.google.cloud.datastore.Entity nativeEntity = results.next(); + assertTrue(equals(statEntity, nativeEntity)); + i++; + } + } - @Test - public void testGetCompositeIndexesNs_Namespace() { - final String namespace = "junit"; - List statEntities = stats.getCompositeIndexesNs(namespace); - Query query = Query.newEntityQueryBuilder().setNamespace(namespace) - .setKind(StatConstants.STAT_COMPOSITE_INDEX_NS).build(); - QueryResults results = datastore.run(query); - int i = 0; - while (results.hasNext()) { - StatCompositeIndexNs statEntity = statEntities.get(i); - com.google.cloud.datastore.Entity nativeEntity = results.next(); - assertTrue(equals(statEntity, nativeEntity)); - i++; - } - } + @Test + public void testGetCompositeIndexesNs_Namespace() { + final String namespace = "junit"; + List statEntities = stats.getCompositeIndexesNs(namespace); + Query query = Query.newEntityQueryBuilder().setNamespace(namespace) + .setKind(StatConstants.STAT_COMPOSITE_INDEX_NS).build(); + QueryResults results = datastore.run(query); + int i = 0; + while (results.hasNext()) { + StatCompositeIndexNs statEntity = statEntities.get(i); + com.google.cloud.datastore.Entity nativeEntity = results.next(); + assertTrue(equals(statEntity, nativeEntity)); + i++; + } + } - private static boolean equals(StatTotalBase stat, com.google.cloud.datastore.Entity entity) { - if (stat != null && entity != null) { - return stat.getBuiltinIndexBytes() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_BYTES) - && stat.getBuiltinIndexCount() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_COUNT) - && stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) - && stat.getCompositeIndexBytes() == entity.getLong(StatConstants.PROP_COMPOSITE_INDEX_BYTES) - && stat.getCompositeIndexCount() == entity.getLong(StatConstants.PROP_COMPOSITE_INDEX_COUNT) - && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) - && stat.getEntityBytes() == entity.getLong(StatConstants.PROP_ENTITY_BYTES) - && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); - } - return stat == null && entity == null; - } + private static boolean equals(StatTotalBase stat, com.google.cloud.datastore.Entity entity) { + if (stat != null && entity != null) { + return stat.getBuiltinIndexBytes() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_BYTES) + && stat.getBuiltinIndexCount() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_COUNT) + && stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) + && stat.getCompositeIndexBytes() == entity + .getLong(StatConstants.PROP_COMPOSITE_INDEX_BYTES) + && stat.getCompositeIndexCount() == entity + .getLong(StatConstants.PROP_COMPOSITE_INDEX_COUNT) + && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) + && stat.getEntityBytes() == entity.getLong(StatConstants.PROP_ENTITY_BYTES) + && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); + } + return stat == null && entity == null; + } - private static boolean equals(StatKindBase stat, com.google.cloud.datastore.Entity entity) { - if (stat != null && entity != null) { - return stat.getBuiltinIndexBytes() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_BYTES) - && stat.getBuiltinIndexCount() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_COUNT) - && stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) - && stat.getCompositeIndexBytes() == entity.getLong(StatConstants.PROP_COMPOSITE_INDEX_BYTES) - && stat.getCompositeIndexCount() == entity.getLong(StatConstants.PROP_COMPOSITE_INDEX_COUNT) - && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) - && stat.getEntityBytes() == entity.getLong(StatConstants.PROP_ENTITY_BYTES) - && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) - && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); - } - return stat == null && entity == null; - } + private static boolean equals(StatKindBase stat, com.google.cloud.datastore.Entity entity) { + if (stat != null && entity != null) { + return stat.getBuiltinIndexBytes() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_BYTES) + && stat.getBuiltinIndexCount() == entity.getLong(StatConstants.PROP_BUILTIN_INDEX_COUNT) + && stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) + && stat.getCompositeIndexBytes() == entity + .getLong(StatConstants.PROP_COMPOSITE_INDEX_BYTES) + && stat.getCompositeIndexCount() == entity + .getLong(StatConstants.PROP_COMPOSITE_INDEX_COUNT) + && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) + && stat.getEntityBytes() == entity.getLong(StatConstants.PROP_ENTITY_BYTES) + && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) + && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); + } + return stat == null && entity == null; + } - private static boolean equals(StatCompositeIndexBase stat, com.google.cloud.datastore.Entity entity) { - if (stat != null && entity != null) { - return stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) - && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) - && stat.getIndexId() == entity.getLong(StatConstants.PROP_INDEX_ID) - && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) - && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) - && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); + private static boolean equals(StatCompositeIndexBase stat, + com.google.cloud.datastore.Entity entity) { + if (stat != null && entity != null) { + return stat.getBytes() == entity.getLong(StatConstants.PROP_BYTES) + && stat.getCount() == entity.getLong(StatConstants.PROP_COUNT) + && stat.getIndexId() == entity.getLong(StatConstants.PROP_INDEX_ID) + && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) + && stat.getKindName().equals(entity.getString(StatConstants.PROP_KIND_NAME)) + && equals(stat.getTimestamp(), entity.getTimestamp(StatConstants.PROP_TIMESTAMP)); - } - return stat == null && entity == null; - } + } + return stat == null && entity == null; + } - private static boolean equals(Date date, Timestamp timestamp) { - long ms1 = date.getTime(); - long ms2 = TimeUnit.SECONDS.toMillis(timestamp.getSeconds()) - + TimeUnit.NANOSECONDS.toMillis(timestamp.getNanos()); - return ms1 == ms2; - } + private static boolean equals(Date date, Timestamp timestamp) { + long ms1 = date.getTime(); + long ms2 = TimeUnit.SECONDS.toMillis(timestamp.getSeconds()) + + TimeUnit.NANOSECONDS.toMillis(timestamp.getNanos()); + return ms1 == ms2; + } } diff --git a/src/test/java/com/jmethods/catatumbo/DatastoreTransactionTest.java b/src/test/java/com/jmethods/catatumbo/DatastoreTransactionTest.java index 417fc34..228a358 100644 --- a/src/test/java/com/jmethods/catatumbo/DatastoreTransactionTest.java +++ b/src/test/java/com/jmethods/catatumbo/DatastoreTransactionTest.java @@ -40,259 +40,259 @@ */ public class DatastoreTransactionTest { - private static EntityManager em = null; + private static EntityManager em = null; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test(expected = EntityManagerException.class) - public void testUpdate() { - Account a1 = new Account(); - a1.setName("Transaction Test"); - a1.setEmail("user@example.com"); - a1 = em.insert(a1); + @Test(expected = EntityManagerException.class) + public void testUpdate() { + Account a1 = new Account(); + a1.setName("Transaction Test"); + a1.setEmail("user@example.com"); + a1 = em.insert(a1); - DatastoreTransaction t1 = em.newTransaction(); - DatastoreTransaction t2 = em.newTransaction(); + DatastoreTransaction t1 = em.newTransaction(); + DatastoreTransaction t2 = em.newTransaction(); - try { - Account account1 = t1.load(Account.class, a1.getId()); - Account account2 = t2.load(Account.class, a1.getId()); + try { + Account account1 = t1.load(Account.class, a1.getId()); + Account account2 = t2.load(Account.class, a1.getId()); - account1.setName("Transaction Test from 1st Transaction"); - account2.setName("Transaction Test from 2nd Transaction"); + account1.setName("Transaction Test from 1st Transaction"); + account2.setName("Transaction Test from 2nd Transaction"); - t1.update(account1); - t2.update(account2); - t1.commit(); - System.out.println("Transaction 1 Committed successfully"); - t2.commit(); - // This should never succeed - System.out.println("Transaction 2 Committed successfully"); - } catch (Exception exp) { - System.out.println(exp.getMessage()); - throw exp; - } finally { - if (t1.isActive()) { - t1.rollback(); - } - if (t2.isActive()) { - t2.rollback(); - } - } + t1.update(account1); + t2.update(account2); + t1.commit(); + System.out.println("Transaction 1 Committed successfully"); + t2.commit(); + // This should never succeed + System.out.println("Transaction 2 Committed successfully"); + } catch (Exception exp) { + System.out.println(exp.getMessage()); + throw exp; + } finally { + if (t1.isActive()) { + t1.rollback(); + } + if (t2.isActive()) { + t2.rollback(); + } + } - } + } - @Test - public void testInsert_OptimisticLock1() { - DatastoreTransaction transaction = em.newTransaction(); - try { - Account entity = new Account(); - entity.setName("Version Test"); - entity.setEmail("user@example.com"); - Account entity2 = transaction.insert(entity); - transaction.commit(); - assertTrue(entity2.getId() != 0 && entity2.getVersion() == 1); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test + public void testInsert_OptimisticLock1() { + DatastoreTransaction transaction = em.newTransaction(); + try { + Account entity = new Account(); + entity.setName("Version Test"); + entity.setEmail("user@example.com"); + Account entity2 = transaction.insert(entity); + transaction.commit(); + assertTrue(entity2.getId() != 0 && entity2.getVersion() == 1); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test - public void testUpdate_OptimisticLock1() { - DatastoreTransaction transaction = em.newTransaction(); - try { - Account entity = new Account(); - entity.setName("Hello World!"); - entity = em.insert(entity); - entity = transaction.load(Account.class, entity.getId()); - entity.setName("Hello World! After Update!!"); - entity = transaction.update(entity); - transaction.commit(); - assertTrue(entity.getId() != 0 && entity.getVersion() == 2); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } + @Test + public void testUpdate_OptimisticLock1() { + DatastoreTransaction transaction = em.newTransaction(); + try { + Account entity = new Account(); + entity.setName("Hello World!"); + entity = em.insert(entity); + entity = transaction.load(Account.class, entity.getId()); + entity.setName("Hello World! After Update!!"); + entity = transaction.update(entity); + transaction.commit(); + assertTrue(entity.getId() != 0 && entity.getVersion() == 2); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } - } + } - @Test(expected = EntityManagerException.class) - public void testUpdate_OptimisticLock2() { - DatastoreTransaction transaction = em.newTransaction(); - try { - Account entity = new Account(); - entity.setName("Hello World!"); - entity = em.insert(entity); - Account entity2 = em.load(Account.class, entity.getId()); - entity2.setName("Hello World! After Update!!"); - entity2 = transaction.update(entity2); - entity2 = transaction.update(entity2); - entity2 = transaction.update(entity2); - entity = transaction.update(entity); - transaction.commit(); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test(expected = EntityManagerException.class) + public void testUpdate_OptimisticLock2() { + DatastoreTransaction transaction = em.newTransaction(); + try { + Account entity = new Account(); + entity.setName("Hello World!"); + entity = em.insert(entity); + Account entity2 = em.load(Account.class, entity.getId()); + entity2.setName("Hello World! After Update!!"); + entity2 = transaction.update(entity2); + entity2 = transaction.update(entity2); + entity2 = transaction.update(entity2); + entity = transaction.update(entity); + transaction.commit(); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test - public void testUpdate_OptimisticLock3() { - DatastoreTransaction transaction = em.newTransaction(); - try { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - Account entity = new Account(); - entity.setName("Test Insert from Transaction " + i); - entities.add(entity); - } - List entities2 = transaction.insert(entities); - transaction.commit(); - assertEquals(1, entities2.get(0).getVersion()); - assertEquals(1, entities2.get(1).getVersion()); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test + public void testUpdate_OptimisticLock3() { + DatastoreTransaction transaction = em.newTransaction(); + try { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + Account entity = new Account(); + entity.setName("Test Insert from Transaction " + i); + entities.add(entity); + } + List entities2 = transaction.insert(entities); + transaction.commit(); + assertEquals(1, entities2.get(0).getVersion()); + assertEquals(1, entities2.get(1).getVersion()); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test - public void testUpdate_OptimisticLock4() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - Account entity = new Account(); - entity.setName("Test Update from Transaction " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - DatastoreTransaction transaction = em.newTransaction(); - try { - List entities3 = transaction.update(entities2); - transaction.commit(); - assertEquals(1, entities2.get(0).getVersion()); - assertEquals(1, entities2.get(1).getVersion()); - assertEquals(2, entities3.get(0).getVersion()); - assertEquals(2, entities3.get(1).getVersion()); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test + public void testUpdate_OptimisticLock4() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + Account entity = new Account(); + entity.setName("Test Update from Transaction " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + DatastoreTransaction transaction = em.newTransaction(); + try { + List entities3 = transaction.update(entities2); + transaction.commit(); + assertEquals(1, entities2.get(0).getVersion()); + assertEquals(1, entities2.get(1).getVersion()); + assertEquals(2, entities3.get(0).getVersion()); + assertEquals(2, entities3.get(1).getVersion()); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test - public void testInsertWithDeferredIdAllocation_LongId() { - DatastoreTransaction transaction = em.newTransaction(); - try { - LongId entity = new LongId(); - entity.setField1("Transaction Insert Test with Deferred ID Allocation"); - transaction.insertWithDeferredIdAllocation(entity); - DatastoreTransaction.Response response = transaction.commit(); - assertTrue(response.getGeneratedKeys().size() == 1); + @Test + public void testInsertWithDeferredIdAllocation_LongId() { + DatastoreTransaction transaction = em.newTransaction(); + try { + LongId entity = new LongId(); + entity.setField1("Transaction Insert Test with Deferred ID Allocation"); + transaction.insertWithDeferredIdAllocation(entity); + DatastoreTransaction.Response response = transaction.commit(); + assertTrue(response.getGeneratedKeys().size() == 1); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test - public void testInsertWithDeferredIdAllocation_LongId_List() { - DatastoreTransaction transaction = em.newTransaction(); - try { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - LongId entity = new LongId(); - entity.setField1("Transaction Insert Test with Deferred ID Allocation " + i); - entities.add(entity); - } - transaction.insertWithDeferredIdAllocation(entities); - DatastoreTransaction.Response response = transaction.commit(); - // Leaving this call to the deprecated method - assertTrue(response.getGeneratedKeys().size() == 5); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test + public void testInsertWithDeferredIdAllocation_LongId_List() { + DatastoreTransaction transaction = em.newTransaction(); + try { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + LongId entity = new LongId(); + entity.setField1("Transaction Insert Test with Deferred ID Allocation " + i); + entities.add(entity); + } + transaction.insertWithDeferredIdAllocation(entities); + DatastoreTransaction.Response response = transaction.commit(); + // Leaving this call to the deprecated method + assertTrue(response.getGeneratedKeys().size() == 5); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_StringId() { - DatastoreTransaction transaction = em.newTransaction(); - try { - StringId entity = new StringId(); - transaction.insertWithDeferredIdAllocation(entity); - transaction.commit(); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_StringId() { + DatastoreTransaction transaction = em.newTransaction(); + try { + StringId entity = new StringId(); + transaction.insertWithDeferredIdAllocation(entity); + transaction.commit(); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } - } + } - @Test(expected = EntityManagerException.class) - public void testInsertWithDeferredIdAllocation_StringId_List() { - DatastoreTransaction transaction = em.newTransaction(); - try { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - StringId entity = new StringId(); - entities.add(entity); - } - transaction.insertWithDeferredIdAllocation(entities); - transaction.commit(); - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test(expected = EntityManagerException.class) + public void testInsertWithDeferredIdAllocation_StringId_List() { + DatastoreTransaction transaction = em.newTransaction(); + try { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + StringId entity = new StringId(); + entities.add(entity); + } + transaction.insertWithDeferredIdAllocation(entities); + transaction.commit(); + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } - @Test(expected = EntityAlreadyExistsException.class) - public void testInsertDuplicateKey() { - StringField entity = new StringField(); - entity.setName("Test for Duplicate Key from Transaction"); - StringField entity2 = em.insert(entity); - DatastoreTransaction transaction = em.newTransaction(); - try { - transaction.insertWithDeferredIdAllocation(entity2); - transaction.commit(); - } catch (EntityAlreadyExistsException exp) { - throw exp; - } catch (EntityManagerException exp) { - String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); - if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { - // Running on emulator that has a bug. - throw new EntityAlreadyExistsException(exp); - } - } finally { - if (transaction.isActive()) { - transaction.rollback(); - } - } - } + @Test(expected = EntityAlreadyExistsException.class) + public void testInsertDuplicateKey() { + StringField entity = new StringField(); + entity.setName("Test for Duplicate Key from Transaction"); + StringField entity2 = em.insert(entity); + DatastoreTransaction transaction = em.newTransaction(); + try { + transaction.insertWithDeferredIdAllocation(entity2); + transaction.commit(); + } catch (EntityAlreadyExistsException exp) { + throw exp; + } catch (EntityManagerException exp) { + String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); + if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { + // Running on emulator that has a bug. + throw new EntityAlreadyExistsException(exp); + } + } finally { + if (transaction.isActive()) { + transaction.rollback(); + } + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/DecimalFieldsTest.java b/src/test/java/com/jmethods/catatumbo/DecimalFieldsTest.java index 39a52d1..92fbea7 100644 --- a/src/test/java/com/jmethods/catatumbo/DecimalFieldsTest.java +++ b/src/test/java/com/jmethods/catatumbo/DecimalFieldsTest.java @@ -33,353 +33,355 @@ * */ public class DecimalFieldsTest { - private static EntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } - - @Test - public void testInsert_n10_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("5"); - entity.setN10(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(n, entity.getN10()); - } - - @Test - public void testInsert_n10_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("5.00"); - entity.setN10(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("5"), entity.getN10()); - } - - @Test - public void testInsert_n10_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-5"); - entity.setN10(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(n, entity.getN10()); - } - - @Test - public void testInsert_n10_4() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-5.0000"); - entity.setN10(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("-5"), entity.getN10()); - } - - @Test(expected = MappingException.class) - public void testInsert_n10_5() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0.1"); - entity.setN10(n); - try { - entity = em.insert(entity); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test - public void testInsert_n11_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal(".5"); - entity.setN11(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("0.5"), entity.getN11()); - } - - @Test - public void testInsert_n11_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal(".900"); - entity.setN11(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("0.9"), entity.getN11()); - } - - @Test(expected = MappingException.class) - public void testInsert_n11_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("1"); - entity.setN11(n); - try { - entity = em.insert(entity); - } catch (Exception exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testInsert_n50_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("99999"); - entity.setN50(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("99999"), entity.getN50()); - } - - @Test - public void testInsert_n50_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("99"); - entity.setN50(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("99"), entity.getN50()); - } - - @Test - public void testInsert_n50_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("99.000"); - entity.setN50(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("99"), entity.getN50()); - } - - @Test(expected = MappingException.class) - public void testInsert_n50_4() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("99.9"); - entity.setN50(n); - try { - entity = em.insert(entity); - } catch (Exception exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testInsert_n73_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("9999.999"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("9999.999"), entity.getN73()); - } - - @Test - public void testInsert_n73_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("1.999"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("1.999"), entity.getN73()); - } - - @Test - public void testInsert_n73_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("29.95"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("29.950"), entity.getN73()); - } - - @Test - public void testInsert_n73_4() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("29.95900"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("29.959"), entity.getN73()); - } - - @Test - public void testInsert_n73_5() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0.001"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("0.001"), entity.getN73()); - } - - @Test - public void testInsert_n73_6() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-0.1"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("-0.100"), entity.getN73()); - } - - @Test - public void testInsert_n73_7() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-9999.999"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("-9999.999"), entity.getN73()); - } - - @Test(expected = MappingException.class) - public void testInsert_n73_8() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-0.5432"); - entity.setN73(n); - try { - entity = em.insert(entity); - } catch (Exception exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testInsert_n180_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("999999999999999999"); - entity.setN180(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("999999999999999999"), entity.getN180()); - } - - @Test - public void testInsert_n180_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("999999999999999999.000000000000"); - entity.setN180(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("999999999999999999"), entity.getN180()); - } - - @Test(expected = MappingException.class) - public void testInsert_n180_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("9999999999999999999"); - entity.setN180(n); - try { - entity = em.insert(entity); - } catch (Exception exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testInsert_n1818_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0.000000000000000001"); - entity.setN1818(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("0.000000000000000001"), entity.getN1818()); - } - - @Test - public void testInsert_n1818_2() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0"); - entity.setN1818(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - assertEquals(new BigDecimal("0.000000000000000000"), entity.getN1818()); - } - - @Test(expected = MappingException.class) - public void testInsert_n1818_3() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0.0000000000000000002"); - entity.setN1818(n); - try { - entity = em.insert(entity); - } catch (Exception exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testQuery_1() { - // This test may fail at time, because of eventual consistency. Need to - // figure out a better way. - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("0.000000000000000001"); - entity.setN1818(n); - entity = em.insert(entity); - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM DecimalFields WHERE __key__=@1"); - request.addPositionalBinding(entity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(DecimalFields.class, request); - List entities = response.getResults(); - assertEquals(1, entities.size()); - assertEquals(new BigDecimal("0.000000000000000001"), entity.getN1818()); - - } - - @Test - public void testUpdate_n10_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("-5.0000"); - entity.setN10(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - entity.setN10(new BigDecimal("9.000")); - entity = em.update(entity); - assertEquals(new BigDecimal("9"), entity.getN10()); - } - - @Test - public void testUpdate_n73_1() { - DecimalFields entity = new DecimalFields(); - BigDecimal n = new BigDecimal("9.99"); - entity.setN73(n); - entity = em.insert(entity); - entity = em.load(DecimalFields.class, entity.getId()); - entity.setN73(new BigDecimal("99.99")); - entity = em.update(entity); - assertEquals(new BigDecimal("99.990"), entity.getN73()); - } - - @Test - public void testUpdate_n73_2() { - BigDecimal[] inputs = { new BigDecimal("0"), new BigDecimal("-1"), new BigDecimal("5"), new BigDecimal("6.1"), - new BigDecimal("7.55"), new BigDecimal("9.328") }; - List entities = new ArrayList<>(inputs.length); - for (BigDecimal input : inputs) { - entities.add(new DecimalFields()); - } - entities = em.insert(entities); - int i = 0; - for (DecimalFields entity : entities) { - entity.setN73(inputs[i++]); - } - List updatedEntities = em.update(entities); - assertFalse(entities.equals(updatedEntities)); - assertEquals(new BigDecimal("0.000"), updatedEntities.get(0).getN73()); - assertEquals(new BigDecimal("-1.000"), updatedEntities.get(1).getN73()); - assertEquals(new BigDecimal("5.000"), updatedEntities.get(2).getN73()); - assertEquals(new BigDecimal("6.100"), updatedEntities.get(3).getN73()); - assertEquals(new BigDecimal("7.550"), updatedEntities.get(4).getN73()); - assertEquals(new BigDecimal("9.328"), updatedEntities.get(5).getN73()); - } + private static EntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } + + @Test + public void testInsert_n10_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("5"); + entity.setN10(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(n, entity.getN10()); + } + + @Test + public void testInsert_n10_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("5.00"); + entity.setN10(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("5"), entity.getN10()); + } + + @Test + public void testInsert_n10_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-5"); + entity.setN10(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(n, entity.getN10()); + } + + @Test + public void testInsert_n10_4() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-5.0000"); + entity.setN10(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("-5"), entity.getN10()); + } + + @Test(expected = MappingException.class) + public void testInsert_n10_5() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0.1"); + entity.setN10(n); + try { + entity = em.insert(entity); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test + public void testInsert_n11_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal(".5"); + entity.setN11(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("0.5"), entity.getN11()); + } + + @Test + public void testInsert_n11_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal(".900"); + entity.setN11(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("0.9"), entity.getN11()); + } + + @Test(expected = MappingException.class) + public void testInsert_n11_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("1"); + entity.setN11(n); + try { + entity = em.insert(entity); + } catch (Exception exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testInsert_n50_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("99999"); + entity.setN50(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("99999"), entity.getN50()); + } + + @Test + public void testInsert_n50_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("99"); + entity.setN50(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("99"), entity.getN50()); + } + + @Test + public void testInsert_n50_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("99.000"); + entity.setN50(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("99"), entity.getN50()); + } + + @Test(expected = MappingException.class) + public void testInsert_n50_4() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("99.9"); + entity.setN50(n); + try { + entity = em.insert(entity); + } catch (Exception exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testInsert_n73_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("9999.999"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("9999.999"), entity.getN73()); + } + + @Test + public void testInsert_n73_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("1.999"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("1.999"), entity.getN73()); + } + + @Test + public void testInsert_n73_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("29.95"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("29.950"), entity.getN73()); + } + + @Test + public void testInsert_n73_4() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("29.95900"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("29.959"), entity.getN73()); + } + + @Test + public void testInsert_n73_5() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0.001"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("0.001"), entity.getN73()); + } + + @Test + public void testInsert_n73_6() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-0.1"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("-0.100"), entity.getN73()); + } + + @Test + public void testInsert_n73_7() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-9999.999"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("-9999.999"), entity.getN73()); + } + + @Test(expected = MappingException.class) + public void testInsert_n73_8() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-0.5432"); + entity.setN73(n); + try { + entity = em.insert(entity); + } catch (Exception exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testInsert_n180_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("999999999999999999"); + entity.setN180(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("999999999999999999"), entity.getN180()); + } + + @Test + public void testInsert_n180_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("999999999999999999.000000000000"); + entity.setN180(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("999999999999999999"), entity.getN180()); + } + + @Test(expected = MappingException.class) + public void testInsert_n180_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("9999999999999999999"); + entity.setN180(n); + try { + entity = em.insert(entity); + } catch (Exception exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testInsert_n1818_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0.000000000000000001"); + entity.setN1818(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("0.000000000000000001"), entity.getN1818()); + } + + @Test + public void testInsert_n1818_2() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0"); + entity.setN1818(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + assertEquals(new BigDecimal("0.000000000000000000"), entity.getN1818()); + } + + @Test(expected = MappingException.class) + public void testInsert_n1818_3() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0.0000000000000000002"); + entity.setN1818(n); + try { + entity = em.insert(entity); + } catch (Exception exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testQuery_1() { + // This test may fail at time, because of eventual consistency. Need to + // figure out a better way. + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("0.000000000000000001"); + entity.setN1818(n); + entity = em.insert(entity); + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM DecimalFields WHERE __key__=@1"); + request.addPositionalBinding(entity.getKey()); + QueryResponse response = em.executeEntityQueryRequest(DecimalFields.class, + request); + List entities = response.getResults(); + assertEquals(1, entities.size()); + assertEquals(new BigDecimal("0.000000000000000001"), entity.getN1818()); + + } + + @Test + public void testUpdate_n10_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("-5.0000"); + entity.setN10(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + entity.setN10(new BigDecimal("9.000")); + entity = em.update(entity); + assertEquals(new BigDecimal("9"), entity.getN10()); + } + + @Test + public void testUpdate_n73_1() { + DecimalFields entity = new DecimalFields(); + BigDecimal n = new BigDecimal("9.99"); + entity.setN73(n); + entity = em.insert(entity); + entity = em.load(DecimalFields.class, entity.getId()); + entity.setN73(new BigDecimal("99.99")); + entity = em.update(entity); + assertEquals(new BigDecimal("99.990"), entity.getN73()); + } + + @Test + public void testUpdate_n73_2() { + BigDecimal[] inputs = { new BigDecimal("0"), new BigDecimal("-1"), new BigDecimal("5"), + new BigDecimal("6.1"), new BigDecimal("7.55"), new BigDecimal("9.328") }; + List entities = new ArrayList<>(inputs.length); + for (BigDecimal input : inputs) { + entities.add(new DecimalFields()); + } + entities = em.insert(entities); + int i = 0; + for (DecimalFields entity : entities) { + entity.setN73(inputs[i++]); + } + List updatedEntities = em.update(entities); + assertFalse(entities.equals(updatedEntities)); + assertEquals(new BigDecimal("0.000"), updatedEntities.get(0).getN73()); + assertEquals(new BigDecimal("-1.000"), updatedEntities.get(1).getN73()); + assertEquals(new BigDecimal("5.000"), updatedEntities.get(2).getN73()); + assertEquals(new BigDecimal("6.100"), updatedEntities.get(3).getN73()); + assertEquals(new BigDecimal("7.550"), updatedEntities.get(4).getN73()); + assertEquals(new BigDecimal("9.328"), updatedEntities.get(5).getN73()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/DefaultAndExternalListenersTest.java b/src/test/java/com/jmethods/catatumbo/DefaultAndExternalListenersTest.java index e86af30..8c025bb 100644 --- a/src/test/java/com/jmethods/catatumbo/DefaultAndExternalListenersTest.java +++ b/src/test/java/com/jmethods/catatumbo/DefaultAndExternalListenersTest.java @@ -33,220 +33,220 @@ */ public class DefaultAndExternalListenersTest { - private static EntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - em.setDefaultListeners(Subtractor.class); - } - - @Test - public void testPreAndPostInsert() { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - assertTrue(entity.getProduct() == 35); - assertTrue(entity.getProduct2() == 70); - assertTrue(entity.getDifference() == 2); - assertTrue(entity.getDifference2() == 4); - } - - @Test - public void testPreAndPostInsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 2, i + 4); - entities.add(entity); - } - entities = em.insert(entities); - assertTrue(entities.get(0).getSum() == 6); - assertTrue(entities.get(0).getSum2() == 12); - assertTrue(entities.get(0).getProduct() == 8); - assertTrue(entities.get(0).getProduct2() == 16); - assertTrue(entities.get(1).getSum() == 8); - assertTrue(entities.get(1).getSum2() == 16); - assertTrue(entities.get(1).getProduct() == 15); - assertTrue(entities.get(1).getProduct2() == 30); - assertTrue(entities.get(0).getDifference() == -2); - assertTrue(entities.get(0).getDifference2() == -4); - assertTrue(entities.get(1).getDifference() == -2); - assertTrue(entities.get(1).getDifference2() == -4); - } - - @Test - public void testPreAndPostUpdate() { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - assertTrue(entity.getProduct() == 18); - assertTrue(entity.getProduct2() == 54); - assertTrue(entity.getDifference() == 7); - assertTrue(entity.getDifference2() == 21); - } - - @Test - public void testPreAndPost_Update_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - entities = em.update(entities); - assertTrue(entities.get(0).getSum() == 1); - assertTrue(entities.get(0).getSum2() == 3); - assertTrue(entities.get(0).getProduct() == 0); - assertTrue(entities.get(0).getProduct2() == 0); - assertTrue(entities.get(1).getSum() == 3); - assertTrue(entities.get(1).getSum2() == 9); - assertTrue(entities.get(1).getProduct() == 2); - assertTrue(entities.get(1).getProduct2() == 6); - assertTrue(entities.get(0).getDifference() == -1); - assertTrue(entities.get(0).getDifference2() == -3); - assertTrue(entities.get(1).getDifference() == -1); - assertTrue(entities.get(1).getDifference2() == -3); - } - - @Test - public void testPreAndPostUpsert() { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - assertTrue(entity.getProduct() == 64); - assertTrue(entity.getProduct2() == 256); - assertTrue(entity.getDifference() == 0); - assertTrue(entity.getDifference2() == 0); - } - - @Test - public void testPreAndPostUpsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 6, i + 2); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.get(0).getSum() == 8); - assertTrue(entities.get(0).getSum2() == 32); - assertTrue(entities.get(0).getProduct() == 12); - assertTrue(entities.get(0).getProduct2() == 48); - assertTrue(entities.get(1).getSum() == 10); - assertTrue(entities.get(1).getSum2() == 40); - assertTrue(entities.get(1).getProduct() == 21); - assertTrue(entities.get(1).getProduct2() == 84); - assertTrue(entities.get(0).getDifference() == 4); - assertTrue(entities.get(0).getDifference2() == 16); - assertTrue(entities.get(1).getDifference() == 4); - assertTrue(entities.get(1).getDifference2() == 16); - } - - @Test - public void testPreAndPostDelete() { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - assertTrue(entity.getProduct() == 2); - assertTrue(entity.getProduct2() == 10); - assertTrue(entity.getDifference() == -1); - assertTrue(entity.getDifference2() == -5); - } - - @Test - public void testPreAndPostDelete_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 1, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - em.delete(entities); - assertTrue(entities.get(0).getSum() == 2); - assertTrue(entities.get(0).getSum2() == 10); - assertTrue(entities.get(0).getProduct() == 1); - assertTrue(entities.get(0).getProduct2() == 5); - assertTrue(entities.get(1).getSum() == 4); - assertTrue(entities.get(1).getSum2() == 20); - assertTrue(entities.get(1).getProduct() == 4); - assertTrue(entities.get(1).getProduct2() == 20); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(0).getDifference2() == 0); - assertTrue(entities.get(1).getDifference() == 0); - assertTrue(entities.get(1).getDifference2() == 0); - } - - @Test - public void testPostLoad() { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(6, 9); - entity = em.insert(entity); - entity = em.load(ExternalCalculatorEntity4.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - assertTrue(entity.getProduct() == 54); - assertTrue(entity.getProduct2() == 54 * 6); - assertTrue(entity.getDifference() == -3); - assertTrue(entity.getDifference2() == -18); - } - - @Test - public void testPreAndPostLoad_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 5, i + 6); - entities.add(entity); - } - entities = em.insert(entities); - List ids = new ArrayList<>(); - for (ExternalCalculatorEntity4 entity : entities) { - ids.add(entity.getId()); - } - entities = em.loadById(ExternalCalculatorEntity4.class, ids); - assertTrue(entities.get(0).getSum() == 11); - assertTrue(entities.get(0).getSum2() == 66); - assertTrue(entities.get(0).getProduct() == 30); - assertTrue(entities.get(0).getProduct2() == 180); - assertTrue(entities.get(1).getSum() == 13); - assertTrue(entities.get(1).getSum2() == 78); - assertTrue(entities.get(1).getProduct() == 42); - assertTrue(entities.get(1).getProduct2() == 42 * 6); - assertTrue(entities.get(0).getDifference() == -1); - assertTrue(entities.get(0).getDifference2() == -6); - assertTrue(entities.get(1).getDifference() == -1); - assertTrue(entities.get(1).getDifference2() == -6); - } - - @Test - public void testPostLoad_Query() { - em.deleteAll(ExternalCalculatorEntity4.class); - ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(8, 9); - entity = em.insert(entity); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest( - String.format("SELECT * FROM %s WHERE __key__ = @1", ExternalCalculatorEntity4.class.getSimpleName())); - request.addPositionalBinding(entity.getKey()); - QueryResponse response = em - .executeEntityQueryRequest(ExternalCalculatorEntity4.class, request); - List entities = response.getResults(); - assertTrue(entities.get(0).getSum() == 17); - assertTrue(entities.get(0).getSum2() == 17 * 6); - assertTrue(entities.get(0).getProduct() == 72); - assertTrue(entities.get(0).getProduct2() == 72 * 6); - assertTrue(entities.get(0).getDifference() == -1); - assertTrue(entities.get(0).getDifference2() == -6); - } + private static EntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + em.setDefaultListeners(Subtractor.class); + } + + @Test + public void testPreAndPostInsert() { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + assertTrue(entity.getProduct() == 35); + assertTrue(entity.getProduct2() == 70); + assertTrue(entity.getDifference() == 2); + assertTrue(entity.getDifference2() == 4); + } + + @Test + public void testPreAndPostInsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 2, i + 4); + entities.add(entity); + } + entities = em.insert(entities); + assertTrue(entities.get(0).getSum() == 6); + assertTrue(entities.get(0).getSum2() == 12); + assertTrue(entities.get(0).getProduct() == 8); + assertTrue(entities.get(0).getProduct2() == 16); + assertTrue(entities.get(1).getSum() == 8); + assertTrue(entities.get(1).getSum2() == 16); + assertTrue(entities.get(1).getProduct() == 15); + assertTrue(entities.get(1).getProduct2() == 30); + assertTrue(entities.get(0).getDifference() == -2); + assertTrue(entities.get(0).getDifference2() == -4); + assertTrue(entities.get(1).getDifference() == -2); + assertTrue(entities.get(1).getDifference2() == -4); + } + + @Test + public void testPreAndPostUpdate() { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + assertTrue(entity.getProduct() == 18); + assertTrue(entity.getProduct2() == 54); + assertTrue(entity.getDifference() == 7); + assertTrue(entity.getDifference2() == 21); + } + + @Test + public void testPreAndPost_Update_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + entities = em.update(entities); + assertTrue(entities.get(0).getSum() == 1); + assertTrue(entities.get(0).getSum2() == 3); + assertTrue(entities.get(0).getProduct() == 0); + assertTrue(entities.get(0).getProduct2() == 0); + assertTrue(entities.get(1).getSum() == 3); + assertTrue(entities.get(1).getSum2() == 9); + assertTrue(entities.get(1).getProduct() == 2); + assertTrue(entities.get(1).getProduct2() == 6); + assertTrue(entities.get(0).getDifference() == -1); + assertTrue(entities.get(0).getDifference2() == -3); + assertTrue(entities.get(1).getDifference() == -1); + assertTrue(entities.get(1).getDifference2() == -3); + } + + @Test + public void testPreAndPostUpsert() { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + assertTrue(entity.getProduct() == 64); + assertTrue(entity.getProduct2() == 256); + assertTrue(entity.getDifference() == 0); + assertTrue(entity.getDifference2() == 0); + } + + @Test + public void testPreAndPostUpsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 6, i + 2); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.get(0).getSum() == 8); + assertTrue(entities.get(0).getSum2() == 32); + assertTrue(entities.get(0).getProduct() == 12); + assertTrue(entities.get(0).getProduct2() == 48); + assertTrue(entities.get(1).getSum() == 10); + assertTrue(entities.get(1).getSum2() == 40); + assertTrue(entities.get(1).getProduct() == 21); + assertTrue(entities.get(1).getProduct2() == 84); + assertTrue(entities.get(0).getDifference() == 4); + assertTrue(entities.get(0).getDifference2() == 16); + assertTrue(entities.get(1).getDifference() == 4); + assertTrue(entities.get(1).getDifference2() == 16); + } + + @Test + public void testPreAndPostDelete() { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + assertTrue(entity.getProduct() == 2); + assertTrue(entity.getProduct2() == 10); + assertTrue(entity.getDifference() == -1); + assertTrue(entity.getDifference2() == -5); + } + + @Test + public void testPreAndPostDelete_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 1, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + em.delete(entities); + assertTrue(entities.get(0).getSum() == 2); + assertTrue(entities.get(0).getSum2() == 10); + assertTrue(entities.get(0).getProduct() == 1); + assertTrue(entities.get(0).getProduct2() == 5); + assertTrue(entities.get(1).getSum() == 4); + assertTrue(entities.get(1).getSum2() == 20); + assertTrue(entities.get(1).getProduct() == 4); + assertTrue(entities.get(1).getProduct2() == 20); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(0).getDifference2() == 0); + assertTrue(entities.get(1).getDifference() == 0); + assertTrue(entities.get(1).getDifference2() == 0); + } + + @Test + public void testPostLoad() { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(6, 9); + entity = em.insert(entity); + entity = em.load(ExternalCalculatorEntity4.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + assertTrue(entity.getProduct() == 54); + assertTrue(entity.getProduct2() == 54 * 6); + assertTrue(entity.getDifference() == -3); + assertTrue(entity.getDifference2() == -18); + } + + @Test + public void testPreAndPostLoad_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(i + 5, i + 6); + entities.add(entity); + } + entities = em.insert(entities); + List ids = new ArrayList<>(); + for (ExternalCalculatorEntity4 entity : entities) { + ids.add(entity.getId()); + } + entities = em.loadById(ExternalCalculatorEntity4.class, ids); + assertTrue(entities.get(0).getSum() == 11); + assertTrue(entities.get(0).getSum2() == 66); + assertTrue(entities.get(0).getProduct() == 30); + assertTrue(entities.get(0).getProduct2() == 180); + assertTrue(entities.get(1).getSum() == 13); + assertTrue(entities.get(1).getSum2() == 78); + assertTrue(entities.get(1).getProduct() == 42); + assertTrue(entities.get(1).getProduct2() == 42 * 6); + assertTrue(entities.get(0).getDifference() == -1); + assertTrue(entities.get(0).getDifference2() == -6); + assertTrue(entities.get(1).getDifference() == -1); + assertTrue(entities.get(1).getDifference2() == -6); + } + + @Test + public void testPostLoad_Query() { + em.deleteAll(ExternalCalculatorEntity4.class); + ExternalCalculatorEntity4 entity = new ExternalCalculatorEntity4(8, 9); + entity = em.insert(entity); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest(String.format( + "SELECT * FROM %s WHERE __key__ = @1", ExternalCalculatorEntity4.class.getSimpleName())); + request.addPositionalBinding(entity.getKey()); + QueryResponse response = em + .executeEntityQueryRequest(ExternalCalculatorEntity4.class, request); + List entities = response.getResults(); + assertTrue(entities.get(0).getSum() == 17); + assertTrue(entities.get(0).getSum2() == 17 * 6); + assertTrue(entities.get(0).getProduct() == 72); + assertTrue(entities.get(0).getProduct2() == 72 * 6); + assertTrue(entities.get(0).getDifference() == -1); + assertTrue(entities.get(0).getDifference2() == -6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/DefaultListenerTest.java b/src/test/java/com/jmethods/catatumbo/DefaultListenerTest.java index 95cc0c4..0c2aae1 100644 --- a/src/test/java/com/jmethods/catatumbo/DefaultListenerTest.java +++ b/src/test/java/com/jmethods/catatumbo/DefaultListenerTest.java @@ -32,60 +32,60 @@ */ public class DefaultListenerTest { - private static EntityManager em; - private static Random random = new Random(); + private static EntityManager em; + private static Random random = new Random(); - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - em.setDefaultListeners(Adder.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + em.setDefaultListeners(Adder.class); + } - @Test - public void testPreAndPostInsert() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - } + @Test + public void testPreAndPostInsert() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + } - @Test - public void testPreAndPostUpdate() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - } + @Test + public void testPreAndPostUpdate() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + } - @Test - public void testPreAndPostUpsert() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - } + @Test + public void testPreAndPostUpsert() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + } - @Test - public void testPreAndPostDelete() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - } + @Test + public void testPreAndPostDelete() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + } - @Test - public void testPostLoad() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(6, 9); - entity = em.insert(entity); - entity = em.load(GlobalCalculatorEntity.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - } + @Test + public void testPostLoad() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(6, 9); + entity = em.insert(entity); + entity = em.load(GlobalCalculatorEntity.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + } } diff --git a/src/test/java/com/jmethods/catatumbo/EmbeddedCollectionTest.java b/src/test/java/com/jmethods/catatumbo/EmbeddedCollectionTest.java index 2471f3f..50950c9 100644 --- a/src/test/java/com/jmethods/catatumbo/EmbeddedCollectionTest.java +++ b/src/test/java/com/jmethods/catatumbo/EmbeddedCollectionTest.java @@ -34,77 +34,77 @@ * */ public class EmbeddedCollectionTest { - private static EntityManager em; + private static EntityManager em; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } - @Test - public void testInsert_PhoneList() { - PhoneList entity = PhoneList.getSample1(); - entity = em.insert(entity); - PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testInsert_PhoneList() { + PhoneList entity = PhoneList.getSample1(); + entity = em.insert(entity); + PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testInsert_PhoneList_Null() { - PhoneList entity = new PhoneList(); - entity = em.insert(entity); - PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testInsert_PhoneList_Null() { + PhoneList entity = new PhoneList(); + entity = em.insert(entity); + PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testUpdate_PhoneList() { - PhoneList entity = PhoneList.getSample1(); - entity = em.insert(entity); - entity = em.load(PhoneList.class, entity.getId()); - entity.getLandLineNumbers().add(PhoneNumber.getSample1()); - entity = em.update(entity); - PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testUpdate_PhoneList() { + PhoneList entity = PhoneList.getSample1(); + entity = em.insert(entity); + entity = em.load(PhoneList.class, entity.getId()); + entity.getLandLineNumbers().add(PhoneNumber.getSample1()); + entity = em.update(entity); + PhoneList loadedEntity = em.load(PhoneList.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testInsert_AddressMap() { - AddressMap entity = new AddressMap(); - Map addresses = new HashMap<>(); - addresses.put("home", Address.getSample1()); - addresses.put("work", Address.getSample2()); - entity.setAddresses(addresses); - entity = em.insert(entity); - AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testInsert_AddressMap() { + AddressMap entity = new AddressMap(); + Map addresses = new HashMap<>(); + addresses.put("home", Address.getSample1()); + addresses.put("work", Address.getSample2()); + entity.setAddresses(addresses); + entity = em.insert(entity); + AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testInsert_AddressMap_Null() { - AddressMap entity = AddressMap.getSample1(); - entity = em.insert(entity); - AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testInsert_AddressMap_Null() { + AddressMap entity = AddressMap.getSample1(); + entity = em.insert(entity); + AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testInsert_AddressMap_NullZip() { - AddressMap entity = AddressMap.getSample2(); - entity = em.insert(entity); - AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testInsert_AddressMap_NullZip() { + AddressMap entity = AddressMap.getSample2(); + entity = em.insert(entity); + AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } - @Test - public void testUpdate_AddressMap() { - AddressMap entity = AddressMap.getSample1(); - entity = em.insert(entity); - entity = em.load(AddressMap.class, entity.getId()); - entity.getAddresses().get("work").setStreet2("Suite 2"); - entity = em.update(entity); - AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); - assertTrue(entity.equals(loadedEntity)); - } + @Test + public void testUpdate_AddressMap() { + AddressMap entity = AddressMap.getSample1(); + entity = em.insert(entity); + entity = em.load(AddressMap.class, entity.getId()); + entity.getAddresses().get("work").setStreet2("Suite 2"); + entity = em.update(entity); + AddressMap loadedEntity = em.load(AddressMap.class, entity.getId()); + assertTrue(entity.equals(loadedEntity)); + } } diff --git a/src/test/java/com/jmethods/catatumbo/EntityManagerFactoryTest.java b/src/test/java/com/jmethods/catatumbo/EntityManagerFactoryTest.java index 6e8400d..9e8ba79 100644 --- a/src/test/java/com/jmethods/catatumbo/EntityManagerFactoryTest.java +++ b/src/test/java/com/jmethods/catatumbo/EntityManagerFactoryTest.java @@ -38,302 +38,307 @@ */ public class EntityManagerFactoryTest { - /** - * This Test requires default project/auth set up using gcloud. - */ - @Test - public void testCreateDefaultEntityManager() { - if (TestUtils.isCI()) { - // TODO - return; - } - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - EntityManager em = emf.createDefaultEntityManager(); - DefaultEntityManager dem = (DefaultEntityManager) em; - Datastore ds = dem.getDatastore(); - assertTrue(ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 - && ds.getOptions().getNamespace().equals("")); - } + /** + * This Test requires default project/auth set up using gcloud. + */ + @Test + public void testCreateDefaultEntityManager() { + if (TestUtils.isCI()) { + // TODO + return; + } + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + EntityManager em = emf.createDefaultEntityManager(); + DefaultEntityManager dem = (DefaultEntityManager) em; + Datastore ds = dem.getDatastore(); + assertTrue( + ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 + && ds.getOptions().getNamespace().equals("")); + } - /** - * This Test requires default project/auth set up using gcloud. - */ - @Test - public void testCreateDefaultEntityManager_Namespace() { - if (TestUtils.isCI()) { - // TODO - return; - } - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - EntityManager em = emf.createDefaultEntityManager("junit"); - DefaultEntityManager dem = (DefaultEntityManager) em; - Datastore ds = dem.getDatastore(); - assertTrue(ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 - && ds.getOptions().getNamespace().equals("junit")); - } + /** + * This Test requires default project/auth set up using gcloud. + */ + @Test + public void testCreateDefaultEntityManager_Namespace() { + if (TestUtils.isCI()) { + // TODO + return; + } + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + EntityManager em = emf.createDefaultEntityManager("junit"); + DefaultEntityManager dem = (DefaultEntityManager) em; + Datastore ds = dem.getDatastore(); + assertTrue( + ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 + && ds.getOptions().getNamespace().equals("junit")); + } - @Test(expected = EntityManagerFactoryException.class) - public void testCreateEntityManager_BadFilePath() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - try { - emf.createEntityManager("my-project", "temp.json"); - } catch (Exception exp) { - System.out.println(exp); - throw exp; - } - } + @Test(expected = EntityManagerFactoryException.class) + public void testCreateEntityManager_BadFilePath() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + try { + emf.createEntityManager("my-project", "temp.json"); + } catch (Exception exp) { + System.out.println(exp); + throw exp; + } + } - @Test - public void testCreateEntityManager_GoodFilePath() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); - String jsonFile = System.getenv(TestUtils.ENV_CREDENTIALS); - if (jsonFile == null) { - System.out.printf("Enviornment variable %s is not set, skipping the test case%n", - TestUtils.ENV_CREDENTIALS); - return; - } - EntityManager em = emf.createEntityManager(projectId, jsonFile); - DefaultEntityManager dem = (DefaultEntityManager) em; - Datastore ds = dem.getDatastore(); - assertTrue(ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 - && ds.getOptions().getNamespace().equals("")); - } + @Test + public void testCreateEntityManager_GoodFilePath() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); + String jsonFile = System.getenv(TestUtils.ENV_CREDENTIALS); + if (jsonFile == null) { + System.out.printf("Enviornment variable %s is not set, skipping the test case%n", + TestUtils.ENV_CREDENTIALS); + return; + } + EntityManager em = emf.createEntityManager(projectId, jsonFile); + DefaultEntityManager dem = (DefaultEntityManager) em; + Datastore ds = dem.getDatastore(); + assertTrue( + ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 + && ds.getOptions().getNamespace().equals("")); + } - @Test(expected = EntityManagerFactoryException.class) - public void testCreateEntityManager_CorruptFilePath() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - File tempFile = null; - try { - tempFile = File.createTempFile("credentials", ".json"); - } catch (IOException exp) { - exp.printStackTrace(); - System.out.println("Skipping test because temp file creation filed"); - return; - } - try { - String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); - EntityManager em = emf.createEntityManager(projectId, tempFile); - DefaultEntityManager dem = (DefaultEntityManager) em; - } catch (Exception exp) { - System.out.println(exp); - exp.printStackTrace(); - throw exp; - } finally { - if (tempFile != null) { - tempFile.delete(); - } - } - } + @Test(expected = EntityManagerFactoryException.class) + public void testCreateEntityManager_CorruptFilePath() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + File tempFile = null; + try { + tempFile = File.createTempFile("credentials", ".json"); + } catch (IOException exp) { + exp.printStackTrace(); + System.out.println("Skipping test because temp file creation filed"); + return; + } + try { + String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); + EntityManager em = emf.createEntityManager(projectId, tempFile); + DefaultEntityManager dem = (DefaultEntityManager) em; + } catch (Exception exp) { + System.out.println(exp); + exp.printStackTrace(); + throw exp; + } finally { + if (tempFile != null) { + tempFile.delete(); + } + } + } - @Test - public void testCreateEntityManager_Namespace() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - try { - String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); - String jsonFile = System.getenv(TestUtils.ENV_CREDENTIALS); - if (jsonFile == null) { - System.out.printf("Enviornment variable %s is not set, skipping the test case%n", - TestUtils.ENV_CREDENTIALS); - return; - } - EntityManager em = emf.createEntityManager(projectId, new File(jsonFile), "junit"); - DefaultEntityManager dem = (DefaultEntityManager) em; - Datastore ds = dem.getDatastore(); - assertTrue(ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 - && ds.getOptions().getNamespace().equals("junit")); - } catch (Exception exp) { - System.out.println(exp); - throw exp; - } - } + @Test + public void testCreateEntityManager_Namespace() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + try { + String projectId = System.getenv(TestUtils.ENV_PROJECT_ID); + String jsonFile = System.getenv(TestUtils.ENV_CREDENTIALS); + if (jsonFile == null) { + System.out.printf("Enviornment variable %s is not set, skipping the test case%n", + TestUtils.ENV_CREDENTIALS); + return; + } + EntityManager em = emf.createEntityManager(projectId, new File(jsonFile), "junit"); + DefaultEntityManager dem = (DefaultEntityManager) em; + Datastore ds = dem.getDatastore(); + assertTrue( + ds.getOptions().getProjectId() != null && ds.getOptions().getProjectId().length() != 0 + && ds.getOptions().getNamespace().equals("junit")); + } catch (Exception exp) { + System.out.println(exp); + throw exp; + } + } - @Test - public void testCreateLocalEntityManager1() { - try { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - EntityManager em = emf.createLocalEntityManager("localhost:9999"); - DefaultEntityManager dem = (DefaultEntityManager) em; - DatastoreOptions options = dem.getDatastore().getOptions(); - assertEquals("localhost:9999", options.getHost()); - assertNotNull(options.getProjectId()); - assertEquals("", options.getNamespace()); - } catch (EntityManagerFactoryException exp) { - if (!TestUtils.isCI()) { - throw exp; - } - } - } + @Test + public void testCreateLocalEntityManager1() { + try { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + EntityManager em = emf.createLocalEntityManager("localhost:9999"); + DefaultEntityManager dem = (DefaultEntityManager) em; + DatastoreOptions options = dem.getDatastore().getOptions(); + assertEquals("localhost:9999", options.getHost()); + assertNotNull(options.getProjectId()); + assertEquals("", options.getNamespace()); + } catch (EntityManagerFactoryException exp) { + if (!TestUtils.isCI()) { + throw exp; + } + } + } - @Test - public void testCreateLocalEntityManager2() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - EntityManager em = emf.createLocalEntityManager("localhost:9999", "cool-project"); - DefaultEntityManager dem = (DefaultEntityManager) em; - DatastoreOptions options = dem.getDatastore().getOptions(); - assertEquals("localhost:9999", options.getHost()); - assertEquals("cool-project", options.getProjectId()); - assertEquals("", options.getNamespace()); - } + @Test + public void testCreateLocalEntityManager2() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + EntityManager em = emf.createLocalEntityManager("localhost:9999", "cool-project"); + DefaultEntityManager dem = (DefaultEntityManager) em; + DatastoreOptions options = dem.getDatastore().getOptions(); + assertEquals("localhost:9999", options.getHost()); + assertEquals("cool-project", options.getProjectId()); + assertEquals("", options.getNamespace()); + } - @Test - public void testCreateLocalEntityManager3() { - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - EntityManager em = emf.createLocalEntityManager("localhost:9999", "cool-project", "scret-namespace"); - DefaultEntityManager dem = (DefaultEntityManager) em; - DatastoreOptions options = dem.getDatastore().getOptions(); - assertEquals("localhost:9999", options.getHost()); - assertEquals("cool-project", options.getProjectId()); - assertEquals("scret-namespace", options.getNamespace()); - } + @Test + public void testCreateLocalEntityManager3() { + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + EntityManager em = emf.createLocalEntityManager("localhost:9999", "cool-project", + "scret-namespace"); + DefaultEntityManager dem = (DefaultEntityManager) em; + DatastoreOptions options = dem.getDatastore().getOptions(); + assertEquals("localhost:9999", options.getHost()); + assertEquals("cool-project", options.getProjectId()); + assertEquals("scret-namespace", options.getNamespace()); + } - @Test - public void testCreateEntityManager_ConnectionParameters1() { - if (TestUtils.isCI()) { - // TODO - return; - } - ConnectionParameters parameters = new ConnectionParameters(); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); + @Test + public void testCreateEntityManager_ConnectionParameters1() { + if (TestUtils.isCI()) { + // TODO + return; + } + ConnectionParameters parameters = new ConnectionParameters(); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); - } + } - @Test - public void testCreateEntityManager_ConnectionParameters2() { - ConnectionParameters parameters = new ConnectionParameters(); - final String serviceURL = "http://localhost:9999"; - parameters.setServiceURL(serviceURL); - parameters.setProjectId("my-project"); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(serviceURL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertNotNull(options.getCredentials()); - } + @Test + public void testCreateEntityManager_ConnectionParameters2() { + ConnectionParameters parameters = new ConnectionParameters(); + final String serviceURL = "http://localhost:9999"; + parameters.setServiceURL(serviceURL); + parameters.setProjectId("my-project"); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(serviceURL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertNotNull(options.getCredentials()); + } - @Test - public void testCreateEntityManager_ConnectionParameters3() { - ConnectionParameters parameters = new ConnectionParameters(); - final String serviceURL = "http://localhost:9999"; - final String projectId = "my-project"; - final String namespace = "my-namespace"; - parameters.setServiceURL(serviceURL); - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(serviceURL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertNotNull(options.getCredentials()); - assertEquals(projectId, options.getProjectId()); - assertEquals(namespace, options.getNamespace()); - } + @Test + public void testCreateEntityManager_ConnectionParameters3() { + ConnectionParameters parameters = new ConnectionParameters(); + final String serviceURL = "http://localhost:9999"; + final String projectId = "my-project"; + final String namespace = "my-namespace"; + parameters.setServiceURL(serviceURL); + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(serviceURL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertNotNull(options.getCredentials()); + assertEquals(projectId, options.getProjectId()); + assertEquals(namespace, options.getNamespace()); + } - @Test - public void testCreateEntityManager_ConnectionParameters4() { - if (TestUtils.isCI()) { - // TODO - return; - } - ConnectionParameters parameters = new ConnectionParameters(); - final String projectId = "my-project"; - final String namespace = "my-namespace"; - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertNotNull(options.getCredentials()); - assertEquals(projectId, options.getProjectId()); - assertEquals(namespace, options.getNamespace()); - } + @Test + public void testCreateEntityManager_ConnectionParameters4() { + if (TestUtils.isCI()) { + // TODO + return; + } + ConnectionParameters parameters = new ConnectionParameters(); + final String projectId = "my-project"; + final String namespace = "my-namespace"; + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertNotNull(options.getCredentials()); + assertEquals(projectId, options.getProjectId()); + assertEquals(namespace, options.getNamespace()); + } - @Test - public void testCreateEntityManager_ConnectionParameters5() { - ConnectionParameters parameters = new ConnectionParameters(); - final String projectId = "my-project"; - final String namespace = "my-namespace"; - final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); - if (Utility.isNullOrEmpty(credentialsFile)) { - System.out.printf("Enviornment variable %s is not set, skipping the test case%n", - TestUtils.ENV_CREDENTIALS); - return; - } - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - parameters.setJsonCredentialsFile(credentialsFile); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); - assertEquals(projectId, options.getProjectId()); - assertEquals(namespace, options.getNamespace()); - } + @Test + public void testCreateEntityManager_ConnectionParameters5() { + ConnectionParameters parameters = new ConnectionParameters(); + final String projectId = "my-project"; + final String namespace = "my-namespace"; + final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); + if (Utility.isNullOrEmpty(credentialsFile)) { + System.out.printf("Enviornment variable %s is not set, skipping the test case%n", + TestUtils.ENV_CREDENTIALS); + return; + } + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + parameters.setJsonCredentialsFile(credentialsFile); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); + assertEquals(projectId, options.getProjectId()); + assertEquals(namespace, options.getNamespace()); + } - @Test - public void testCreateEntityManager_ConnectionParameters6() throws FileNotFoundException { - ConnectionParameters parameters = new ConnectionParameters(); - final String projectId = "my-project"; - final String namespace = "my-namespace"; - final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); - if (Utility.isNullOrEmpty(credentialsFile)) { - System.out.printf("Enviornment variable %s is not set, skipping the test case%n", - TestUtils.ENV_CREDENTIALS); - return; - } - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile)); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); - assertEquals(projectId, options.getProjectId()); - assertEquals(namespace, options.getNamespace()); - } + @Test + public void testCreateEntityManager_ConnectionParameters6() throws FileNotFoundException { + ConnectionParameters parameters = new ConnectionParameters(); + final String projectId = "my-project"; + final String namespace = "my-namespace"; + final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); + if (Utility.isNullOrEmpty(credentialsFile)) { + System.out.printf("Enviornment variable %s is not set, skipping the test case%n", + TestUtils.ENV_CREDENTIALS); + return; + } + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile)); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); + assertEquals(projectId, options.getProjectId()); + assertEquals(namespace, options.getNamespace()); + } - @Test - public void testCreateEntityManager_ConnectionParameters7() throws FileNotFoundException { - ConnectionParameters parameters = new ConnectionParameters(); - final String projectId = "my-project"; - final String namespace = "my-namespace"; - final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); - if (Utility.isNullOrEmpty(credentialsFile)) { - System.out.printf("Enviornment variable %s is not set, skipping the test case%n", - TestUtils.ENV_CREDENTIALS); - return; - } - parameters.setProjectId(projectId); - parameters.setNamespace(namespace); - parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile)); - parameters.setJsonCredentialsFile("nonexistentfile.json"); - EntityManagerFactory emf = EntityManagerFactory.getInstance(); - DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); - DatastoreOptions options = em.getDatastore().getOptions(); - assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); - assertNotNull(options.getProjectId()); - assertTrue(options.getProjectId().length() > 0); - assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); - assertEquals(projectId, options.getProjectId()); - assertEquals(namespace, options.getNamespace()); - } + @Test + public void testCreateEntityManager_ConnectionParameters7() throws FileNotFoundException { + ConnectionParameters parameters = new ConnectionParameters(); + final String projectId = "my-project"; + final String namespace = "my-namespace"; + final String credentialsFile = System.getenv(TestUtils.ENV_CREDENTIALS); + if (Utility.isNullOrEmpty(credentialsFile)) { + System.out.printf("Enviornment variable %s is not set, skipping the test case%n", + TestUtils.ENV_CREDENTIALS); + return; + } + parameters.setProjectId(projectId); + parameters.setNamespace(namespace); + parameters.setJsonCredentialsStream(new FileInputStream(credentialsFile)); + parameters.setJsonCredentialsFile("nonexistentfile.json"); + EntityManagerFactory emf = EntityManagerFactory.getInstance(); + DefaultEntityManager em = (DefaultEntityManager) emf.createEntityManager(parameters); + DatastoreOptions options = em.getDatastore().getOptions(); + assertEquals(ConnectionParameters.DEFAULT_SERVICE_URL, options.getHost()); + assertNotNull(options.getProjectId()); + assertTrue(options.getProjectId().length() > 0); + assertEquals(ServiceAccountCredentials.class, options.getCredentials().getClass()); + assertEquals(projectId, options.getProjectId()); + assertEquals(namespace, options.getNamespace()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/EntityManagerTest.java b/src/test/java/com/jmethods/catatumbo/EntityManagerTest.java index 72f4a47..ce3e175 100644 --- a/src/test/java/com/jmethods/catatumbo/EntityManagerTest.java +++ b/src/test/java/com/jmethods/catatumbo/EntityManagerTest.java @@ -136,3333 +136,3370 @@ */ public class EntityManagerTest { - private static EntityManager em; - private static Random random = new Random(); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - // Register a custom mapper - MapperFactory.getInstance().setDefaultMapper(DeviceType.class, new DeviceTypeMapper()); - em = TestUtils.getEntityManager(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteAll_Null() { - em.deleteAll((String) null); - } - - @Test(expected = IllegalArgumentException.class) - public void testDeleteAll_Blank() { - em.deleteAll(" "); - } - - @Test - public void testInsertLongId_AutoGenerated() { - LongId entity = new LongId(); - entity.setField1("Hello World!"); - entity = em.insert(entity); - assertNotEquals(0, entity.getId()); - } - - @Test - public void testInsertLongId_Preset() { - LongId entity = new LongId(); - long id = random.nextLong(); - entity.setId(id); - entity.setField1("Hello World!"); - entity = em.insert(entity); - assertEquals(id, entity.getId()); - } - - @Test(expected = EntityManagerException.class) - public void testInsertLongId2() { - try { - LongId2 entity = new LongId2(); - entity.setField1("Hello World!"); - entity = em.insert(entity); - } catch (EntityManagerException exp) { - exp.printStackTrace(); - throw exp; - } - } - - @Test - public void testInsertStringId_AutoGenerated() { - StringId entity = new StringId(); - entity.setGreetings("Good Morning!"); - entity = em.insert(entity); - assertNotNull(entity.getId()); - } - - @Test - public void testInsertStringId_Preset() { - StringId entity = new StringId(); - String id = "greeting1"; - entity.setId(id); - entity.setGreetings("Good Morning!"); - entity = em.insert(entity); - assertEquals(id, entity.getId()); - } - - @Test(expected = EntityManagerException.class) - public void testInsertStringId2() { - StringId2 entity = new StringId2(); - entity = em.insert(entity); - } - - @Test - public void testInsertBooleanField_True() { - BooleanField entity = new BooleanField(); - entity.setAwesome(true); - entity = em.insert(entity); - assertTrue(entity.getId() > 0L && entity.isAwesome()); - } - - @Test - public void testInsertBooleanField_False() { - BooleanField entity = new BooleanField(); - entity.setAwesome(false); - entity = em.insert(entity); - assertTrue(entity.getId() > 0L && !entity.isAwesome()); - } - - @Test - public void testInsertBooleanObject_True() { - BooleanObject entity = new BooleanObject(); - entity.setAwesome(true); - entity = em.insert(entity); - assertTrue(entity.getId() > 0L && Boolean.TRUE.equals(entity.getAwesome())); - } - - @Test - public void testInsertBooleanObject_False() { - BooleanObject entity = new BooleanObject(); - entity.setAwesome(false); - entity = em.insert(entity); - assertTrue(entity.getId() > 0L && Boolean.FALSE.equals(entity.getAwesome())); - } - - @Test - public void testInsertBooleanObject_Null() { - BooleanObject entity = new BooleanObject(); - entity = em.insert(entity); - assertTrue(entity.getId() > 0L && entity.getAwesome() == null); - } - - @Test - public void testInsertCharField() { - CharField entity = new CharField(); - entity.setSex('M'); - entity = em.insert(entity); - entity = em.load(CharField.class, entity.getId()); - assertTrue(entity.getId() > 0L && entity.getSex() == 'M'); - } - - @Test - public void testInsertCharObject() { - CharObject entity = new CharObject(); - entity.setSex('F'); - entity = em.insert(entity); - entity = em.load(CharObject.class, entity.getId()); - assertTrue(entity.getId() > 0L && entity.getSex() == 'F'); - } - - @Test - public void testInsertCharObject_Null() { - CharObject entity = new CharObject(); - entity = em.insert(entity); - entity = em.load(CharObject.class, entity.getId()); - assertTrue(entity.getId() > 0L && entity.getSex() == null); - } - - @Test - public void testInsertShortField() { - ShortField entity = new ShortField(); - entity.setAge((short) 25); - entity = em.insert(entity); - entity = em.load(ShortField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getAge() == 25); - } - - @Test - public void testInsertShortObject() { - ShortObject entity = new ShortObject(); - entity.setAge(new Short((short) 25)); - entity = em.insert(entity); - entity = em.load(ShortObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getAge() == 25); - } - - @Test - public void testInsertShortObject_Null() { - ShortObject entity = new ShortObject(); - entity = em.insert(entity); - entity = em.load(ShortObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getAge() == null); - } - - @Test - public void testInsertIntegerField() { - IntegerField entity = new IntegerField(); - entity.setCount(3456789); - entity = em.insert(entity); - entity = em.load(IntegerField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCount() == 3456789); - } - - @Test - public void testInsertIntegerField_Negative_Value() { - IntegerField entity = new IntegerField(); - entity.setCount(-3456789); - entity = em.insert(entity); - entity = em.load(IntegerField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCount() == -3456789); - } - - @Test - public void testInsertIntegerObject() { - IntegerObject entity = new IntegerObject(); - entity.setCount(new Integer(3456789)); - entity = em.insert(entity); - entity = em.load(IntegerObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCount() == 3456789); - } - - @Test - public void testInsertIntegerObject_Null() { - IntegerObject entity = new IntegerObject(); - entity = em.insert(entity); - entity = em.load(IntegerObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCount() == null); - } - - @Test - public void testInsertLongField() { - LongField entity = new LongField(); - entity.setDistanceFromEarth(2400000000000000L); - entity = em.insert(entity); - entity = em.load(LongField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == 2400000000000000L); - } - - @Test - public void testInsertLongObject() { - LongObject entity = new LongObject(); - entity.setDistanceFromEarth(2400000000000000L); - entity = em.insert(entity); - entity = em.load(LongObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == 2400000000000000L); - } - - @Test - public void testInsertLongObject_Null() { - LongObject entity = new LongObject(); - entity = em.insert(entity); - entity = em.load(LongObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == null); - } - - @Test - public void testInsertFloatField() { - FloatField entity = new FloatField(); - entity.setArea(Float.MAX_VALUE); - entity = em.insert(entity); - entity = em.load(FloatField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == Float.MAX_VALUE); - } - - @Test - public void testInsertFloatField_Negative() { - FloatField entity = new FloatField(); - entity.setArea(-Float.MIN_VALUE); - entity = em.insert(entity); - entity = em.load(FloatField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == -Float.MIN_VALUE); - } - - @Test - public void testInsertFloatField_PI() { - FloatField entity = new FloatField(); - entity.setArea(3.1415927f); - entity = em.insert(entity); - entity = em.load(FloatField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == 3.1415927f); - } - - @Test - public void testInsertFloatObject() { - FloatObject entity = new FloatObject(); - entity.setArea(Float.valueOf(Float.MAX_VALUE)); - entity = em.insert(entity); - entity = em.load(FloatObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == Float.MAX_VALUE); - } - - @Test - public void testInsertFloatObject_Negative() { - FloatObject entity = new FloatObject(); - entity.setArea(Float.valueOf(-Float.MIN_VALUE)); - entity = em.insert(entity); - entity = em.load(FloatObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == -Float.MIN_VALUE); - } - - @Test - public void testInsertFloatObject_Null() { - FloatObject entity = new FloatObject(); - entity = em.insert(entity); - entity = em.load(FloatObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == null); - } - - @Test - public void testInsertDoubleField() { - DoubleField entity = new DoubleField(); - entity.setArea(Double.MAX_VALUE); - entity = em.insert(entity); - entity = em.load(DoubleField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == Double.MAX_VALUE); - } - - @Test - public void testInsertDoubleField_Negative() { - DoubleField entity = new DoubleField(); - entity.setArea(-Double.MIN_VALUE); - entity = em.insert(entity); - entity = em.load(DoubleField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == -Double.MIN_VALUE); - } - - @Test - public void testInsertDoubleObject() { - DoubleObject entity = new DoubleObject(); - entity.setArea(Double.MAX_VALUE); - entity = em.insert(entity); - entity = em.load(DoubleObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == Double.MAX_VALUE); - } - - @Test - public void testInsertDoubleObject_Negative() { - DoubleObject entity = new DoubleObject(); - entity.setArea(-Double.MIN_VALUE); - entity = em.insert(entity); - entity = em.load(DoubleObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == -Double.MIN_VALUE); - } - - @Test - public void testInsertDoubleObject_Null() { - DoubleObject entity = new DoubleObject(); - entity = em.insert(entity); - entity = em.load(DoubleObject.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getArea() == null); - } - - @Test - public void testInsertStringField() { - StringField entity = new StringField(); - String name = "Google Cloud Datastore"; - entity.setName(name); - entity = em.insert(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName().equals(name)); - } - - @Test - public void testInsertStringField_Blank() { - StringField entity = new StringField(); - String name = ""; - entity.setName(name); - entity = em.insert(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName().equals(name)); - } - - @Test - public void testInsertStringField_Spaces() { - StringField entity = new StringField(); - String name = " "; - entity.setName(name); - entity = em.insert(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName().equals(name)); - } - - @Test - public void testInsertStringField_Null() { - StringField entity = new StringField(); - entity = em.insert(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName() == null); - } - - @Test - public void testInsertCalendarField() { - CalendarField entity = new CalendarField(); - Calendar now = Calendar.getInstance(); - entity.setCreationDate(now); - entity = em.insert(entity); - entity = em.load(CalendarField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); - } - - @Test - public void testInsertCalendarField_GMT() { - CalendarField entity = new CalendarField(); - Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - entity.setCreationDate(now); - entity = em.insert(entity); - entity = em.load(CalendarField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); - } - - @Test - public void testInsertCalendarField_Null() { - CalendarField entity = new CalendarField(); - // Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - // entity.setCreationDate(now); - entity = em.insert(entity); - entity = em.load(CalendarField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate() == null); - } - - @Test - public void testInsertDateField() { - DateField entity = new DateField(); - Date now = new Date(); - entity.setCreationDate(now); - entity = em.insert(entity); - entity = em.load(DateField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate().getTime() == now.getTime()); - } - - @Test - public void testInsertDateField_Future() { - DateField entity = new DateField(); - long currentTime = System.currentTimeMillis(); - long hundredYearsFromNow = currentTime + 100L * 366L * 24L * 60L * 60L * 1000L; - Date date = new Date(hundredYearsFromNow); - entity.setCreationDate(date); - entity = em.insert(entity); - entity = em.load(DateField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate().getTime() == date.getTime()); - } - - @Test - public void testInsertDateField_Null() { - DateField entity = new DateField(); - entity = em.insert(entity); - entity = em.load(DateField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getCreationDate() == null); - } - - @Test - public void testInsertLocalDateField() { - LocalDateField entity = new LocalDateField(); - LocalDate now = LocalDate.now(); - entity.setBirthDate(now); - entity = em.insert(entity); - entity = em.load(LocalDateField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getBirthDate().equals(now)); - } - - @Test - public void testInsertLocalDateField_Null() { - LocalDateField entity = new LocalDateField(); - entity = em.insert(entity); - entity = em.load(LocalDateField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getBirthDate() == null); - } - - @Test - public void testInsertLocalTimeField_Now() { - LocalTimeField entity = new LocalTimeField(); - LocalTime now = LocalTime.now(); - entity.setStartTime(now); - entity = em.insert(entity); - entity = em.load(LocalTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getStartTime().equals(now)); - } - - @Test - public void testInsertLocalTimeField_Null() { - LocalTimeField entity = new LocalTimeField(); - entity = em.insert(entity); - entity = em.load(LocalTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getStartTime() == null); - } - - @Test - public void testInsertLocalDateTimeField_Now() { - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime now = LocalDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity = em.load(LocalDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); - } - - @Test - public void testInsertLocalDateTimeField_Null() { - LocalDateTimeField entity = new LocalDateTimeField(); - entity = em.insert(entity); - entity = em.load(LocalDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); - } - - @Test - public void testInsertOffsetDateTimeField_Now() { - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime now = OffsetDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity = em.load(OffsetDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); - } - - @Test - public void testInsertOffsetDateTimeField_Null() { - OffsetDateTimeField entity = new OffsetDateTimeField(); - entity.setTimestamp(null); - entity = em.insert(entity); - entity = em.load(OffsetDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); - } - - @Test - public void testInsertOffsetDateTimeField_Nano() { - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime now = OffsetDateTime.now().withNano(999999999); - entity.setTimestamp(now); - OffsetDateTimeField entity2 = em.insert(entity); - // Here we lose the nano precision and only have micros - OffsetDateTimeField entity3 = em.load(OffsetDateTimeField.class, entity2.getId()); - assertEquals(entity2.getTimestamp(), entity3.getTimestamp()); - assertEquals(entity.getTimestamp().toEpochSecond(), entity3.getTimestamp().toEpochSecond()); - assertEquals(TimeUnit.NANOSECONDS.toMicros(entity.getTimestamp().getNano()), - TimeUnit.NANOSECONDS.toMicros(entity3.getTimestamp().getNano())); - } - - @Test - public void testInsertZonedDateTimeField_Now() { - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime now = ZonedDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity = em.load(ZonedDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); - } - - @Test - public void testInsertZonedDateTimeField_Null() { - ZonedDateTimeField entity = new ZonedDateTimeField(); - entity = em.insert(entity); - entity = em.load(ZonedDateTimeField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); - } - - @Test - public void testInsertZonedDateTimeField_Nano() { - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime now = ZonedDateTime.now().withNano(999999999); - entity.setTimestamp(now); - ZonedDateTimeField entity2 = em.insert(entity); - // Here we lose the nano precision and only have micros - ZonedDateTimeField entity3 = em.load(ZonedDateTimeField.class, entity2.getId()); - assertEquals(entity2.getTimestamp(), entity3.getTimestamp()); - assertEquals(entity.getTimestamp().toEpochSecond(), entity3.getTimestamp().toEpochSecond()); - assertEquals(TimeUnit.NANOSECONDS.toMicros(entity.getTimestamp().getNano()), - TimeUnit.NANOSECONDS.toMicros(entity3.getTimestamp().getNano())); - } - - @Test - public void testInsertByteArrayField() { - byte[] salt = new byte[16]; - random.nextBytes(salt); - ByteArrayField entity = new ByteArrayField(); - entity.setSalt(salt); - entity = em.insert(entity); - entity = em.load(ByteArrayField.class, entity.getId()); - assertTrue(entity.getId() > 0 && Arrays.equals(entity.getSalt(), salt)); - } - - @Test - public void testInsertByteArrayField_Null() { - ByteArrayField entity = new ByteArrayField(); - entity = em.insert(entity); - entity = em.load(ByteArrayField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getSalt() == null); - } - - @Test - public void testInsertCharArrayField() { - CharArrayField entity = new CharArrayField(); - char[] password = "secret".toCharArray(); - entity.setPassword(password); - entity = em.insert(entity); - entity = em.load(CharArrayField.class, entity.getId()); - assertTrue(entity.getId() > 0 && Arrays.equals(password, entity.getPassword())); - } - - @Test - public void testInsertCharArrayField_Blank() { - CharArrayField entity = new CharArrayField(); - char[] password = "".toCharArray(); - entity.setPassword(password); - entity = em.insert(entity); - entity = em.load(CharArrayField.class, entity.getId()); - assertTrue(entity.getId() > 0 && Arrays.equals(password, entity.getPassword())); - } - - @Test - public void testInsertCharArrayField_Null() { - CharArrayField entity = new CharArrayField(); - entity = em.insert(entity); - entity = em.load(CharArrayField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getPassword() == null); - } - - @Test - public void testInsertEnumField() { - EnumField entity = new EnumField(); - entity.setSize(EnumField.Size.LARGE); - entity = em.insert(entity); - entity = em.load(EnumField.class, entity.getId()); - assertEquals(EnumField.Size.LARGE, entity.getSize()); - } - - @Test - public void testInsertEnumField_Null() { - EnumField entity = new EnumField(); - entity = em.insert(entity); - entity = em.load(EnumField.class, entity.getId()); - assertNull(entity.getSize()); - } - - @Test - public void testUpdateEnumField() { - EnumField entity = new EnumField(); - entity.setSize(EnumField.Size.LARGE); - entity = em.insert(entity); - entity.setSize(EnumField.Size.SMALL); - entity = em.update(entity); - entity = em.load(EnumField.class, entity.getId()); - assertEquals(EnumField.Size.SMALL, entity.getSize()); - } - - @Test - public void testUpdateEnumField_Null() { - EnumField entity = new EnumField(); - entity.setSize(EnumField.Size.LARGE); - entity = em.insert(entity); - entity.setSize(null); - entity = em.update(entity); - entity = em.load(EnumField.class, entity.getId()); - assertNull(entity.getSize()); - } - - @Test - public void testInsertKeyReference() { - Department department = new Department(); - department.setName("Sales"); - department = em.insert(department); - - Country country = new Country(); - country.setName("United States"); - country = em.insert(country); - - Employee employee = new Employee(); - employee.setName("Sai Pullabhotla"); - employee.setDepartment(department.getFullKey()); - employee.setCountry(country.getKey()); - employee = em.insert(employee); - assertTrue(employee.getId() > 0 && employee.getDepartment().equals(department.getFullKey())); - } - - @Test - public void testInsertParentChild() { - ParentEntity parent = new ParentEntity(); - parent.setField1("I'm parent!"); - parent = em.insert(parent); - - ChildEntity child = new ChildEntity(); - child.setField1("I'm child!"); - child.setParentKey(parent.getKey()); - child = em.insert(child); - - GrandchildEntity grandchild = new GrandchildEntity(); - grandchild.setField1("I'm grangchild"); - grandchild.setParentKey(child.getKey()); - grandchild = em.insert(grandchild); - - assertTrue(child.getParentKey().equals(parent.getKey()) && grandchild.getParentKey().equals(child.getKey())); - } - - @Test - public void testInsert_GeoLocationField() { - GeoLocationField ny = GeoLocationField.NEW_YORK_CITY; - ny = em.insert(ny); - GeoLocationField entity = em.load(GeoLocationField.class, ny.getId()); - assertTrue(entity.getId() != 0 && entity.getCity().equals(ny.getCity()) - && entity.getCoordinates().equals(ny.getCoordinates())); - } - - @Test - public void testInsert_GeoLocationField_Null() { - GeoLocationField entity = new GeoLocationField(); - entity.setCity("NULL CITY"); - entity = em.insert(entity); - entity = em.load(GeoLocationField.class, entity.getId()); - assertNull(entity.getCoordinates()); - } - - @Test - public void testInsert_IgnoredField() { - IgnoreField entity = new IgnoreField(); - entity.setName("John Doe"); - entity.setComputed("This should not be persisted"); - entity = em.insert(entity); - entity = em.load(IgnoreField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName().equals("John Doe") && entity.getComputed() == null); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateLongId_AutoGenerateTrue() { - LongId entity = new LongId(); - entity.setField1("Update entity that does not exist"); - em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateLongId_AutoGenerateFalse() { - LongId2 entity = new LongId2(); - entity.setField1("Update entity that does not exist"); - em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateStringId_AutoGenerateTrue() { - StringId entity = new StringId(); - entity.setGreetings("Update entity that does not exist"); - em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateStringId_AutoGenerateFalse() { - StringId2 entity = new StringId2(); - entity.setGreetings("Update entity that does not exist"); - em.update(entity); - } - - @Test - public void testUpdateBooleanField() { - BooleanField entity = new BooleanField(); - entity.setAwesome(false); - entity = em.insert(entity); - entity.setAwesome(true); - entity = em.update(entity); - entity = em.load(BooleanField.class, entity.getId()); - assertTrue(entity.isAwesome()); - } - - @Test - public void testUpdateBooleanObject() { - BooleanObject entity = new BooleanObject(); - entity.setAwesome(Boolean.TRUE); - entity = em.insert(entity); - entity.setAwesome(Boolean.FALSE); - entity = em.update(entity); - entity = em.load(BooleanObject.class, entity.getId()); - assertTrue(!entity.getAwesome()); - } - - @Test - public void testUpdateBooleanObject_Null() { - BooleanObject entity = new BooleanObject(); - entity.setAwesome(Boolean.TRUE); - entity = em.insert(entity); - entity.setAwesome(null); - entity = em.update(entity); - entity = em.load(BooleanObject.class, entity.getId()); - assertTrue(entity.getAwesome() == null); - } - - @Test - public void testUpdateCharField() { - CharField entity = new CharField(); - entity.setSex('M'); - entity = em.insert(entity); - entity.setSex('F'); - entity = em.update(entity); - entity = em.load(CharField.class, entity.getId()); - assertTrue(entity.getSex() == 'F'); - } - - @Test - public void testUpdateCharObject() { - CharObject entity = new CharObject(); - entity.setSex('M'); - entity = em.insert(entity); - entity.setSex('F'); - entity = em.update(entity); - entity = em.load(CharObject.class, entity.getId()); - assertTrue(entity.getSex() == 'F'); - } - - @Test - public void testUpdateCharObject_Null() { - CharObject entity = new CharObject(); - entity.setSex('M'); - entity = em.insert(entity); - entity.setSex(null); - entity = em.update(entity); - entity = em.load(CharObject.class, entity.getId()); - assertTrue(entity.getSex() == null); - } - - @Test - public void testUpdateShortField() { - ShortField entity = new ShortField(); - entity.setAge((short) 13); - entity = em.insert(entity); - entity.setAge((short) 30); - entity = em.update(entity); - entity = em.load(ShortField.class, entity.getId()); - assertTrue(entity.getAge() == 30); - } - - @Test - public void testUpdateShortObject() { - ShortObject entity = new ShortObject(); - entity.setAge((short) 13); - entity = em.insert(entity); - entity.setAge((short) 30); - entity = em.update(entity); - entity = em.load(ShortObject.class, entity.getId()); - assertTrue(entity.getAge() == 30); - } - - @Test - public void testUpdateShortObject_Null() { - ShortObject entity = new ShortObject(); - entity.setAge((short) 13); - entity = em.insert(entity); - entity.setAge(null); - entity = em.update(entity); - entity = em.load(ShortObject.class, entity.getId()); - assertTrue(entity.getAge() == null); - } - - @Test - public void testUpdateIntegerField() { - IntegerField entity = new IntegerField(); - entity.setCount(9876543); - entity = em.insert(entity); - entity.setCount(3456789); - entity = em.update(entity); - entity = em.load(IntegerField.class, entity.getId()); - assertTrue(entity.getCount() == 3456789); - } - - @Test - public void testUpdateIntegerObject() { - IntegerObject entity = new IntegerObject(); - entity.setCount(9876543); - entity = em.insert(entity); - entity.setCount(3456789); - entity = em.update(entity); - entity = em.load(IntegerObject.class, entity.getId()); - assertTrue(entity.getCount() == 3456789); - } - - @Test - public void testUpdateIntegerObject_Null() { - IntegerObject entity = new IntegerObject(); - entity.setCount(9876543); - entity = em.insert(entity); - entity.setCount(null); - entity = em.update(entity); - entity = em.load(IntegerObject.class, entity.getId()); - assertTrue(entity.getCount() == null); - } - - @Test - public void testUpdateLongField() { - LongField entity = new LongField(); - entity.setDistanceFromEarth(9876543210L); - entity = em.insert(entity); - entity.setDistanceFromEarth(987654321098765L); - entity = em.update(entity); - entity = em.load(LongField.class, entity.getId()); - assertTrue(entity.getDistanceFromEarth() == 987654321098765L); - } - - @Test - public void testUpdateLongObject() { - LongObject entity = new LongObject(); - entity.setDistanceFromEarth(9876543210L); - entity = em.insert(entity); - entity.setDistanceFromEarth(987654321098765L); - entity = em.update(entity); - entity = em.load(LongObject.class, entity.getId()); - assertTrue(entity.getDistanceFromEarth() == 987654321098765L); - } - - @Test - public void testUpdateLongObject_Null() { - LongObject entity = new LongObject(); - entity.setDistanceFromEarth(9876543210L); - entity = em.insert(entity); - entity.setDistanceFromEarth(null); - entity = em.update(entity); - entity = em.load(LongObject.class, entity.getId()); - assertTrue(entity.getDistanceFromEarth() == null); - } - - @Test - public void testUpdateFloatField() { - FloatField entity = new FloatField(); - entity.setArea(322.456f); - entity = em.insert(entity); - entity.setArea(456.322f); - entity = em.update(entity); - entity = em.load(FloatField.class, entity.getId()); - assertTrue(entity.getArea() == 456.322f); - } - - @Test - public void testUpdateFloatObject() { - FloatObject entity = new FloatObject(); - entity.setArea(322.456f); - entity = em.insert(entity); - entity.setArea(456.322f); - entity = em.update(entity); - entity = em.load(FloatObject.class, entity.getId()); - assertTrue(entity.getArea() == 456.322f); - } - - @Test - public void testUpdateFloatObject_Null() { - FloatObject entity = new FloatObject(); - entity.setArea(322.456f); - entity = em.insert(entity); - entity.setArea(null); - entity = em.update(entity); - entity = em.load(FloatObject.class, entity.getId()); - assertTrue(entity.getArea() == null); - } - - @Test - public void testUpdateDoubleField() { - DoubleField entity = new DoubleField(); - entity.setArea(Double.MAX_VALUE); - entity = em.insert(entity); - entity.setArea(Double.MIN_VALUE); - entity = em.update(entity); - entity = em.load(DoubleField.class, entity.getId()); - assertTrue(entity.getArea() == Double.MIN_VALUE); - } - - @Test - public void testUpdateDoubleObject() { - DoubleObject entity = new DoubleObject(); - entity.setArea(Double.MAX_VALUE); - entity = em.insert(entity); - entity.setArea(Double.MIN_VALUE); - entity = em.update(entity); - entity = em.load(DoubleObject.class, entity.getId()); - assertTrue(entity.getArea() == Double.MIN_VALUE); - } - - @Test - public void testUpdateDoubleObject_Null() { - DoubleObject entity = new DoubleObject(); - entity.setArea(Double.MAX_VALUE); - entity = em.insert(entity); - entity.setArea(null); - entity = em.update(entity); - entity = em.load(DoubleObject.class, entity.getId()); - assertTrue(entity.getArea() == null); - } - - @Test - public void testUpdateStringField() { - StringField entity = new StringField(); - entity.setName("Omaha"); - entity = em.insert(entity); - entity.setName("New York"); - entity = em.update(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getName().equals("New York")); - } - - @Test - public void testUpdateStringField_Empty() { - StringField entity = new StringField(); - entity.setName("Omaha"); - entity = em.insert(entity); - entity.setName(""); - entity = em.update(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getName().equals("")); - } - - @Test - public void testUpdateStringField_Null() { - StringField entity = new StringField(); - entity.setName("Omaha"); - entity = em.insert(entity); - entity.setName(null); - entity = em.update(entity); - entity = em.load(StringField.class, entity.getId()); - assertTrue(entity.getName() == null); - } - - @Test - public void testUpdateCalendarField() { - CalendarField entity = new CalendarField(); - Calendar now = Calendar.getInstance(); - entity.setCreationDate(now); - entity = em.insert(entity); - now.add(Calendar.DATE, 1); - entity.setCreationDate(now); - entity = em.update(entity); - entity = em.load(CalendarField.class, entity.getId()); - assertTrue(entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); - } - - @Test - public void testUpdateCalendarField_Null() { - CalendarField entity = new CalendarField(); - Calendar now = Calendar.getInstance(); - entity.setCreationDate(now); - entity = em.insert(entity); - entity.setCreationDate(null); - entity = em.update(entity); - entity = em.load(CalendarField.class, entity.getId()); - assertTrue(entity.getCreationDate() == null); - } - - @Test - public void testUpdateDateField() { - DateField entity = new DateField(); - Calendar now = Calendar.getInstance(); - entity.setCreationDate(now.getTime()); - entity = em.insert(entity); - now.add(Calendar.DATE, 1); - entity.setCreationDate(now.getTime()); - entity = em.update(entity); - entity = em.load(DateField.class, entity.getId()); - assertTrue(entity.getCreationDate().getTime() == now.getTimeInMillis()); - } - - @Test - public void testUpdateDateField_Null() { - DateField entity = new DateField(); - Calendar now = Calendar.getInstance(); - entity.setCreationDate(now.getTime()); - entity = em.insert(entity); - entity.setCreationDate(null); - entity = em.update(entity); - entity = em.load(DateField.class, entity.getId()); - assertTrue(entity.getCreationDate() == null); - } - - @Test - public void testUpdateLocalDateField() { - LocalDateField entity = new LocalDateField(); - LocalDate today = LocalDate.now(); - entity.setBirthDate(today); - entity = em.insert(entity); - LocalDate tomorrow = today.plusDays(1); - entity.setBirthDate(tomorrow); - entity = em.update(entity); - entity = em.load(LocalDateField.class, entity.getId()); - assertTrue(entity.getBirthDate().equals(tomorrow)); - } - - @Test - public void testUpdateLocalDateField_Null() { - LocalDateField entity = new LocalDateField(); - LocalDate today = LocalDate.now(); - entity.setBirthDate(today); - entity = em.insert(entity); - entity.setBirthDate(null); - entity = em.update(entity); - entity = em.load(LocalDateField.class, entity.getId()); - assertNull(entity.getBirthDate()); - } - - @Test - public void testUpdateLocalTimeField() { - LocalTimeField entity = new LocalTimeField(); - LocalTime now = LocalTime.now(); - entity.setStartTime(now); - entity = em.insert(entity); - LocalTime plusOneHour = now.plusHours(1); - entity.setStartTime(plusOneHour); - entity = em.update(entity); - entity = em.load(LocalTimeField.class, entity.getId()); - assertEquals(plusOneHour, entity.getStartTime()); - } - - @Test - public void testUpdateLocalTimeField_Null() { - LocalTimeField entity = new LocalTimeField(); - LocalTime now = LocalTime.now(); - entity.setStartTime(now); - entity = em.insert(entity); - entity.setStartTime(null); - entity = em.update(entity); - entity = em.load(LocalTimeField.class, entity.getId()); - assertNull(entity.getStartTime()); - } - - @Test - public void testUpdateLocalDateTimeField() { - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime now = LocalDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - LocalDateTime nextDay = now.plusDays(1); - entity.setTimestamp(nextDay); - entity = em.update(entity); - entity = em.load(LocalDateTimeField.class, entity.getId()); - assertEquals(nextDay, entity.getTimestamp()); - } - - @Test - public void testUpdateLocalDateTimeField_Nano() { - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime now = LocalDateTime.now().withNano(999999999); - entity.setTimestamp(now); - entity = em.insert(entity); - LocalDateTime nextDay = now.plusDays(1); - entity.setTimestamp(nextDay); - entity = em.update(entity); - entity = em.load(LocalDateTimeField.class, entity.getId()); - assertEquals(nextDay, entity.getTimestamp()); - } - - @Test - public void testUpdateLocalDateTimeField_Null() { - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime now = LocalDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity.setTimestamp(null); - entity = em.update(entity); - entity = em.load(LocalDateTimeField.class, entity.getId()); - assertNull(entity.getTimestamp()); - } - - @Test - public void testUpdateOffsetDateTimeField() { - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime now = OffsetDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - OffsetDateTime nextDay = now.plusDays(2); - entity.setTimestamp(nextDay); - entity = em.update(entity); - entity = em.load(OffsetDateTimeField.class, entity.getId()); - assertEquals(nextDay, entity.getTimestamp()); - } - - @Test - public void testUpdateOffsetDateTimeField_Null() { - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime now = OffsetDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity.setTimestamp(null); - entity = em.update(entity); - entity = em.load(OffsetDateTimeField.class, entity.getId()); - assertNull(entity.getTimestamp()); - } - - @Test - public void testUpdateZonedDateTimeField() { - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime now = ZonedDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - ZonedDateTime nextDay = now.plusDays(2); - entity.setTimestamp(nextDay); - entity = em.update(entity); - entity = em.load(ZonedDateTimeField.class, entity.getId()); - assertEquals(nextDay, entity.getTimestamp()); - } - - @Test - public void testUpdateZonedDateTimeField_Null() { - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime now = ZonedDateTime.now(); - entity.setTimestamp(now); - entity = em.insert(entity); - entity.setTimestamp(null); - entity = em.update(entity); - entity = em.load(ZonedDateTimeField.class, entity.getId()); - assertNull(entity.getTimestamp()); - } - - @Test - public void testUpdateByteArayField() { - byte[] salt = new byte[64]; - random.nextBytes(salt); - ByteArrayField entity = new ByteArrayField(); - entity.setSalt(salt); - entity = em.insert(entity); - salt = new byte[32]; - random.nextBytes(salt); - entity.setSalt(salt); - entity = em.update(entity); - entity = em.load(ByteArrayField.class, entity.getId()); - assertTrue(Arrays.equals(salt, entity.getSalt())); - } - - @Test - public void testUpdateByteArayField_Null() { - byte[] salt = new byte[64]; - random.nextBytes(salt); - ByteArrayField entity = new ByteArrayField(); - entity.setSalt(salt); - entity = em.insert(entity); - salt = null; - entity.setSalt(salt); - entity = em.update(entity); - entity = em.load(ByteArrayField.class, entity.getId()); - assertTrue(entity.getSalt() == null); - } - - @Test - public void testUpdateCharArayField() { - char[] password = "super secret phrase".toCharArray(); - CharArrayField entity = new CharArrayField(); - entity.setPassword(password); - entity = em.insert(entity); - password = "What a lovely day!".toCharArray(); - entity.setPassword(password); - entity = em.update(entity); - entity = em.load(CharArrayField.class, entity.getId()); - assertTrue(Arrays.equals(password, entity.getPassword())); - } - - @Test - public void testUpdateCharArayField_Null() { - char[] password = "super secret phrase".toCharArray(); - CharArrayField entity = new CharArrayField(); - entity.setPassword(password); - entity = em.insert(entity); - password = null; - entity.setPassword(password); - entity = em.update(entity); - entity = em.load(CharArrayField.class, entity.getId()); - assertTrue(entity.getPassword() == null); - } - - @Test - public void testInsert_ListFields() { - ListFields entity = ListFields.getSampleEntity1(); - entity = em.insert(entity); - ListFields entity2 = em.load(ListFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_ListFields_Null() { - ListFields entity = new ListFields(); - entity = em.insert(entity); - ListFields entity2 = em.load(ListFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_ListFields() { - ListFields entity = ListFields.getSampleEntity1(); - entity = em.insert(entity); - List stringList = entity.getStringList(); - stringList.add("Ten"); - stringList.add("Hundred"); - entity = em.update(entity); - ListFields entity2 = em.load(ListFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_ListFields_Null() { - ListFields entity = ListFields.getSampleEntity1(); - entity = em.insert(entity); - entity.setStringList(null); - entity = em.update(entity); - ListFields entity2 = em.load(ListFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_ListFields_Keys() { - ListFields entity = new ListFields(); - String[] tagNames = { "List", "ArrayList", "LinkedList" }; - List tags = new ArrayList<>(); - for (String tagName : tagNames) { - Tag tag = new Tag(); - tag.setName(tagName); - tags.add(tag); - } - tags = em.insert(tags); - List keyList = new ArrayList<>(); - for (Tag tag : tags) { - keyList.add(tag.getKey()); - } - entity.setKeyList(keyList); - entity = em.insert(entity); - ListFields entity2 = em.load(ListFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_SetFields() { - SetFields entity = SetFields.getSampleEntity1(); - entity = em.insert(entity); - SetFields entity2 = em.load(SetFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_SetFields() { - SetFields entity = SetFields.getSampleEntity1(); - entity = em.insert(entity); - Set stringSet = entity.getStringSet(); - stringSet.add("Powerball"); - entity = em.update(entity); - SetFields entity2 = em.load(SetFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_SetFields_Null() { - SetFields entity = new SetFields(); - entity = em.insert(entity); - SetFields entity2 = em.load(SetFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_SetFields_Null() { - SetFields entity = SetFields.getSampleEntity1(); - entity = em.insert(entity); - entity.setStringSet(null); - entity = em.update(entity); - SetFields entity2 = em.load(SetFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_SetFields_Keys() { - SetFields entity = new SetFields(); - String[] tagNames = { "Set", "HashSet", "LinkedHashSet", "TreeSet" }; - List tags = new ArrayList<>(); - for (String tagName : tagNames) { - Tag tag = new Tag(); - tag.setName(tagName); - tags.add(tag); - } - tags = em.insert(tags); - Set keySet = new HashSet<>(); - for (Tag tag : tags) { - keySet.add(tag.getKey()); - } - entity.setKeySet(keySet); - entity = em.insert(entity); - SetFields entity2 = em.load(SetFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_MapFields() { - MapFields entity = MapFields.getSampleEntity1(); - entity = em.insert(entity); - MapFields entity2 = em.load(MapFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_MapFields_Null() { - MapFields entity = new MapFields(); - entity = em.insert(entity); - MapFields entity2 = em.load(MapFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_MapFields() { - MapFields entity = MapFields.getSampleEntity1(); - entity = em.insert(entity); - entity.getStringMap().put("Catatumbo", "Framework for GCS"); - entity = em.update(entity); - MapFields entity2 = em.load(MapFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_MapFields_Null() { - MapFields entity = MapFields.getSampleEntity1(); - entity = em.insert(entity); - entity.setStringMap(null); - entity = em.update(entity); - MapFields entity2 = em.load(MapFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_MapFields_Keys() { - MapFields entity = new MapFields(); - String[] tagNames = { "Map", "HashMap", "SortedMap", "TreeMap", "LinkedHashMap" }; - List tags = new ArrayList<>(); - for (String tagName : tagNames) { - Tag tag = new Tag(); - tag.setName(tagName); - tags.add(tag); - } - tags = em.insert(tags); - Map keyMap = new HashMap<>(); - int i = 0; - for (Tag tag : tags) { - keyMap.put(tag.getName(), tag.getKey()); - } - entity.setKeyMap(keyMap); - entity = em.insert(entity); - MapFields entity2 = em.load(MapFields.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test(expected = EntityNotFoundException.class) - public void testUpdate_ThatDoesNotExist() { - LongId entity = new LongId(); - entity.setId(100); - entity.setField1("I'm 100L"); - // In case if it exists, delete it - em.delete(entity); - LongId entity2 = em.load(LongId.class, entity.getId()); - if (entity2 == null) { - try { - em.update(entity); - } catch (EntityNotFoundException exp) { - throw exp; - } catch (EntityManagerException exp) { - String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); - if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { - // Running on emulator that has a bug. - throw new EntityNotFoundException(exp); - } - } - } - } - - @Test - public void testUpdate_GeoLocationField() { - GeoLocationField omaha = GeoLocationField.OMAHA; - GeoLocationField entity = new GeoLocationField(omaha.getCity(), omaha.getCoordinates()); - entity = em.insert(entity); - GeoLocation newCoordinates = new GeoLocation(10, 10); - entity.setCoordinates(newCoordinates); - em.update(entity); - entity = em.load(GeoLocationField.class, entity.getId()); - assertTrue(entity.getCoordinates().equals(newCoordinates)); - } - - @Test - public void testUpdate_GeoLocationField_Null() { - GeoLocationField paris = GeoLocationField.PARIS; - GeoLocationField entity = new GeoLocationField(paris.getCity(), paris.getCoordinates()); - entity = em.insert(entity); - entity.setCoordinates(null); - em.update(entity); - entity = em.load(GeoLocationField.class, entity.getId()); - assertNull(entity.getCoordinates()); - } - - @Test - public void testUpdate_IgnoredField() { - IgnoreField entity = new IgnoreField(); - entity.setName("John Doe"); - entity.setComputed("This should not be persisted"); - entity = em.insert(entity); - entity = em.load(IgnoreField.class, entity.getId()); - entity.setName("John Smith"); - entity.setComputed("Wassup!"); - em.update(entity); - entity = em.load(IgnoreField.class, entity.getId()); - assertTrue(entity.getId() > 0 && entity.getName().equals("John Smith") && entity.getComputed() == null); - } - - @Test - public void testUpsert_LongId_Insert() { - final String message = "Upsert created me"; - LongId entity = new LongId(); - entity.setField1(message); - entity = em.upsert(entity); - entity = em.load(LongId.class, entity.getId()); - assertTrue(message.equals(entity.getField1())); - } - - @Test - public void testUpsert_LongId_Update() { - final String message = "Upsert created me"; - final String message2 = "Upsert created me, then updated"; - LongId entity = new LongId(); - entity.setField1(message); - entity = em.upsert(entity); - entity = em.load(LongId.class, entity.getId()); - entity.setField1(message2); - em.upsert(entity); - entity = em.load(LongId.class, entity.getId()); - assertTrue(message2.equals(entity.getField1())); - } - - @Test - public void testUpsert_StringId_Insert() { - final String greetings = "Upsert created me"; - StringId entity = new StringId(); - entity.setGreetings(greetings); - entity = em.upsert(entity); - entity = em.load(StringId.class, entity.getId()); - assertTrue(greetings.equals(entity.getGreetings())); - - } - - @Test - public void testUpsert_StringId_Update() { - final String greetings1 = "Upsert created me"; - final String greetings2 = "Upsert first created me, then updated"; - StringId entity = new StringId(); - entity.setGreetings(greetings1); - entity = em.upsert(entity); - entity = em.load(StringId.class, entity.getId()); - entity.setGreetings(greetings2); - em.upsert(entity); - entity = em.load(StringId.class, entity.getId()); - assertTrue(greetings2.equals(entity.getGreetings())); - - } - - @Test - public void testUpsert_List_Insert() { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - StringField entity = new StringField(); - entity.setName("I'm StringField Entity " + i); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.size() == 5 && entities.get(0).getId() != 0); - } - - @Test(expected = EntityManagerException.class) - public void testDelete_UnsetId() { - StringField entity = new StringField(); - em.delete(entity); - } - - @Test - public void testDelete_Root() { - StringField entity = new StringField(); - entity.setName("Hello World!"); - entity = em.insert(entity); - entity = em.load(StringField.class, entity.getId()); - em.delete(entity); - StringField entity2 = em.load(StringField.class, entity.getId()); - assertTrue(entity != null && entity2 == null); - } - - @Test - public void testDelete_Child() { - ParentEntity parent = new ParentEntity(); - parent.setField1("Parent for Delete Test!"); - parent = em.insert(parent); - - ChildEntity child = new ChildEntity(); - child.setField1("Child for Delete Test"); - child.setParentKey(parent.getKey()); - child = em.insert(child); - - child = em.load(ChildEntity.class, parent.getKey(), child.getId()); - em.delete(child); - ChildEntity child2 = em.load(ChildEntity.class, parent.getKey(), child.getId()); - assertTrue(child != null && child2 == null); - } - - @Test - public void testDelete_Child_WithNoParent() { - ParentEntity parent = new ParentEntity(); - parent.setField1("Parent for Delete Test!"); - parent = em.insert(parent); - - ChildEntity child = new ChildEntity(); - child.setField1("Child for Delete Test"); - child.setParentKey(parent.getKey()); - child = em.insert(child); - - // Second Child with the same ID as the first one, but no parent. - ChildEntity child2 = new ChildEntity(); - child2.setId(child.getId()); - child2.setField1("Child with no parent"); - child2 = em.insert(child2); - - child2 = em.load(ChildEntity.class, child2.getId()); - em.delete(child2); - ChildEntity child3 = em.load(ChildEntity.class, child2.getId()); - assertTrue(child2 != null && child3 == null); - } - - @Test - public void testDelete_Grandchild() { - ParentEntity parent = new ParentEntity(); - parent.setField1("Parent for Delete Test!"); - parent = em.insert(parent); - - ChildEntity child = new ChildEntity(); - child.setField1("Child for Delete Test"); - child.setParentKey(parent.getKey()); - child = em.insert(child); - - GrandchildEntity grandchild = new GrandchildEntity(); - grandchild.setField1("Grandchild for Delete Test"); - grandchild.setParentKey(child.getKey()); - grandchild = em.insert(grandchild); - - grandchild = em.load(GrandchildEntity.class, child.getKey(), grandchild.getId()); - em.delete(grandchild); - GrandchildEntity grandchild2 = em.load(GrandchildEntity.class, child.getKey(), grandchild.getId()); - assertTrue(grandchild != null && grandchild2 == null); - } - - /* - * @Test public void testDeleteAll() { List entities = new - * ArrayList<>(); for (int i = 0; i < 5; i++) { DeleteAll entity = new - * DeleteAll(); entity.setField1("Delete All " + i); entities.add(entity); } - * em.insert(entities); try { Thread.sleep(5000L); } catch - * (InterruptedException e) { e.printStackTrace(); } long deleteCount = - * em.deleteAll(DeleteAll.class); assertTrue(deleteCount == 5); } - */ - - @Test - public void testLoad_ThatDoesNotExist() { - long id = random.nextLong(); - StringField entity = new StringField(); - entity.setId(id); - em.delete(entity); - StringField entity2 = em.load(StringField.class, id); - assertNull(entity2); - } - - @Test - public void testLoad_Good() { - long id = random.nextLong(); - StringField entity = new StringField(); - entity.setId(id); - entity.setName("USA"); - em.delete(entity); - em.insert(entity); - StringField entity2 = em.load(StringField.class, entity.getId()); - assertTrue(entity.getId() == entity2.getId()); - } - - @Test - public void testLoad_ParentChild() { - ParentEntity parent = new ParentEntity(); - parent.setField1("Parent for load test"); - parent = em.insert(parent); - - ChildEntity child = new ChildEntity(); - child.setField1("Child for load test"); - child.setParentKey(parent.getKey()); - child = em.insert(child); - - GrandchildEntity grandchild = new GrandchildEntity(); - grandchild.setField1("Grandchild for laod test"); - grandchild.setParentKey(child.getKey()); - grandchild = em.insert(grandchild); - - ParentEntity parent2 = em.load(ParentEntity.class, parent.getId()); - ChildEntity child2 = em.load(ChildEntity.class, parent2.getKey(), child.getId()); - GrandchildEntity grandchild2 = em.load(GrandchildEntity.class, child2.getKey(), grandchild.getId()); - - assertTrue(grandchild.getId() == grandchild2.getId() && grandchild.getField1().equals(grandchild2.getField1()) - && grandchild.getParentKey().equals(grandchild2.getParentKey())); - } - - @Test - public void testLoad_IgnoredField() { - IgnoreField2 entity = new IgnoreField2(); - entity.setName("Hello World"); - entity.setComputed("Hola Mundo"); - entity = em.insert(entity); - entity = em.load(IgnoreField2.class, entity.getId()); - - // Load the previously inserted entity using IgnoreFeild.class - IgnoreField entity2 = em.load(IgnoreField.class, entity.getId()); - assertTrue(entity.getId() == entity2.getId() && entity.getComputed() != null && entity2.getComputed() == null); - } - - @Test - public void testLoadById() { - List entities = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - LongId entity = new LongId(); - entity.setField1("Test for Loading Multiple Entities " + i); - entities.add(entity); - } - entities = em.insert(entities); - List identifiers = new ArrayList<>(); - for (LongId entity : entities) { - identifiers.add(entity.getId()); - } - List entities2 = em.loadById(LongId.class, identifiers); - assertEquals(entities, entities2); - } - - @Test - public void testLoadById_MissingKey() { - List entities = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - LongId entity = new LongId(); - entity.setField1("Test for Loading Multiple Entities " + i); - entities.add(entity); - } - entities = em.insert(entities); - List identifiers = new ArrayList<>(); - for (LongId entity : entities) { - identifiers.add(entity.getId()); - } - identifiers.add(0, -100L); - identifiers.add(3, -200L); - List entities2 = em.loadById(LongId.class, identifiers); - assertTrue(entities2.get(0) == null && entities2.get(1) != null && entities2.get(3) == null); - } - - @Test - public void testLoadByName() { - List entities = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - StringId entity = new StringId(); - entity.setGreetings("Test for Loading Multiple Entities " + i); - entities.add(entity); - } - entities = em.insert(entities); - List identifiers = new ArrayList<>(); - for (StringId entity : entities) { - identifiers.add(entity.getId()); - } - List entities2 = em.loadByName(StringId.class, identifiers); - assertEquals(entities, entities2); - } - - @Test - public void executeTest_SelectAll() { - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Task order by __key__"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 50 && tasks.get(0).getId() == 1 && tasks.get(tasks.size() - 1).getId() == 50); - } - - @Test - public void rexecuteTest_SelectPriorityFilter() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = @1 order by __key__"); - request.addPositionalBinding(0); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 10 && tasks.get(0).getId() == 5 && tasks.get(tasks.size() - 1).getId() == 50); - } - - @Test - public void executeTest_SelectPriorityAndCompleteFilter() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = @1 AND complete = @2 order by __key__"); - request.addPositionalBinding(0); - request.addPositionalBinding(true); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 10 && tasks.get(tasks.size() - 1).getId() == 50); - } - - @Test - public void testExecute_SelectPriorityAndCompleteFilter_Varargs() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = @1 AND complete = @2 order by __key__"); - request.addPositionalBindings(0, true); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 10 && tasks.get(tasks.size() - 1).getId() == 50); - } - - @Test - public void executeTest_SelectTaskNameFilter() { - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Task WHERE name = @1 order by __key__"); - request.addPositionalBinding("My Task 13"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 1 && tasks.get(0).getId() == 13); - } - - @Test - public void executeTest_SelectTasksDueByTomorrow() { - Calendar cal = getToday(); - cal.add(Calendar.DATE, 1); - Date tomorrow = cal.getTime(); - - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Task WHERE completionDate <= @1"); - request.addPositionalBinding(tomorrow); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 20); - } - - @Test - public void executeTest_SelectTasksDueByBetweenTomorrowAndDayAfter_NamedBindings() { - Calendar cal = getToday(); - cal.add(Calendar.DATE, 1); - Date tomorrow = cal.getTime(); - cal.add(Calendar.DATE, 1); - Date dayAfterTomorrow = cal.getTime(); - Map bindings = new HashMap<>(); - bindings.put("Tomorrow", tomorrow); - bindings.put("DayAfterTomorrow", dayAfterTomorrow); - - EntityQueryRequest request = em.createEntityQueryRequest( - "SELECT * FROM Task WHERE completionDate >= @Tomorrow AND completionDate <= @DayAfterTomorrow"); - request.setNamedBindings(bindings); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 20); - } - - @Test - public void runQueryTest_Pagination_Forward() { - final int pageSize = 5; - String query = "SELECT * FROM Task ORDER BY __key__"; - DatastoreCursor endCursor = null; - List tasks = null; - for (int i = 0; i < 5; i++) { - String pageQuery = query + " LIMIT @Limit"; - if (i > 0) { - pageQuery += " OFFSET @Offset"; - } - EntityQueryRequest request = em.createEntityQueryRequest(pageQuery); - request.setNamedBinding("Limit", pageSize); - if (i > 0) { - request.setNamedBinding("Offset", endCursor); - } - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - tasks = response.getResults(); - endCursor = response.getEndCursor(); - System.out.println("**** Page " + (i + 1) + "****"); - for (Task task : tasks) { - System.out.println(task.getId() + " ---> " + task.getName()); - } - } - assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 21); - - } - - @Test - public void testExecute() { - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * from Task"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - for (Task task : tasks) { - System.out.println(task.getId() + "--->" + task.getName()); - } - System.out.println("Start Cursor: " + response.getStartCursor()); - System.out.println("End Cursor: " + response.getEndCursor()); - assertTrue(tasks.size() == 50); - } - - @Test - public void testExecute_Limit_10() { - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * from Task LIMIT @1"); - request.addPositionalBinding(10L); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - System.out.println("Start Cursor: " + response.getStartCursor()); - System.out.println("End Cursor: " + response.getEndCursor()); - for (Task task : tasks) { - System.out.println(task.getId() + "--->" + task.getName()); - } - assertTrue(tasks.size() == 10); - } - - @Test - public void testExecute_PositionalBinding() { - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * from Task WHERE priority=@1"); - request.addPositionalBinding(3); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - System.out.println("Start Cursor: " + response.getStartCursor()); - System.out.println("End Cursor: " + response.getEndCursor()); - for (Task task : tasks) { - System.out.println(task.getId() + "--->" + task.getName()); - } - assertTrue(tasks.size() == 10); - } - - @Test - public void testExecute_PositionalBindings() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * from Task WHERE priority=@1 AND complete=@2"); - request.addPositionalBinding(0); - request.addPositionalBinding(true); - - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - System.out.println("Start Cursor: " + response.getStartCursor()); - System.out.println("End Cursor: " + response.getEndCursor()); - for (Task task : tasks) { - System.out.println(task.getId() + "--->" + task.getName()); - } - assertTrue(tasks.size() == 5); - } - - @Test - public void testExecute_GeoLocation() { - em.deleteAll(GeoLocationField.class); - GeoLocationField jfk = GeoLocationField.NEW_YORK_CITY; - GeoLocationField oma = GeoLocationField.OMAHA; - GeoLocationField cdg = GeoLocationField.PARIS; - em.insert(jfk); - em.insert(oma); - em.insert(cdg); - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM CityCoordinates ORDER BY city"); - QueryResponse response = em.executeEntityQueryRequest(GeoLocationField.class, request); - List cities = response.getResults(); - // This test fails sometimes if the below assertion is cities.size() == - // 3. - assertTrue(cities.size() > 0 && cities.get(0).getCoordinates().equals(jfk.getCoordinates())); - - } - - @Test - public void testExecuteProjectionQuery() { - ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Task"); - QueryResponse response = em.executeProjectionQueryRequest(Task.class, request); - List tasks = response.getResults(); - for (Task task : tasks) { - System.out.printf("Id: %d; Name: %s; Priority: %s; Complete: %s; Completion Date: %s\n", task.getId(), - task.getName(), task.getPriority(), task.isComplete(), task.getCompletionDate()); - } - assertTrue(tasks.size() == 50); - } - - @Test - public void testExecuteProjectionQuery2() { - // Uses a different entity - with a subset of properties from the main - // entity - ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Task"); - QueryResponse response = em.executeProjectionQueryRequest(TaskName.class, request); - List tasks = response.getResults(); - for (TaskName task : tasks) { - System.out.printf("Id: %d; Name: %s; \n", task.getId(), task.getName()); - } - assertTrue(tasks.size() == 50); - } - - @Test - public void testExecuteKeyQuery() { - KeyQueryRequest request = em.createKeyQueryRequest("SELECT __key__ from Task"); - QueryResponse response = em.executeKeyQueryRequest(request); - List keys = response.getResults(); - for (DatastoreKey key : keys) { - System.out.printf("%-10s %20s %s\n", key.kind(), key.nameOrId(), key.getEncoded()); - } - assertTrue(keys.size() == 50); - } - - @Test(expected = EntityManagerException.class) - public void testUpdate_InvalidStringId() { - StringId entity = new StringId(); - entity.setGreetings("Good Night, this should never show up in the datastore"); - entity = em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testExecute_WithLiteral_Default() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - } - - @Test(expected = EntityManagerException.class) - public void testExecute_WithLiteral_False() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - } - - @Test - public void testExecute_WithLiteral_True() { - EntityQueryRequest request = em - .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); - request.setAllowLiterals(true); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - List tasks = response.getResults(); - assertTrue(tasks.size() == 10 && tasks.get(0).getId() == 5 && tasks.get(tasks.size() - 1).getId() == 50); - } - - @Test(expected = EntityManagerException.class) - public void testExecute_WithSyntheticLiteral_Default() { - EntityQueryRequest request = em.createEntityQueryRequest( - "SELECT * FROM Task where completionDate > datetime('2016-08-10T00:00:00.000000z')"); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - } - - @Test - public void testExecute_WithSyntheticLiteral_True() { - EntityQueryRequest request = em.createEntityQueryRequest( - "SELECT * FROM Task where completionDate > datetime('2016-08-10T00:00:00.000000z')"); - request.setAllowLiterals(true); - QueryResponse response = em.executeEntityQueryRequest(Task.class, request); - // Let's not worry about the results - } - - @Test - public void testInsert_Embedded() { - Customer entity = Customer.createSampleCustomer1(); - entity = em.insert(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_Embedded_NullAddress() { - Customer entity = Customer.createSampleCustomer2(); - entity = em.insert(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_Embedded_NullZipCode() { - Customer entity = Customer.createSampleCustomer3(); - entity = em.insert(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_Embedded() { - Customer entity = Customer.createSampleCustomer1(); - entity = em.insert(entity); - entity = em.load(Customer.class, entity.getId()); - entity.setName("John Smith"); - entity.getBillingAddress().setCity("Lincoln"); - entity.getShippingAddress().getZipCode().setFiveDigits("65432"); - em.update(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_Embedded_NullAddress() { - Customer entity = Customer.createSampleCustomer2(); - entity = em.insert(entity); - entity = em.load(Customer.class, entity.getId()); - entity.setName("Super Customer Updated"); - entity.getBillingAddress().setCity("Lincoln"); - entity.getShippingAddress().getZipCode().setFiveDigits("65432"); - em.update(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_Embedded_NullZipCode() { - Customer entity = Customer.createSampleCustomer3(); - entity = em.insert(entity); - entity = em.load(Customer.class, entity.getId()); - entity.setName("Super Customer Updated"); - entity.getShippingAddress().getZipCode().setFiveDigits("65432"); - entity.getBillingAddress().getZipCode().setFiveDigits("65432"); - em.update(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testDelete_Embedded() { - Customer entity = Customer.createSampleCustomer1(); - entity = em.insert(entity); - entity = em.load(Customer.class, entity.getId()); - em.delete(entity); - Customer entity2 = em.load(Customer.class, entity.getId()); - assertTrue(entity != null && entity2 == null); - } - - @Test - public void testExecuteEntityQuery_Embedded() { - em.deleteAll(Customer.class); - List customers = new ArrayList<>(); - customers.add(Customer.createSampleCustomer1()); - customers.add(Customer.createSampleCustomer2()); - customers.add(Customer.createSampleCustomer3()); - em.insert(customers); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Customer"); - QueryResponse response = em.executeEntityQueryRequest(Customer.class, request); - List output = response.getResults(); - assertTrue(output.size() == 3); - } - - @Test - public void testExecuteProjectionQuery_Embedded() { - em.deleteAll(Customer.class); - List customers = new ArrayList<>(); - customers.add(Customer.createSampleCustomer1()); - customers.add(Customer.createSampleCustomer2()); - customers.add(Customer.createSampleCustomer3()); - em.insert(customers); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Customer"); - QueryResponse response = em.executeProjectionQueryRequest(Customer.class, request); - List output = response.getResults(); - assertTrue(output.size() == 3); - } - - @Test - public void testInsert_MappedSupperClass() { - SubClass1 entity = new SubClass1(); - entity.setName("John Doe"); - entity.setCreatedBy("user1"); - entity.setCreatedOn(new Date()); - entity.setModifiedBy("user2"); - entity.setModifiedOn(new Date()); - entity = em.insert(entity); - SubClass1 entity2 = em.load(SubClass1.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_MappedSupperClass2() { - SubClass2 entity = new SubClass2(); - entity.setName("John Doe"); - entity.setCreatedBy("user1"); - entity.setCreatedOn(new Date()); - entity.setModifiedBy("user2"); - entity.setModifiedOn(new Date()); - entity = em.insert(entity); - SubClass2 entity2 = em.load(SubClass2.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testUpdate_MappedSupperClass2() { - SubClass2 entity = new SubClass2(); - entity.setName("John Doe"); - entity.setCreatedBy("user1"); - entity.setCreatedOn(new Date()); - entity.setModifiedBy("user2"); - entity.setModifiedOn(new Date()); - entity = em.insert(entity); - SubClass2 entity2 = em.load(SubClass2.class, entity.getId()); - entity2.setName("John Smith"); - em.update(entity2); - SubClass2 entity3 = em.load(SubClass2.class, entity2.getId()); - assertTrue(entity3.equals(entity2)); - } - - @Test - public void testInsert_MappedSupperClass3() { - SubClass3 entity = new SubClass3(); - entity.setFieldx("I'm super super!"); - entity.setName("John Doe"); - entity.setCreatedBy("user1"); - entity.setCreatedOn(new Date()); - entity.setModifiedBy("user2"); - entity.setModifiedOn(new Date()); - entity = em.insert(entity); - SubClass3 entity2 = em.load(SubClass3.class, entity.getId()); - assertTrue(entity.equals(entity2) && entity2.getMyKey() != null); - } - - @Test - public void testInsert_MappedSupperClass4() { - SubClass4 entity = new SubClass4(); - entity.setFieldx("I'm super super!"); - entity.setName("John Doe"); - entity.setCreatedBy("user1"); - entity.setCreatedOn(new Date()); - entity.setModifiedBy("user2"); - entity.setModifiedOn(new Date()); - entity = em.insert(entity); - SubClass4 entity2 = em.load(SubClass4.class, entity.getId()); - assertTrue(entity.equals(entity2) && entity2.getCreatedBy() == null); - } - - @Test - public void testInsert_OptimisticLock1() { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Optimistic Lock Test Insert Single"); - OptimisticLock1 entity2 = em.insert(entity); - assertTrue(entity2.getId() != 0 && entity2.getVersion() == 1); - } - - @Test - public void testInsert_OptimisticLock1_Multiple() { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Optimistic Lock Test Insert Multiple " + i); - entities.add(entity); - } - List insertedEntities = em.insert(entities); - assertTrue(insertedEntities.get(0).getVersion() == 1 && insertedEntities.get(1).getVersion() == 1 - && insertedEntities.get(2).getVersion() == 1 && insertedEntities.get(3).getVersion() == 1 - && insertedEntities.get(4).getVersion() == 1); - } - - @Test - public void testUpdate_OptimisticLock1() { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Before Update!"); - OptimisticLock1 entity2 = em.insert(entity); - OptimisticLock1 entity3 = em.load(OptimisticLock1.class, entity2.getId()); - entity3.setName("After Update"); - OptimisticLock1 entity4 = em.update(entity3); - OptimisticLock1 entity5 = em.load(OptimisticLock1.class, entity4.getId()); - assertTrue(entity2.getVersion() == 1 && entity3.getVersion() == 1 && entity4.getVersion() == 2 - && entity5.getVersion() == 2); - } - - @Test(expected = EntityManagerException.class) - public void testUpdate_OptimisticLock2() { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Hello World!"); - entity = em.insert(entity); - OptimisticLock1 entity2 = em.load(OptimisticLock1.class, entity.getId()); - entity2.setName("Hello World! After Update!!"); - entity2 = em.update(entity2); - entity2 = em.update(entity2); - entity2 = em.update(entity2); - entity = em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpdate_OptimisticLock3() { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Hello World!"); - entity = em.insert(entity); - OptimisticLock1 entity2 = em.load(OptimisticLock1.class, entity.getId()); - entity2.setName("Hello World! After Update!!"); - entity2 = em.update(entity2); - em.delete(entity); - entity2 = em.update(entity2); - } - - @Test - public void testUpdate_OptimisticLock4() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Test Update Multiple " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); - List entities3 = em.loadById(OptimisticLock1.class, ids); - List entities4 = em.update(entities3); - assertEquals(1, entities2.get(0).getVersion()); - assertEquals(1, entities2.get(1).getVersion()); - assertEquals(1, entities3.get(0).getVersion()); - assertEquals(1, entities3.get(1).getVersion()); - assertEquals(2, entities4.get(0).getVersion()); - assertEquals(2, entities4.get(1).getVersion()); - } - - @Test(expected = OptimisticLockException.class) - public void testUpdate_OptimisticLock5() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Test Update Multiple " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); - List entities3 = em.loadById(OptimisticLock1.class, ids); - em.delete(entities3); - List entities4 = em.update(entities3); - } - - @Test(expected = OptimisticLockException.class) - public void testUpdate_OptimisticLock6() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - OptimisticLock1 entity = new OptimisticLock1(); - entity.setName("Test Update Multiple " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); - List entities3 = em.loadById(OptimisticLock1.class, ids); - List entities4 = em.update(entities3); - List entities5 = em.update(entities3); - } - - @Test - public void testRunInTransaction() { - final StringField entity = new StringField(); - entity.setName("Run in transaction test"); - final StringField insertedEntity = em.insert(entity); - StringField updatedEntity = em.executeInTransaction(new TransactionalTask() { - @Override - public StringField execute(DatastoreTransaction transaction) { - // StringField entity = new StringField(); - StringField loadedEntity = transaction.load(StringField.class, insertedEntity.getId()); - loadedEntity.setName("Updated from runInTransaction"); - loadedEntity = transaction.update(loadedEntity); - return loadedEntity; - } - }); - assertTrue(updatedEntity.getName().equals("Updated from runInTransaction")); - } - - @Test(expected = EntityManagerException.class) - public void testRunInTransaction_Failure() { - final StringField entity = new StringField(); - entity.setId(3001); - entity.setName("Run in transaction test"); - final StringField insertedEntity = em.insert(entity); - em.executeInTransaction(new TransactionalTask() { - @Override - public Void execute(DatastoreTransaction transaction) { - for (int i = 3000; i < 3005; i++) { - StringField entity = new StringField(); - entity.setId(i); - transaction.insert(entity); - } - return null; - } - }); - } - - @Test - public void testInsert_IndexedString_MaxLimit() { - StringField entity = new StringField(); - final int length = 1500; - entity.setName(TestUtils.getRandomString(length)); - StringField insertedEntity = em.insert(entity); - StringField loadedEntity = em.load(StringField.class, insertedEntity.getId()); - assertEquals(length, insertedEntity.getName().length()); - assertEquals(length, loadedEntity.getName().length()); - } - - @Test(expected = EntityManagerException.class) - public void testInsert_IndexedString_MaxLimit_Exceeded() { - StringField entity = new StringField(); - final int length = 1501; - entity.setName(TestUtils.getRandomString(length)); - StringField insertedEntity = em.insert(entity); - } - - @Test - public void testInsert_UnIndexedString_5K() { - UnindexedStringField entity = new UnindexedStringField(); - final int length = 5 * 1024; - entity.setHugeString(TestUtils.getRandomString(length)); - UnindexedStringField insertedEntity = em.insert(entity); - UnindexedStringField loadedEntity = em.load(UnindexedStringField.class, insertedEntity.getId()); - assertEquals(length, insertedEntity.getHugeString().length()); - assertEquals(length, loadedEntity.getHugeString().length()); - } - - @Test - public void testInsertEmbedded_Imploded1() { - Contact contact = Contact.createContact1(); - Contact insertedContact = em.insert(contact); - Contact loadedContact = em.load(Contact.class, insertedContact.getId()); - assertTrue(contact.equalsExceptId(insertedContact)); - assertTrue(insertedContact.equals(loadedContact)); - } - - @Test - public void testInsertEmbedded_Imploded2() { - Contact contact = Contact.createContact2(); - Contact insertedContact = em.insert(contact); - Contact loadedContact = em.load(Contact.class, insertedContact.getId()); - assertTrue(contact.equalsExceptId(insertedContact)); - assertTrue(insertedContact.equals(loadedContact)); - } - - @Test - public void testUpdateEmbedded_Imploded1() { - Contact contact = Contact.createContact2(); - contact = em.insert(contact); - contact = em.load(Contact.class, contact.getId()); - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("1"); - phone.setAreaCode("111"); - phone.setSubscriberNumber("2223333"); - contact.setMobileNumber(phone); - em.update(contact); - contact = em.load(Contact.class, contact.getId()); - assertEquals("2223333", contact.getMobileNumber().getSubscriberNumber()); - } - - @Test - public void testInsert_BigDecimal() { - BigDecimalField entity = new BigDecimalField(new BigDecimal(23.654)); - entity = em.insert(entity); - BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); - assertTrue(entity.getId() != 0); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_BigDecimal_Null() { - BigDecimalField entity = new BigDecimalField(); - entity = em.insert(entity); - BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); - assertTrue(entity.getId() != 0); - assertTrue(entity.equals(entity2) && entity2.getValue() == null); - } - - @Test - public void testUpdate_BigDecimal() { - BigDecimalField entity = new BigDecimalField(new BigDecimal("500")); - entity = em.insert(entity); - entity.setValue(new BigDecimal(0)); - entity = em.update(entity); - BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); - assertTrue(entity.getId() != 0); - assertTrue(entity.equals(entity2) && entity2.getValue().compareTo(BigDecimal.ZERO) == 0); - } - - @Test - public void testUpdate_BigDecimal_Null() { - BigDecimalField entity = new BigDecimalField(new BigDecimal("5000")); - entity = em.insert(entity); - entity.setValue(null); - entity = em.update(entity); - BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); - assertTrue(entity.getId() != 0); - assertTrue(entity.equals(entity2) && entity2.getValue() == null); - } - - @Test - public void testInsert_Item() { - Item entity = new Item(); - entity.setName("Candy"); - entity.setPrice(new BigDecimal("1")); - entity.setDiscount(BigDecimal.ZERO); - entity = em.insert(entity); - Item entity2 = em.load(Item.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test(expected = MappingException.class) - public void testInsert_Item_PrecisionLoss() { - Item entity = new Item(); - entity.setName("Candy"); - entity.setPrice(new BigDecimal("1.699")); - entity = em.insert(entity); - Item entity2 = em.load(Item.class, entity.getId()); - assertTrue(entity.equals(entity2)); - } - - @Test - public void testInsert_DeviceType() { - Visitor entity = new Visitor(DeviceType.TABLET); - entity = em.insert(entity); - Visitor entity2 = em.load(Visitor.class, entity.getId()); - assertTrue(entity.equals(entity2)); - - } - - @Test - public void testInsert_AccessorTestEntity() { - AccessorTestEntity entity = AccessorTestEntity.getSample1(); - AccessorTestEntity entity2 = em.insert(entity); - AccessorTestEntity entity3 = em.load(AccessorTestEntity.class, entity2.getId()); - assertTrue(entity.equalsExceptId(entity2)); - assertEquals(entity2, entity3); - } - - @Test - public void testArrayIndex1() { - ParentEntity parentEntity = new ParentEntity(); - parentEntity.setField1("ArrayIndexTest"); - parentEntity = em.insert(parentEntity); - ArrayIndex entity = ArrayIndex.getSampleEntity(); - entity.setParentKey(parentEntity.getKey()); - entity = em.insert(entity); - String gql = "SELECT * FROM ArrayIndex WHERE stringList=@1 AND __key__ HAS ANCESTOR @2"; - EntityQueryRequest request = em.createEntityQueryRequest(gql); - request.addPositionalBinding("Two"); - request.addPositionalBinding(parentEntity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); - List results = response.getResults(); - assertEquals(1, results.size()); - } - - @Test - public void testArrayIndex2() { - ParentEntity parentEntity = new ParentEntity(); - parentEntity.setField1("ArrayIndexTest"); - parentEntity = em.insert(parentEntity); - ArrayIndex entity = ArrayIndex.getSampleEntity(); - entity.setParentKey(parentEntity.getKey()); - entity = em.insert(entity); - String gql = "SELECT * FROM ArrayIndex WHERE unindexedStringList=@1 AND __key__ HAS ANCESTOR @2"; - EntityQueryRequest request = em.createEntityQueryRequest(gql); - request.addPositionalBinding("Two"); - request.addPositionalBinding(parentEntity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); - List results = response.getResults(); - assertEquals(0, results.size()); - } - - @Test - public void testArrayIndex3() { - ParentEntity parentEntity = new ParentEntity(); - parentEntity.setField1("ArrayIndexTest"); - parentEntity = em.insert(parentEntity); - ArrayIndex entity = ArrayIndex.getSampleEntity(); - entity.setParentKey(parentEntity.getKey()); - entity = em.insert(entity); - String gql = "SELECT * FROM ArrayIndex WHERE stringSet=@1 AND __key__ HAS ANCESTOR @2"; - EntityQueryRequest request = em.createEntityQueryRequest(gql); - request.addPositionalBinding("Two"); - request.addPositionalBinding(parentEntity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); - List results = response.getResults(); - assertEquals(1, results.size()); - } - - @Test - public void testArrayIndex4() { - ParentEntity parentEntity = new ParentEntity(); - parentEntity.setField1("ArrayIndexTest"); - parentEntity = em.insert(parentEntity); - ArrayIndex entity = ArrayIndex.getSampleEntity(); - entity.setParentKey(parentEntity.getKey()); - entity = em.insert(entity); - String gql = "SELECT * FROM ArrayIndex WHERE unindexedStringSet=@1 AND __key__ HAS ANCESTOR @2"; - EntityQueryRequest request = em.createEntityQueryRequest(gql); - request.addPositionalBinding("Two"); - request.addPositionalBinding(parentEntity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); - List results = response.getResults(); - assertEquals(0, results.size()); - } - - @Test - public void testEntitySerializationWithKey() { - ParentEntity entity = new ParentEntity(); - entity.setField1("Serialization Test"); - entity = em.insert(entity); - ObjectOutputStream out = null; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - out = new ObjectOutputStream(bos); - out.writeObject(entity); - } catch (Exception exp) { - fail(exp.toString()); - } finally { - Utility.close(out); - } - ParentEntity entity2 = null; - ObjectInputStream in = null; - try { - in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); - entity2 = (ParentEntity) in.readObject(); - } catch (Exception exp) { - fail(exp.toString()); - } finally { - Utility.close(in); - } - assertEquals(entity, entity2); - } - - @Test - public void testInsertTimestamp_Calendar() { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Insert"); - AutoTimestampCalendar entity2 = em.insert(entity); - assertNotNull(entity2.getCreatedOn()); - assertNotNull(entity2.getModifiedOn()); - assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); - } - - @Test - public void testUpsertTimestamp_Calendar() { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Upsert"); - AutoTimestampCalendar entity2 = em.upsert(entity); - assertNull(entity2.getCreatedOn()); - assertNotNull(entity2.getModifiedOn()); - } - - @Test - public void testUpsertTimestamp_Calendar_2() { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Upsert with created date set on entity"); - entity.setCreatedOn(Calendar.getInstance()); - AutoTimestampCalendar entity2 = em.upsert(entity); - assertNotNull(entity2.getCreatedOn()); - assertNotNull(entity2.getModifiedOn()); - } - - @Test - public void testUpdateTimestamp_Calendar() { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Insert"); - AutoTimestampCalendar entity2 = em.insert(entity); - AutoTimestampCalendar entity3 = em.load(AutoTimestampCalendar.class, entity2.getId()); - entity3.setName("Update"); - AutoTimestampCalendar entity4 = em.update(entity3); - assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); - assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); - assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); - } - - @Test - public void testInsertTimestamp_Calendar_Multiple() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Insert " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - assertNotNull(entities2.get(0).getCreatedOn()); - assertNotNull(entities2.get(1).getCreatedOn()); - assertNotNull(entities2.get(0).getModifiedOn()); - assertNotNull(entities2.get(1).getModifiedOn()); - } - - @Test - public void testUpsertTimestamp_Calendar_Multiple() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Upsert " + i); - entities.add(entity); - } - List entities2 = em.upsert(entities); - assertNull(entities2.get(0).getCreatedOn()); - assertNull(entities2.get(1).getCreatedOn()); - assertNotNull(entities2.get(0).getModifiedOn()); - assertNotNull(entities2.get(1).getModifiedOn()); - } - - @Test - public void testUpdateTimestamp_Calendar_Multiple() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - AutoTimestampCalendar entity = new AutoTimestampCalendar(); - entity.setName("Insert Multiple " + i); - entities.add(entity); - } - List entities2 = em.insert(entities); - List keys = new ArrayList<>(entities2.size()); - for (int i = 0; i < entities2.size(); i++) { - keys.add(entities2.get(i).getId()); - } - List entities3 = em.loadById(AutoTimestampCalendar.class, keys); - for (int i = 0; i < entities3.size(); i++) { - entities3.get(i).setName("Update Multiple " + i); - keys.add(entities.get(i).getId()); - } - List entities4 = em.update(entities3); - - assertNotNull(entities4.get(0).getCreatedOn()); - assertNotNull(entities4.get(1).getCreatedOn()); - assertNotNull(entities4.get(0).getModifiedOn()); - assertNotNull(entities4.get(1).getModifiedOn()); - assertNotEquals(entities4.get(0).getCreatedOn(), entities4.get(0).getModifiedOn()); - assertNotEquals(entities4.get(1).getCreatedOn(), entities4.get(1).getModifiedOn()); - } - - @Test - public void testInsertTimestamp_Date() { - AutoTimestampDate entity = new AutoTimestampDate(); - entity.setName("Insert"); - AutoTimestampDate entity2 = em.insert(entity); - assertNotNull(entity2.getCreatedDate()); - assertNotNull(entity2.getModifiedDate()); - assertEquals(entity2.getCreatedDate(), entity2.getModifiedDate()); - } - - @Test - public void testUpsertTimestamp_Date() { - AutoTimestampDate entity = new AutoTimestampDate(); - entity.setName("Upsert"); - AutoTimestampDate entity2 = em.upsert(entity); - assertNull(entity2.getCreatedDate()); - assertNotNull(entity2.getModifiedDate()); - } - - @Test - public void testUpdateTimestamp_Date() { - AutoTimestampDate entity = new AutoTimestampDate(); - entity.setName("Insert"); - AutoTimestampDate entity2 = em.insert(entity); - AutoTimestampDate entity3 = em.load(AutoTimestampDate.class, entity2.getId()); - entity3.setName("Update"); - AutoTimestampDate entity4 = em.update(entity3); - assertEquals(entity2.getCreatedDate(), entity3.getCreatedDate()); - assertEquals(entity3.getCreatedDate(), entity4.getCreatedDate()); - assertNotEquals(entity3.getCreatedDate(), entity4.getModifiedDate()); - } - - @Test - public void testInsertTimestamp_Long() { - AutoTimestampLong entity = new AutoTimestampLong(); - entity.setName("Insert"); - AutoTimestampLong entity2 = em.insert(entity); - assertNotNull(entity2.getCreatedDate()); - assertNotNull(entity2.getModifiedDate()); - assertEquals(entity2.getCreatedDate(), entity2.getModifiedDate()); - } - - @Test - public void testUpsertTimestamp_Long() { - AutoTimestampLong entity = new AutoTimestampLong(); - entity.setName("Upsert"); - AutoTimestampLong entity2 = em.upsert(entity); - assertNull(entity2.getCreatedDate()); - assertNotNull(entity2.getModifiedDate()); - } - - @Test - public void testUpdateTimestamp_Long() { - AutoTimestampLong entity = new AutoTimestampLong(); - entity.setName("Insert"); - AutoTimestampLong entity2 = em.insert(entity); - AutoTimestampLong entity3 = em.load(AutoTimestampLong.class, entity2.getId()); - entity3.setName("Update"); - AutoTimestampLong entity4 = em.update(entity3); - assertEquals(entity2.getCreatedDate(), entity3.getCreatedDate()); - assertEquals(entity3.getCreatedDate(), entity4.getCreatedDate()); - assertNotEquals(entity3.getCreatedDate(), entity4.getModifiedDate()); - } - - @Test - public void testInsertTimestamp_OffsetDateTime() { - AutoTimestampOffsetDateTime entity = new AutoTimestampOffsetDateTime(); - entity.setName("Insert"); - AutoTimestampOffsetDateTime entity2 = em.insert(entity); - assertNotNull(entity2.getCreatedOn()); - assertNotNull(entity2.getModifiedOn()); - assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); - } - - @Test - public void testUpdateTimestamp_OffsetDateTime() { - AutoTimestampOffsetDateTime entity = new AutoTimestampOffsetDateTime(); - entity.setName("Insert"); - AutoTimestampOffsetDateTime entity2 = em.insert(entity); - AutoTimestampOffsetDateTime entity3 = em.load(AutoTimestampOffsetDateTime.class, entity2.getId()); - entity3.setName("Update"); - AutoTimestampOffsetDateTime entity4 = em.update(entity3); - assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); - assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); - assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); - } - - @Test - public void testInsertTimestamp_ZonedDateTime() { - AutoTimestampZonedDateTime entity = new AutoTimestampZonedDateTime(); - entity.setName("Insert"); - AutoTimestampZonedDateTime entity2 = em.insert(entity); - assertNotNull(entity2.getCreatedOn()); - assertNotNull(entity2.getModifiedOn()); - assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); - } - - @Test - public void testUpdateTimestamp_ZonedDateTime() { - AutoTimestampZonedDateTime entity = new AutoTimestampZonedDateTime(); - entity.setName("Insert"); - AutoTimestampZonedDateTime entity2 = em.insert(entity); - AutoTimestampZonedDateTime entity3 = em.load(AutoTimestampZonedDateTime.class, entity2.getId()); - entity3.setName("Update"); - AutoTimestampZonedDateTime entity4 = em.update(entity3); - assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); - assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); - assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); - } - - @Test(expected = EntityManagerException.class) - public void testInsertProjectedEntity() { - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe"); - em.insert(entity); - } - - @Test(expected = EntityManagerException.class) - public void testInsertProjectedEntity_List() { - List entities = new ArrayList<>(5); - for (int i = 0; i < 5; i++) { - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe " + i); - entities.add(entity); - } - entities = em.insert(entities); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateProjectedEntity() { - Contact contact = Contact.createContact1(); - contact = em.insert(contact); - ContactProjection entity = em.load(ContactProjection.class, contact.getId()); - entity.setLastName("Doe Updated"); - em.update(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpdateProjectedEntity_List() { - List contacts = new ArrayList<>(5); - List ids = new ArrayList<>(5); - for (int i = 0; i < 5; i++) { - contacts.add(Contact.createContact1()); - } - contacts = em.insert(contacts); - for (Contact contact : contacts) { - ids.add(contact.getId()); - } - - List entities = em.loadById(ContactProjection.class, ids); - em.update(entities); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertProjectedEntity() { - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe"); - em.upsert(entity); - } - - @Test(expected = EntityManagerException.class) - public void testUpsertProjectedEntity_List() { - List entities = new ArrayList<>(5); - for (int i = 0; i < 5; i++) { - ContactProjection entity = new ContactProjection(); - entity.setLastName("Doe " + i); - entities.add(entity); - } - entities = em.upsert(entities); - } - - @Test - public void testDeleteProjectedEntity() { - Contact entity = Contact.createContact1(); - entity = em.insert(entity); - ContactProjection projectedEntity = em.load(ContactProjection.class, entity.getId()); - em.delete(projectedEntity); - entity = em.load(Contact.class, entity.getId()); - assertNull(entity); - assertNotNull(projectedEntity); - } - - @Test - public void testDeleteProjectedEntity_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - entities.add(Contact.createContact1()); - } - entities = em.insert(entities); - List ids = new ArrayList<>(5); - for (Contact entity : entities) { - ids.add(entity.getId()); - } - List projectedEntities = em.loadById(ContactProjection.class, ids); - em.delete(projectedEntities); - entities = em.loadById(Contact.class, ids); - assertNull(entities.get(0)); - assertNull(entities.get(1)); - assertNull(entities.get(2)); - assertNull(entities.get(3)); - assertNull(entities.get(4)); - } - - @Test - public void testQueryByLocalDate_PositionalBinding() { - em.deleteAll(LocalDateField.class); - LocalDateField entity = new LocalDateField(); - LocalDate birthDate = LocalDate.of(2007, 1, 12); - entity.setBirthDate(birthDate); - entity = em.insert(entity); - String query = "SELECT * FROM LocalDateField WHERE birthDate=@1"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBindings(birthDate); - QueryResponse response = em.executeEntityQueryRequest(LocalDateField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByLocalDate_NamedBinding() { - em.deleteAll(LocalDateField.class); - LocalDateField entity = new LocalDateField(); - LocalDate birthDate = LocalDate.of(2007, 1, 12); - entity.setBirthDate(birthDate); - entity = em.insert(entity); - String query = "SELECT * FROM LocalDateField WHERE birthDate=@BirthDate"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.setNamedBinding("BirthDate", birthDate); - QueryResponse response = em.executeEntityQueryRequest(LocalDateField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByLocalTime_PositionalBinding() { - em.deleteAll(LocalTimeField.class); - LocalTimeField entity = new LocalTimeField(); - LocalTime time = LocalTime.of(0, 0, 0, 1); - entity.setStartTime(time); - entity = em.insert(entity); - String query = "SELECT * FROM LocalTimeField WHERE startTime=@1"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBindings(time); - QueryResponse response = em.executeEntityQueryRequest(LocalTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByLocalTime_NamedBinding() { - em.deleteAll(LocalTimeField.class); - LocalTimeField entity = new LocalTimeField(); - LocalTime time = LocalTime.of(0, 0, 0, 1); - entity.setStartTime(time); - entity = em.insert(entity); - String query = "SELECT * FROM LocalTimeField WHERE startTime=@Time"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.setNamedBinding("Time", time); - QueryResponse response = em.executeEntityQueryRequest(LocalTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByLocalDateTime_PositionalBinding() { - em.deleteAll(LocalDateTimeField.class); - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime timestamp = LocalDateTime.of(2007, 1, 12, 10, 30, 3, 456789); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM LocalDateTimeField WHERE timestamp=@1"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBindings(timestamp); - QueryResponse response = em.executeEntityQueryRequest(LocalDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByLocalDateTime_NamedBinding() { - em.deleteAll(LocalDateTimeField.class); - LocalDateTimeField entity = new LocalDateTimeField(); - LocalDateTime timestamp = LocalDateTime.of(1947, 8, 15, 0, 0, 0, 999999999); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM LocalDateTimeField WHERE timestamp=@ts"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.setNamedBinding("ts", timestamp); - QueryResponse response = em.executeEntityQueryRequest(LocalDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByOffsetDateTime_PositionalBinding() { - em.deleteAll(OffsetDateTimeField.class); - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime timestamp = OffsetDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, ZoneOffset.of("Z")); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM OffsetDateTimeField WHERE timestamp=@1"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBindings(timestamp); - QueryResponse response = em.executeEntityQueryRequest(OffsetDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByOffsetDateTime_NamedBinding() { - em.deleteAll(OffsetDateTimeField.class); - OffsetDateTimeField entity = new OffsetDateTimeField(); - OffsetDateTime timestamp = OffsetDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, ZoneOffset.of("Z")); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM OffsetDateTimeField WHERE timestamp=@Search"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.setNamedBinding("Search", timestamp); - QueryResponse response = em.executeEntityQueryRequest(OffsetDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByZonedDateTime_PositionalBinding() { - em.deleteAll(ZonedDateTimeField.class); - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime timestamp = ZonedDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, ZoneOffset.of("Z")); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM ZonedDateTimeField WHERE timestamp=@1"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBindings(timestamp); - QueryResponse response = em.executeEntityQueryRequest(ZonedDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - @Test - public void testQueryByZonedDateTime_NamedBinding() { - em.deleteAll(ZonedDateTimeField.class); - ZonedDateTimeField entity = new ZonedDateTimeField(); - ZonedDateTime timestamp = ZonedDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, ZoneOffset.of("Z")); - entity.setTimestamp(timestamp); - entity = em.insert(entity); - String query = "SELECT * FROM ZonedDateTimeField WHERE timestamp=@Timestamp"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.setNamedBinding("Timestamp", timestamp); - QueryResponse response = em.executeEntityQueryRequest(ZonedDateTimeField.class, request); - List entities = response.getResults(); - System.out.println(entities); - assertTrue(entities.size() == 1); - } - - // Test for a single entity - @Test - public void testAllocateId_1() { - StringField entity = new StringField(); - DatastoreKey key = em.allocateId(entity); - assertEquals(StringField.class.getSimpleName(), key.kind()); - assertTrue(key.id() > 0); - } - - // Test for single entity with a parent - @Test - public void testAllocateId_2() { - ParentEntity parentEntity = new ParentEntity(); - parentEntity.setField1("Test for allocate Id"); - parentEntity = em.insert(parentEntity); - ChildEntity childEntity = new ChildEntity(); - childEntity.setParentKey(parentEntity.getKey()); - DatastoreKey key = em.allocateId(childEntity); - assertEquals(ChildEntity.class.getSimpleName(), key.kind()); - assertEquals(key.parent(), parentEntity.getKey()); - assertTrue(key.id() > 0); - } - - // Test for multiple entities of different types - @Test - public void testAllocateId_3() { - StringField stringField = new StringField(); - LongField longField = new LongField(); - BooleanField booleanField = new BooleanField(); - User user = User.getSample1(); - List entities = new ArrayList<>(); - entities.add(stringField); - entities.add(longField); - entities.add(booleanField); - entities.add(user); - List keys = em.allocateId(entities); - assertEquals(StringField.class.getSimpleName(), keys.get(0).kind()); - assertTrue(keys.get(0).id() > 0); - assertEquals(LongField.class.getSimpleName(), keys.get(1).kind()); - assertTrue(keys.get(1).id() > 0); - assertEquals(BooleanField.class.getSimpleName(), keys.get(2).kind()); - assertTrue(keys.get(2).id() > 0); - assertEquals(User.class.getSimpleName(), keys.get(3).kind()); - assertTrue(keys.get(3).id() > 0); - } - - // Test with a String ID - @Test(expected = IllegalArgumentException.class) - public void testAllocateId_4() { - StringId entity = new StringId(); - DatastoreKey key = em.allocateId(entity); - } - - // Test with a non-zero ID - @Test(expected = IllegalArgumentException.class) - public void testAllocateId_5() { - StringField entity = new StringField(); - entity.setId(12345); - DatastoreKey key = em.allocateId(entity); - } - - // Test with a non-null ID - @Test(expected = IllegalArgumentException.class) - public void testAllocateId_6() { - LongObjectId entity = new LongObjectId(); - entity.setId(12345L); - DatastoreKey key = em.allocateId(entity); - } - - // Test with a non-null, but zero ID - @Test - public void testAllocateId_7() { - LongObjectId entity = new LongObjectId(); - entity.setId(0L); - DatastoreKey key = em.allocateId(entity); - assertEquals(LongObjectId.class.getSimpleName(), key.kind()); - assertTrue(key.id() > 0); - } - - @Test - public void testInsert_WrappedLongIdEntity() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample1(); - WrappedLongIdEntity entity2 = em.insert(entity); - assertTrue(entity2.getId().getValue() > 0); - } - - @Test - public void testUpsert_WrappedLongIdEntity() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample2(); - WrappedLongIdEntity entity2 = em.upsert(entity); - assertTrue(entity2.getId().getValue() > 0); - } - - @Test - public void testUpdate_WrappedLongIdEntity() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); - WrappedLongIdEntity entity2 = em.insert(entity); - assertTrue(entity2.getId().getValue() > 0); - entity2.setName(entity2.getName() + " - updated"); - WrappedLongIdEntity entity3 = em.update(entity2); - WrappedLongIdEntity entity4 = em.load(WrappedLongIdEntity.class, entity2.getId().getValue()); - assertEquals(entity3, entity4); - } - - @Test - public void testInsert_WrappedLongObjectIdEntity() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample1(); - WrappedLongObjectIdEntity entity2 = em.insert(entity); - assertTrue(entity2.getId().getValue() > 0); - } - - @Test - public void testUpsert_WrappedLongObjectIdEntity() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample2(); - WrappedLongObjectIdEntity entity2 = em.upsert(entity); - assertTrue(entity2.getId().getValue() > 0); - } - - @Test - public void testUpdate_WrappedLongObjectIdEntity() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample3(); - WrappedLongObjectIdEntity entity2 = em.upsert(entity); - assertTrue(entity2.getId().getValue() > 0); - entity2.setName(entity2.getName() + " - updated"); - WrappedLongObjectIdEntity entity3 = em.update(entity2); - WrappedLongObjectIdEntity entity4 = em.load(WrappedLongObjectIdEntity.class, entity3.getId().getValue()); - assertEquals(entity3, entity4); - } - - @Test - public void testInsert_User() { - User entity = User.getSample1(); - User entity2 = em.insert(entity); - assertTrue(entity2.getId().getValue() > 0); - assertEquals(entity.getName(), entity.getName()); - } - - @Test - public void testUpsert_User() { - User entity = User.getSample2(); - User entity2 = em.insert(entity); - assertEquals(0, entity.getId().getValue()); - assertTrue(entity2.getId().getValue() > 0); - assertEquals(entity.getName(), entity.getName()); - } - - @Test - public void testInsertUserContact() { - User user = User.getSample2(); - User user2 = em.insert(user); - UserContact uc = new UserContact(); - uc.setUserKey(user2.getKey()); - uc.setContactName("John Doe"); - UserContact uc2 = em.insert(uc); - assertTrue(uc2.getId() > 0); - assertEquals(uc2.getUserKey(), user2.getKey()); - } - - @Test - public void testLoad_ByKey() { - ParentEntity entity = new ParentEntity(); - entity.setField1("test for load by key"); - entity = em.insert(entity); - ParentEntity entity2 = em.load(ParentEntity.class, entity.getKey()); - assertEquals(entity, entity2); - } - - @Test - public void testLoad_ByKeys() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ParentEntity entity = new ParentEntity(); - entity.setField1("test for load by key " + i); - entities.add(entity); - } - entities = em.insert(entities); - List keys = new ArrayList<>(entities.size()); - for (ParentEntity entity : entities) { - keys.add(entity.getKey()); - } - List loadedEntities = em.loadByKey(ParentEntity.class, keys); - assertEquals(entities, loadedEntities); - } - - @Test - public void testInsert_NestedMapEntity() { - NestedMapEntity entity = NestedMapEntity.getSample1(); - NestedMapEntity entity2 = em.insert(entity); - NestedMapEntity entity3 = em.load(NestedMapEntity.class, entity2.getId()); - assertEquals(entity.getNestedMap(), entity2.getNestedMap()); - assertEquals(entity2, entity3); - } - - @Test - public void testUpdate_NestedMapEntity() { - NestedMapEntity entity = NestedMapEntity.getSample1(); - NestedMapEntity entity2 = em.insert(entity); - NestedMapEntity entity3 = em.load(NestedMapEntity.class, entity2.getId()); - assertEquals(entity.getNestedMap(), entity2.getNestedMap()); - assertEquals(entity2, entity3); - entity3.getNestedMap().put("double", 1.0); - NestedMapEntity entity4 = em.update(entity3); - NestedMapEntity entity5 = em.load(NestedMapEntity.class, entity4.getId()); - assertEquals(entity3, entity4); - assertEquals(entity4, entity5); - } - - @Test - public void testInsert_ImmutablePerson() { - ImmutablePerson entity = ImmutablePerson.getSample1(); - ImmutablePerson entity2 = em.insert(entity); - ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); - assertTrue(entity.equalsExceptAutoGeneratedFields(entity2)); - assertEquals(entity2, entity3); - - // Checks listeners - assertTrue(entity.isPreInsertFired()); - assertFalse(entity.isPostInsertFired()); - assertFalse(entity.isPostLoadFired()); - - assertTrue(entity2.isPostInsertFired()); - assertFalse(entity2.isPreInsertFired()); - assertFalse(entity2.isPostLoadFired()); - - assertTrue(entity3.isPostLoadFired()); - assertFalse(entity3.isPreInsertFired()); - assertFalse(entity3.isPostInsertFired()); - - } - - @Test - public void testInsert_ImmutablePerson_AllNulls() { - ImmutablePerson entity = ImmutablePerson.getSample2(); - ImmutablePerson entity2 = em.insert(entity); - ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); - // assertTrue(entity.equalsExceptId(entity2)); - assertEquals(entity2, entity3); - - } - - @Test - public void testInsert_ImmutableSubClass() { - ImmutableSubClass entity = ImmutableSubClass.newBuilder().setName("Immutable SubClass").build(); - ImmutableSubClass entity2 = em.insert(entity); - ImmutableSubClass entity3 = em.load(ImmutableSubClass.class, entity2.getId()); - assertTrue(entity.equalsExceptGeneratedValues(entity2)); - assertEquals(entity2, entity3); - } - - @Test - public void testUpdate_ImmutableSubClass() { - ImmutableSubClass entity = ImmutableSubClass.newBuilder().setName("Immutable SubClass for Update").build(); - ImmutableSubClass entity2 = em.insert(entity); - ImmutableSubClass entity3 = em.update(entity2); - ImmutableSubClass entity4 = em.load(ImmutableSubClass.class, entity2.getId()); - assertTrue(entity.equalsExceptGeneratedValues(entity2)); - assertEquals(0L, entity2.getVersion()); - assertEquals(1L, entity3.getVersion()); - assertEquals(entity3, entity4); - } - - @Test - public void testDelete_ImmutableSubClass() { - ImmutableSubClass entity = ImmutableSubClass.newBuilder().setName("Immutable SubClass for Delete").build(); - ImmutableSubClass entity2 = em.insert(entity); - ImmutableSubClass entity3 = em.load(ImmutableSubClass.class, entity2.getId()); - em.delete(entity3); - ImmutableSubClass entity4 = em.load(ImmutableSubClass.class, entity3.getId()); - assertNull(entity4); - } - - @Test(expected = EntityAlreadyExistsException.class) - public void testDuplicateKey() { - StringField entity = new StringField(); - entity.setName("Dup Test"); - entity = em.insert(entity); - try { - entity = em.insert(entity); - } catch (EntityAlreadyExistsException exp) { - throw exp; - } catch (EntityManagerException exp) { - String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); - if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { - // Running on emulator that has a bug. - throw new EntityAlreadyExistsException(exp); - } - } - } - - private static Calendar getToday() { - Calendar today = Calendar.getInstance(); - today.set(Calendar.HOUR_OF_DAY, 0); - today.set(Calendar.MINUTE, 0); - today.set(Calendar.SECOND, 0); - today.set(Calendar.MILLISECOND, 0); - return today; - } + private static EntityManager em; + private static Random random = new Random(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + // Register a custom mapper + MapperFactory.getInstance().setDefaultMapper(DeviceType.class, new DeviceTypeMapper()); + em = TestUtils.getEntityManager(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test(expected = IllegalArgumentException.class) + public void testDeleteAll_Null() { + em.deleteAll((String) null); + } + + @Test(expected = IllegalArgumentException.class) + public void testDeleteAll_Blank() { + em.deleteAll(" "); + } + + @Test + public void testInsertLongId_AutoGenerated() { + LongId entity = new LongId(); + entity.setField1("Hello World!"); + entity = em.insert(entity); + assertNotEquals(0, entity.getId()); + } + + @Test + public void testInsertLongId_Preset() { + LongId entity = new LongId(); + long id = random.nextLong(); + entity.setId(id); + entity.setField1("Hello World!"); + entity = em.insert(entity); + assertEquals(id, entity.getId()); + } + + @Test(expected = EntityManagerException.class) + public void testInsertLongId2() { + try { + LongId2 entity = new LongId2(); + entity.setField1("Hello World!"); + entity = em.insert(entity); + } catch (EntityManagerException exp) { + exp.printStackTrace(); + throw exp; + } + } + + @Test + public void testInsertStringId_AutoGenerated() { + StringId entity = new StringId(); + entity.setGreetings("Good Morning!"); + entity = em.insert(entity); + assertNotNull(entity.getId()); + } + + @Test + public void testInsertStringId_Preset() { + StringId entity = new StringId(); + String id = "greeting1"; + entity.setId(id); + entity.setGreetings("Good Morning!"); + entity = em.insert(entity); + assertEquals(id, entity.getId()); + } + + @Test(expected = EntityManagerException.class) + public void testInsertStringId2() { + StringId2 entity = new StringId2(); + entity = em.insert(entity); + } + + @Test + public void testInsertBooleanField_True() { + BooleanField entity = new BooleanField(); + entity.setAwesome(true); + entity = em.insert(entity); + assertTrue(entity.getId() > 0L && entity.isAwesome()); + } + + @Test + public void testInsertBooleanField_False() { + BooleanField entity = new BooleanField(); + entity.setAwesome(false); + entity = em.insert(entity); + assertTrue(entity.getId() > 0L && !entity.isAwesome()); + } + + @Test + public void testInsertBooleanObject_True() { + BooleanObject entity = new BooleanObject(); + entity.setAwesome(true); + entity = em.insert(entity); + assertTrue(entity.getId() > 0L && Boolean.TRUE.equals(entity.getAwesome())); + } + + @Test + public void testInsertBooleanObject_False() { + BooleanObject entity = new BooleanObject(); + entity.setAwesome(false); + entity = em.insert(entity); + assertTrue(entity.getId() > 0L && Boolean.FALSE.equals(entity.getAwesome())); + } + + @Test + public void testInsertBooleanObject_Null() { + BooleanObject entity = new BooleanObject(); + entity = em.insert(entity); + assertTrue(entity.getId() > 0L && entity.getAwesome() == null); + } + + @Test + public void testInsertCharField() { + CharField entity = new CharField(); + entity.setSex('M'); + entity = em.insert(entity); + entity = em.load(CharField.class, entity.getId()); + assertTrue(entity.getId() > 0L && entity.getSex() == 'M'); + } + + @Test + public void testInsertCharObject() { + CharObject entity = new CharObject(); + entity.setSex('F'); + entity = em.insert(entity); + entity = em.load(CharObject.class, entity.getId()); + assertTrue(entity.getId() > 0L && entity.getSex() == 'F'); + } + + @Test + public void testInsertCharObject_Null() { + CharObject entity = new CharObject(); + entity = em.insert(entity); + entity = em.load(CharObject.class, entity.getId()); + assertTrue(entity.getId() > 0L && entity.getSex() == null); + } + + @Test + public void testInsertShortField() { + ShortField entity = new ShortField(); + entity.setAge((short) 25); + entity = em.insert(entity); + entity = em.load(ShortField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getAge() == 25); + } + + @Test + public void testInsertShortObject() { + ShortObject entity = new ShortObject(); + entity.setAge(new Short((short) 25)); + entity = em.insert(entity); + entity = em.load(ShortObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getAge() == 25); + } + + @Test + public void testInsertShortObject_Null() { + ShortObject entity = new ShortObject(); + entity = em.insert(entity); + entity = em.load(ShortObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getAge() == null); + } + + @Test + public void testInsertIntegerField() { + IntegerField entity = new IntegerField(); + entity.setCount(3456789); + entity = em.insert(entity); + entity = em.load(IntegerField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCount() == 3456789); + } + + @Test + public void testInsertIntegerField_Negative_Value() { + IntegerField entity = new IntegerField(); + entity.setCount(-3456789); + entity = em.insert(entity); + entity = em.load(IntegerField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCount() == -3456789); + } + + @Test + public void testInsertIntegerObject() { + IntegerObject entity = new IntegerObject(); + entity.setCount(new Integer(3456789)); + entity = em.insert(entity); + entity = em.load(IntegerObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCount() == 3456789); + } + + @Test + public void testInsertIntegerObject_Null() { + IntegerObject entity = new IntegerObject(); + entity = em.insert(entity); + entity = em.load(IntegerObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCount() == null); + } + + @Test + public void testInsertLongField() { + LongField entity = new LongField(); + entity.setDistanceFromEarth(2400000000000000L); + entity = em.insert(entity); + entity = em.load(LongField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == 2400000000000000L); + } + + @Test + public void testInsertLongObject() { + LongObject entity = new LongObject(); + entity.setDistanceFromEarth(2400000000000000L); + entity = em.insert(entity); + entity = em.load(LongObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == 2400000000000000L); + } + + @Test + public void testInsertLongObject_Null() { + LongObject entity = new LongObject(); + entity = em.insert(entity); + entity = em.load(LongObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getDistanceFromEarth() == null); + } + + @Test + public void testInsertFloatField() { + FloatField entity = new FloatField(); + entity.setArea(Float.MAX_VALUE); + entity = em.insert(entity); + entity = em.load(FloatField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == Float.MAX_VALUE); + } + + @Test + public void testInsertFloatField_Negative() { + FloatField entity = new FloatField(); + entity.setArea(-Float.MIN_VALUE); + entity = em.insert(entity); + entity = em.load(FloatField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == -Float.MIN_VALUE); + } + + @Test + public void testInsertFloatField_PI() { + FloatField entity = new FloatField(); + entity.setArea(3.1415927f); + entity = em.insert(entity); + entity = em.load(FloatField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == 3.1415927f); + } + + @Test + public void testInsertFloatObject() { + FloatObject entity = new FloatObject(); + entity.setArea(Float.valueOf(Float.MAX_VALUE)); + entity = em.insert(entity); + entity = em.load(FloatObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == Float.MAX_VALUE); + } + + @Test + public void testInsertFloatObject_Negative() { + FloatObject entity = new FloatObject(); + entity.setArea(Float.valueOf(-Float.MIN_VALUE)); + entity = em.insert(entity); + entity = em.load(FloatObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == -Float.MIN_VALUE); + } + + @Test + public void testInsertFloatObject_Null() { + FloatObject entity = new FloatObject(); + entity = em.insert(entity); + entity = em.load(FloatObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == null); + } + + @Test + public void testInsertDoubleField() { + DoubleField entity = new DoubleField(); + entity.setArea(Double.MAX_VALUE); + entity = em.insert(entity); + entity = em.load(DoubleField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == Double.MAX_VALUE); + } + + @Test + public void testInsertDoubleField_Negative() { + DoubleField entity = new DoubleField(); + entity.setArea(-Double.MIN_VALUE); + entity = em.insert(entity); + entity = em.load(DoubleField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == -Double.MIN_VALUE); + } + + @Test + public void testInsertDoubleObject() { + DoubleObject entity = new DoubleObject(); + entity.setArea(Double.MAX_VALUE); + entity = em.insert(entity); + entity = em.load(DoubleObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == Double.MAX_VALUE); + } + + @Test + public void testInsertDoubleObject_Negative() { + DoubleObject entity = new DoubleObject(); + entity.setArea(-Double.MIN_VALUE); + entity = em.insert(entity); + entity = em.load(DoubleObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == -Double.MIN_VALUE); + } + + @Test + public void testInsertDoubleObject_Null() { + DoubleObject entity = new DoubleObject(); + entity = em.insert(entity); + entity = em.load(DoubleObject.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getArea() == null); + } + + @Test + public void testInsertStringField() { + StringField entity = new StringField(); + String name = "Google Cloud Datastore"; + entity.setName(name); + entity = em.insert(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getName().equals(name)); + } + + @Test + public void testInsertStringField_Blank() { + StringField entity = new StringField(); + String name = ""; + entity.setName(name); + entity = em.insert(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getName().equals(name)); + } + + @Test + public void testInsertStringField_Spaces() { + StringField entity = new StringField(); + String name = " "; + entity.setName(name); + entity = em.insert(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getName().equals(name)); + } + + @Test + public void testInsertStringField_Null() { + StringField entity = new StringField(); + entity = em.insert(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getName() == null); + } + + @Test + public void testInsertCalendarField() { + CalendarField entity = new CalendarField(); + Calendar now = Calendar.getInstance(); + entity.setCreationDate(now); + entity = em.insert(entity); + entity = em.load(CalendarField.class, entity.getId()); + assertTrue( + entity.getId() > 0 && entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); + } + + @Test + public void testInsertCalendarField_GMT() { + CalendarField entity = new CalendarField(); + Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + entity.setCreationDate(now); + entity = em.insert(entity); + entity = em.load(CalendarField.class, entity.getId()); + assertTrue( + entity.getId() > 0 && entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); + } + + @Test + public void testInsertCalendarField_Null() { + CalendarField entity = new CalendarField(); + // Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + // entity.setCreationDate(now); + entity = em.insert(entity); + entity = em.load(CalendarField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCreationDate() == null); + } + + @Test + public void testInsertDateField() { + DateField entity = new DateField(); + Date now = new Date(); + entity.setCreationDate(now); + entity = em.insert(entity); + entity = em.load(DateField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCreationDate().getTime() == now.getTime()); + } + + @Test + public void testInsertDateField_Future() { + DateField entity = new DateField(); + long currentTime = System.currentTimeMillis(); + long hundredYearsFromNow = currentTime + 100L * 366L * 24L * 60L * 60L * 1000L; + Date date = new Date(hundredYearsFromNow); + entity.setCreationDate(date); + entity = em.insert(entity); + entity = em.load(DateField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCreationDate().getTime() == date.getTime()); + } + + @Test + public void testInsertDateField_Null() { + DateField entity = new DateField(); + entity = em.insert(entity); + entity = em.load(DateField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getCreationDate() == null); + } + + @Test + public void testInsertLocalDateField() { + LocalDateField entity = new LocalDateField(); + LocalDate now = LocalDate.now(); + entity.setBirthDate(now); + entity = em.insert(entity); + entity = em.load(LocalDateField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getBirthDate().equals(now)); + } + + @Test + public void testInsertLocalDateField_Null() { + LocalDateField entity = new LocalDateField(); + entity = em.insert(entity); + entity = em.load(LocalDateField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getBirthDate() == null); + } + + @Test + public void testInsertLocalTimeField_Now() { + LocalTimeField entity = new LocalTimeField(); + LocalTime now = LocalTime.now(); + entity.setStartTime(now); + entity = em.insert(entity); + entity = em.load(LocalTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getStartTime().equals(now)); + } + + @Test + public void testInsertLocalTimeField_Null() { + LocalTimeField entity = new LocalTimeField(); + entity = em.insert(entity); + entity = em.load(LocalTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getStartTime() == null); + } + + @Test + public void testInsertLocalDateTimeField_Now() { + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime now = LocalDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity = em.load(LocalDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); + } + + @Test + public void testInsertLocalDateTimeField_Null() { + LocalDateTimeField entity = new LocalDateTimeField(); + entity = em.insert(entity); + entity = em.load(LocalDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); + } + + @Test + public void testInsertOffsetDateTimeField_Now() { + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime now = OffsetDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity = em.load(OffsetDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); + } + + @Test + public void testInsertOffsetDateTimeField_Null() { + OffsetDateTimeField entity = new OffsetDateTimeField(); + entity.setTimestamp(null); + entity = em.insert(entity); + entity = em.load(OffsetDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); + } + + @Test + public void testInsertOffsetDateTimeField_Nano() { + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime now = OffsetDateTime.now().withNano(999999999); + entity.setTimestamp(now); + OffsetDateTimeField entity2 = em.insert(entity); + // Here we lose the nano precision and only have micros + OffsetDateTimeField entity3 = em.load(OffsetDateTimeField.class, entity2.getId()); + assertEquals(entity2.getTimestamp(), entity3.getTimestamp()); + assertEquals(entity.getTimestamp().toEpochSecond(), entity3.getTimestamp().toEpochSecond()); + assertEquals(TimeUnit.NANOSECONDS.toMicros(entity.getTimestamp().getNano()), + TimeUnit.NANOSECONDS.toMicros(entity3.getTimestamp().getNano())); + } + + @Test + public void testInsertZonedDateTimeField_Now() { + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime now = ZonedDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity = em.load(ZonedDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp().equals(now)); + } + + @Test + public void testInsertZonedDateTimeField_Null() { + ZonedDateTimeField entity = new ZonedDateTimeField(); + entity = em.insert(entity); + entity = em.load(ZonedDateTimeField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getTimestamp() == null); + } + + @Test + public void testInsertZonedDateTimeField_Nano() { + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime now = ZonedDateTime.now().withNano(999999999); + entity.setTimestamp(now); + ZonedDateTimeField entity2 = em.insert(entity); + // Here we lose the nano precision and only have micros + ZonedDateTimeField entity3 = em.load(ZonedDateTimeField.class, entity2.getId()); + assertEquals(entity2.getTimestamp(), entity3.getTimestamp()); + assertEquals(entity.getTimestamp().toEpochSecond(), entity3.getTimestamp().toEpochSecond()); + assertEquals(TimeUnit.NANOSECONDS.toMicros(entity.getTimestamp().getNano()), + TimeUnit.NANOSECONDS.toMicros(entity3.getTimestamp().getNano())); + } + + @Test + public void testInsertByteArrayField() { + byte[] salt = new byte[16]; + random.nextBytes(salt); + ByteArrayField entity = new ByteArrayField(); + entity.setSalt(salt); + entity = em.insert(entity); + entity = em.load(ByteArrayField.class, entity.getId()); + assertTrue(entity.getId() > 0 && Arrays.equals(entity.getSalt(), salt)); + } + + @Test + public void testInsertByteArrayField_Null() { + ByteArrayField entity = new ByteArrayField(); + entity = em.insert(entity); + entity = em.load(ByteArrayField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getSalt() == null); + } + + @Test + public void testInsertCharArrayField() { + CharArrayField entity = new CharArrayField(); + char[] password = "secret".toCharArray(); + entity.setPassword(password); + entity = em.insert(entity); + entity = em.load(CharArrayField.class, entity.getId()); + assertTrue(entity.getId() > 0 && Arrays.equals(password, entity.getPassword())); + } + + @Test + public void testInsertCharArrayField_Blank() { + CharArrayField entity = new CharArrayField(); + char[] password = "".toCharArray(); + entity.setPassword(password); + entity = em.insert(entity); + entity = em.load(CharArrayField.class, entity.getId()); + assertTrue(entity.getId() > 0 && Arrays.equals(password, entity.getPassword())); + } + + @Test + public void testInsertCharArrayField_Null() { + CharArrayField entity = new CharArrayField(); + entity = em.insert(entity); + entity = em.load(CharArrayField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getPassword() == null); + } + + @Test + public void testInsertEnumField() { + EnumField entity = new EnumField(); + entity.setSize(EnumField.Size.LARGE); + entity = em.insert(entity); + entity = em.load(EnumField.class, entity.getId()); + assertEquals(EnumField.Size.LARGE, entity.getSize()); + } + + @Test + public void testInsertEnumField_Null() { + EnumField entity = new EnumField(); + entity = em.insert(entity); + entity = em.load(EnumField.class, entity.getId()); + assertNull(entity.getSize()); + } + + @Test + public void testUpdateEnumField() { + EnumField entity = new EnumField(); + entity.setSize(EnumField.Size.LARGE); + entity = em.insert(entity); + entity.setSize(EnumField.Size.SMALL); + entity = em.update(entity); + entity = em.load(EnumField.class, entity.getId()); + assertEquals(EnumField.Size.SMALL, entity.getSize()); + } + + @Test + public void testUpdateEnumField_Null() { + EnumField entity = new EnumField(); + entity.setSize(EnumField.Size.LARGE); + entity = em.insert(entity); + entity.setSize(null); + entity = em.update(entity); + entity = em.load(EnumField.class, entity.getId()); + assertNull(entity.getSize()); + } + + @Test + public void testInsertKeyReference() { + Department department = new Department(); + department.setName("Sales"); + department = em.insert(department); + + Country country = new Country(); + country.setName("United States"); + country = em.insert(country); + + Employee employee = new Employee(); + employee.setName("Sai Pullabhotla"); + employee.setDepartment(department.getFullKey()); + employee.setCountry(country.getKey()); + employee = em.insert(employee); + assertTrue(employee.getId() > 0 && employee.getDepartment().equals(department.getFullKey())); + } + + @Test + public void testInsertParentChild() { + ParentEntity parent = new ParentEntity(); + parent.setField1("I'm parent!"); + parent = em.insert(parent); + + ChildEntity child = new ChildEntity(); + child.setField1("I'm child!"); + child.setParentKey(parent.getKey()); + child = em.insert(child); + + GrandchildEntity grandchild = new GrandchildEntity(); + grandchild.setField1("I'm grangchild"); + grandchild.setParentKey(child.getKey()); + grandchild = em.insert(grandchild); + + assertTrue(child.getParentKey().equals(parent.getKey()) + && grandchild.getParentKey().equals(child.getKey())); + } + + @Test + public void testInsert_GeoLocationField() { + GeoLocationField ny = GeoLocationField.NEW_YORK_CITY; + ny = em.insert(ny); + GeoLocationField entity = em.load(GeoLocationField.class, ny.getId()); + assertTrue(entity.getId() != 0 && entity.getCity().equals(ny.getCity()) + && entity.getCoordinates().equals(ny.getCoordinates())); + } + + @Test + public void testInsert_GeoLocationField_Null() { + GeoLocationField entity = new GeoLocationField(); + entity.setCity("NULL CITY"); + entity = em.insert(entity); + entity = em.load(GeoLocationField.class, entity.getId()); + assertNull(entity.getCoordinates()); + } + + @Test + public void testInsert_IgnoredField() { + IgnoreField entity = new IgnoreField(); + entity.setName("John Doe"); + entity.setComputed("This should not be persisted"); + entity = em.insert(entity); + entity = em.load(IgnoreField.class, entity.getId()); + assertTrue( + entity.getId() > 0 && entity.getName().equals("John Doe") && entity.getComputed() == null); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateLongId_AutoGenerateTrue() { + LongId entity = new LongId(); + entity.setField1("Update entity that does not exist"); + em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateLongId_AutoGenerateFalse() { + LongId2 entity = new LongId2(); + entity.setField1("Update entity that does not exist"); + em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateStringId_AutoGenerateTrue() { + StringId entity = new StringId(); + entity.setGreetings("Update entity that does not exist"); + em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateStringId_AutoGenerateFalse() { + StringId2 entity = new StringId2(); + entity.setGreetings("Update entity that does not exist"); + em.update(entity); + } + + @Test + public void testUpdateBooleanField() { + BooleanField entity = new BooleanField(); + entity.setAwesome(false); + entity = em.insert(entity); + entity.setAwesome(true); + entity = em.update(entity); + entity = em.load(BooleanField.class, entity.getId()); + assertTrue(entity.isAwesome()); + } + + @Test + public void testUpdateBooleanObject() { + BooleanObject entity = new BooleanObject(); + entity.setAwesome(Boolean.TRUE); + entity = em.insert(entity); + entity.setAwesome(Boolean.FALSE); + entity = em.update(entity); + entity = em.load(BooleanObject.class, entity.getId()); + assertTrue(!entity.getAwesome()); + } + + @Test + public void testUpdateBooleanObject_Null() { + BooleanObject entity = new BooleanObject(); + entity.setAwesome(Boolean.TRUE); + entity = em.insert(entity); + entity.setAwesome(null); + entity = em.update(entity); + entity = em.load(BooleanObject.class, entity.getId()); + assertTrue(entity.getAwesome() == null); + } + + @Test + public void testUpdateCharField() { + CharField entity = new CharField(); + entity.setSex('M'); + entity = em.insert(entity); + entity.setSex('F'); + entity = em.update(entity); + entity = em.load(CharField.class, entity.getId()); + assertTrue(entity.getSex() == 'F'); + } + + @Test + public void testUpdateCharObject() { + CharObject entity = new CharObject(); + entity.setSex('M'); + entity = em.insert(entity); + entity.setSex('F'); + entity = em.update(entity); + entity = em.load(CharObject.class, entity.getId()); + assertTrue(entity.getSex() == 'F'); + } + + @Test + public void testUpdateCharObject_Null() { + CharObject entity = new CharObject(); + entity.setSex('M'); + entity = em.insert(entity); + entity.setSex(null); + entity = em.update(entity); + entity = em.load(CharObject.class, entity.getId()); + assertTrue(entity.getSex() == null); + } + + @Test + public void testUpdateShortField() { + ShortField entity = new ShortField(); + entity.setAge((short) 13); + entity = em.insert(entity); + entity.setAge((short) 30); + entity = em.update(entity); + entity = em.load(ShortField.class, entity.getId()); + assertTrue(entity.getAge() == 30); + } + + @Test + public void testUpdateShortObject() { + ShortObject entity = new ShortObject(); + entity.setAge((short) 13); + entity = em.insert(entity); + entity.setAge((short) 30); + entity = em.update(entity); + entity = em.load(ShortObject.class, entity.getId()); + assertTrue(entity.getAge() == 30); + } + + @Test + public void testUpdateShortObject_Null() { + ShortObject entity = new ShortObject(); + entity.setAge((short) 13); + entity = em.insert(entity); + entity.setAge(null); + entity = em.update(entity); + entity = em.load(ShortObject.class, entity.getId()); + assertTrue(entity.getAge() == null); + } + + @Test + public void testUpdateIntegerField() { + IntegerField entity = new IntegerField(); + entity.setCount(9876543); + entity = em.insert(entity); + entity.setCount(3456789); + entity = em.update(entity); + entity = em.load(IntegerField.class, entity.getId()); + assertTrue(entity.getCount() == 3456789); + } + + @Test + public void testUpdateIntegerObject() { + IntegerObject entity = new IntegerObject(); + entity.setCount(9876543); + entity = em.insert(entity); + entity.setCount(3456789); + entity = em.update(entity); + entity = em.load(IntegerObject.class, entity.getId()); + assertTrue(entity.getCount() == 3456789); + } + + @Test + public void testUpdateIntegerObject_Null() { + IntegerObject entity = new IntegerObject(); + entity.setCount(9876543); + entity = em.insert(entity); + entity.setCount(null); + entity = em.update(entity); + entity = em.load(IntegerObject.class, entity.getId()); + assertTrue(entity.getCount() == null); + } + + @Test + public void testUpdateLongField() { + LongField entity = new LongField(); + entity.setDistanceFromEarth(9876543210L); + entity = em.insert(entity); + entity.setDistanceFromEarth(987654321098765L); + entity = em.update(entity); + entity = em.load(LongField.class, entity.getId()); + assertTrue(entity.getDistanceFromEarth() == 987654321098765L); + } + + @Test + public void testUpdateLongObject() { + LongObject entity = new LongObject(); + entity.setDistanceFromEarth(9876543210L); + entity = em.insert(entity); + entity.setDistanceFromEarth(987654321098765L); + entity = em.update(entity); + entity = em.load(LongObject.class, entity.getId()); + assertTrue(entity.getDistanceFromEarth() == 987654321098765L); + } + + @Test + public void testUpdateLongObject_Null() { + LongObject entity = new LongObject(); + entity.setDistanceFromEarth(9876543210L); + entity = em.insert(entity); + entity.setDistanceFromEarth(null); + entity = em.update(entity); + entity = em.load(LongObject.class, entity.getId()); + assertTrue(entity.getDistanceFromEarth() == null); + } + + @Test + public void testUpdateFloatField() { + FloatField entity = new FloatField(); + entity.setArea(322.456f); + entity = em.insert(entity); + entity.setArea(456.322f); + entity = em.update(entity); + entity = em.load(FloatField.class, entity.getId()); + assertTrue(entity.getArea() == 456.322f); + } + + @Test + public void testUpdateFloatObject() { + FloatObject entity = new FloatObject(); + entity.setArea(322.456f); + entity = em.insert(entity); + entity.setArea(456.322f); + entity = em.update(entity); + entity = em.load(FloatObject.class, entity.getId()); + assertTrue(entity.getArea() == 456.322f); + } + + @Test + public void testUpdateFloatObject_Null() { + FloatObject entity = new FloatObject(); + entity.setArea(322.456f); + entity = em.insert(entity); + entity.setArea(null); + entity = em.update(entity); + entity = em.load(FloatObject.class, entity.getId()); + assertTrue(entity.getArea() == null); + } + + @Test + public void testUpdateDoubleField() { + DoubleField entity = new DoubleField(); + entity.setArea(Double.MAX_VALUE); + entity = em.insert(entity); + entity.setArea(Double.MIN_VALUE); + entity = em.update(entity); + entity = em.load(DoubleField.class, entity.getId()); + assertTrue(entity.getArea() == Double.MIN_VALUE); + } + + @Test + public void testUpdateDoubleObject() { + DoubleObject entity = new DoubleObject(); + entity.setArea(Double.MAX_VALUE); + entity = em.insert(entity); + entity.setArea(Double.MIN_VALUE); + entity = em.update(entity); + entity = em.load(DoubleObject.class, entity.getId()); + assertTrue(entity.getArea() == Double.MIN_VALUE); + } + + @Test + public void testUpdateDoubleObject_Null() { + DoubleObject entity = new DoubleObject(); + entity.setArea(Double.MAX_VALUE); + entity = em.insert(entity); + entity.setArea(null); + entity = em.update(entity); + entity = em.load(DoubleObject.class, entity.getId()); + assertTrue(entity.getArea() == null); + } + + @Test + public void testUpdateStringField() { + StringField entity = new StringField(); + entity.setName("Omaha"); + entity = em.insert(entity); + entity.setName("New York"); + entity = em.update(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getName().equals("New York")); + } + + @Test + public void testUpdateStringField_Empty() { + StringField entity = new StringField(); + entity.setName("Omaha"); + entity = em.insert(entity); + entity.setName(""); + entity = em.update(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getName().equals("")); + } + + @Test + public void testUpdateStringField_Null() { + StringField entity = new StringField(); + entity.setName("Omaha"); + entity = em.insert(entity); + entity.setName(null); + entity = em.update(entity); + entity = em.load(StringField.class, entity.getId()); + assertTrue(entity.getName() == null); + } + + @Test + public void testUpdateCalendarField() { + CalendarField entity = new CalendarField(); + Calendar now = Calendar.getInstance(); + entity.setCreationDate(now); + entity = em.insert(entity); + now.add(Calendar.DATE, 1); + entity.setCreationDate(now); + entity = em.update(entity); + entity = em.load(CalendarField.class, entity.getId()); + assertTrue(entity.getCreationDate().getTimeInMillis() == now.getTimeInMillis()); + } + + @Test + public void testUpdateCalendarField_Null() { + CalendarField entity = new CalendarField(); + Calendar now = Calendar.getInstance(); + entity.setCreationDate(now); + entity = em.insert(entity); + entity.setCreationDate(null); + entity = em.update(entity); + entity = em.load(CalendarField.class, entity.getId()); + assertTrue(entity.getCreationDate() == null); + } + + @Test + public void testUpdateDateField() { + DateField entity = new DateField(); + Calendar now = Calendar.getInstance(); + entity.setCreationDate(now.getTime()); + entity = em.insert(entity); + now.add(Calendar.DATE, 1); + entity.setCreationDate(now.getTime()); + entity = em.update(entity); + entity = em.load(DateField.class, entity.getId()); + assertTrue(entity.getCreationDate().getTime() == now.getTimeInMillis()); + } + + @Test + public void testUpdateDateField_Null() { + DateField entity = new DateField(); + Calendar now = Calendar.getInstance(); + entity.setCreationDate(now.getTime()); + entity = em.insert(entity); + entity.setCreationDate(null); + entity = em.update(entity); + entity = em.load(DateField.class, entity.getId()); + assertTrue(entity.getCreationDate() == null); + } + + @Test + public void testUpdateLocalDateField() { + LocalDateField entity = new LocalDateField(); + LocalDate today = LocalDate.now(); + entity.setBirthDate(today); + entity = em.insert(entity); + LocalDate tomorrow = today.plusDays(1); + entity.setBirthDate(tomorrow); + entity = em.update(entity); + entity = em.load(LocalDateField.class, entity.getId()); + assertTrue(entity.getBirthDate().equals(tomorrow)); + } + + @Test + public void testUpdateLocalDateField_Null() { + LocalDateField entity = new LocalDateField(); + LocalDate today = LocalDate.now(); + entity.setBirthDate(today); + entity = em.insert(entity); + entity.setBirthDate(null); + entity = em.update(entity); + entity = em.load(LocalDateField.class, entity.getId()); + assertNull(entity.getBirthDate()); + } + + @Test + public void testUpdateLocalTimeField() { + LocalTimeField entity = new LocalTimeField(); + LocalTime now = LocalTime.now(); + entity.setStartTime(now); + entity = em.insert(entity); + LocalTime plusOneHour = now.plusHours(1); + entity.setStartTime(plusOneHour); + entity = em.update(entity); + entity = em.load(LocalTimeField.class, entity.getId()); + assertEquals(plusOneHour, entity.getStartTime()); + } + + @Test + public void testUpdateLocalTimeField_Null() { + LocalTimeField entity = new LocalTimeField(); + LocalTime now = LocalTime.now(); + entity.setStartTime(now); + entity = em.insert(entity); + entity.setStartTime(null); + entity = em.update(entity); + entity = em.load(LocalTimeField.class, entity.getId()); + assertNull(entity.getStartTime()); + } + + @Test + public void testUpdateLocalDateTimeField() { + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime now = LocalDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + LocalDateTime nextDay = now.plusDays(1); + entity.setTimestamp(nextDay); + entity = em.update(entity); + entity = em.load(LocalDateTimeField.class, entity.getId()); + assertEquals(nextDay, entity.getTimestamp()); + } + + @Test + public void testUpdateLocalDateTimeField_Nano() { + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime now = LocalDateTime.now().withNano(999999999); + entity.setTimestamp(now); + entity = em.insert(entity); + LocalDateTime nextDay = now.plusDays(1); + entity.setTimestamp(nextDay); + entity = em.update(entity); + entity = em.load(LocalDateTimeField.class, entity.getId()); + assertEquals(nextDay, entity.getTimestamp()); + } + + @Test + public void testUpdateLocalDateTimeField_Null() { + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime now = LocalDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity.setTimestamp(null); + entity = em.update(entity); + entity = em.load(LocalDateTimeField.class, entity.getId()); + assertNull(entity.getTimestamp()); + } + + @Test + public void testUpdateOffsetDateTimeField() { + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime now = OffsetDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + OffsetDateTime nextDay = now.plusDays(2); + entity.setTimestamp(nextDay); + entity = em.update(entity); + entity = em.load(OffsetDateTimeField.class, entity.getId()); + assertEquals(nextDay, entity.getTimestamp()); + } + + @Test + public void testUpdateOffsetDateTimeField_Null() { + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime now = OffsetDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity.setTimestamp(null); + entity = em.update(entity); + entity = em.load(OffsetDateTimeField.class, entity.getId()); + assertNull(entity.getTimestamp()); + } + + @Test + public void testUpdateZonedDateTimeField() { + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime now = ZonedDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + ZonedDateTime nextDay = now.plusDays(2); + entity.setTimestamp(nextDay); + entity = em.update(entity); + entity = em.load(ZonedDateTimeField.class, entity.getId()); + assertEquals(nextDay, entity.getTimestamp()); + } + + @Test + public void testUpdateZonedDateTimeField_Null() { + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime now = ZonedDateTime.now(); + entity.setTimestamp(now); + entity = em.insert(entity); + entity.setTimestamp(null); + entity = em.update(entity); + entity = em.load(ZonedDateTimeField.class, entity.getId()); + assertNull(entity.getTimestamp()); + } + + @Test + public void testUpdateByteArayField() { + byte[] salt = new byte[64]; + random.nextBytes(salt); + ByteArrayField entity = new ByteArrayField(); + entity.setSalt(salt); + entity = em.insert(entity); + salt = new byte[32]; + random.nextBytes(salt); + entity.setSalt(salt); + entity = em.update(entity); + entity = em.load(ByteArrayField.class, entity.getId()); + assertTrue(Arrays.equals(salt, entity.getSalt())); + } + + @Test + public void testUpdateByteArayField_Null() { + byte[] salt = new byte[64]; + random.nextBytes(salt); + ByteArrayField entity = new ByteArrayField(); + entity.setSalt(salt); + entity = em.insert(entity); + salt = null; + entity.setSalt(salt); + entity = em.update(entity); + entity = em.load(ByteArrayField.class, entity.getId()); + assertTrue(entity.getSalt() == null); + } + + @Test + public void testUpdateCharArayField() { + char[] password = "super secret phrase".toCharArray(); + CharArrayField entity = new CharArrayField(); + entity.setPassword(password); + entity = em.insert(entity); + password = "What a lovely day!".toCharArray(); + entity.setPassword(password); + entity = em.update(entity); + entity = em.load(CharArrayField.class, entity.getId()); + assertTrue(Arrays.equals(password, entity.getPassword())); + } + + @Test + public void testUpdateCharArayField_Null() { + char[] password = "super secret phrase".toCharArray(); + CharArrayField entity = new CharArrayField(); + entity.setPassword(password); + entity = em.insert(entity); + password = null; + entity.setPassword(password); + entity = em.update(entity); + entity = em.load(CharArrayField.class, entity.getId()); + assertTrue(entity.getPassword() == null); + } + + @Test + public void testInsert_ListFields() { + ListFields entity = ListFields.getSampleEntity1(); + entity = em.insert(entity); + ListFields entity2 = em.load(ListFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_ListFields_Null() { + ListFields entity = new ListFields(); + entity = em.insert(entity); + ListFields entity2 = em.load(ListFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_ListFields() { + ListFields entity = ListFields.getSampleEntity1(); + entity = em.insert(entity); + List stringList = entity.getStringList(); + stringList.add("Ten"); + stringList.add("Hundred"); + entity = em.update(entity); + ListFields entity2 = em.load(ListFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_ListFields_Null() { + ListFields entity = ListFields.getSampleEntity1(); + entity = em.insert(entity); + entity.setStringList(null); + entity = em.update(entity); + ListFields entity2 = em.load(ListFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_ListFields_Keys() { + ListFields entity = new ListFields(); + String[] tagNames = { "List", "ArrayList", "LinkedList" }; + List tags = new ArrayList<>(); + for (String tagName : tagNames) { + Tag tag = new Tag(); + tag.setName(tagName); + tags.add(tag); + } + tags = em.insert(tags); + List keyList = new ArrayList<>(); + for (Tag tag : tags) { + keyList.add(tag.getKey()); + } + entity.setKeyList(keyList); + entity = em.insert(entity); + ListFields entity2 = em.load(ListFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_SetFields() { + SetFields entity = SetFields.getSampleEntity1(); + entity = em.insert(entity); + SetFields entity2 = em.load(SetFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_SetFields() { + SetFields entity = SetFields.getSampleEntity1(); + entity = em.insert(entity); + Set stringSet = entity.getStringSet(); + stringSet.add("Powerball"); + entity = em.update(entity); + SetFields entity2 = em.load(SetFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_SetFields_Null() { + SetFields entity = new SetFields(); + entity = em.insert(entity); + SetFields entity2 = em.load(SetFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_SetFields_Null() { + SetFields entity = SetFields.getSampleEntity1(); + entity = em.insert(entity); + entity.setStringSet(null); + entity = em.update(entity); + SetFields entity2 = em.load(SetFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_SetFields_Keys() { + SetFields entity = new SetFields(); + String[] tagNames = { "Set", "HashSet", "LinkedHashSet", "TreeSet" }; + List tags = new ArrayList<>(); + for (String tagName : tagNames) { + Tag tag = new Tag(); + tag.setName(tagName); + tags.add(tag); + } + tags = em.insert(tags); + Set keySet = new HashSet<>(); + for (Tag tag : tags) { + keySet.add(tag.getKey()); + } + entity.setKeySet(keySet); + entity = em.insert(entity); + SetFields entity2 = em.load(SetFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_MapFields() { + MapFields entity = MapFields.getSampleEntity1(); + entity = em.insert(entity); + MapFields entity2 = em.load(MapFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_MapFields_Null() { + MapFields entity = new MapFields(); + entity = em.insert(entity); + MapFields entity2 = em.load(MapFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_MapFields() { + MapFields entity = MapFields.getSampleEntity1(); + entity = em.insert(entity); + entity.getStringMap().put("Catatumbo", "Framework for GCS"); + entity = em.update(entity); + MapFields entity2 = em.load(MapFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_MapFields_Null() { + MapFields entity = MapFields.getSampleEntity1(); + entity = em.insert(entity); + entity.setStringMap(null); + entity = em.update(entity); + MapFields entity2 = em.load(MapFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_MapFields_Keys() { + MapFields entity = new MapFields(); + String[] tagNames = { "Map", "HashMap", "SortedMap", "TreeMap", "LinkedHashMap" }; + List tags = new ArrayList<>(); + for (String tagName : tagNames) { + Tag tag = new Tag(); + tag.setName(tagName); + tags.add(tag); + } + tags = em.insert(tags); + Map keyMap = new HashMap<>(); + int i = 0; + for (Tag tag : tags) { + keyMap.put(tag.getName(), tag.getKey()); + } + entity.setKeyMap(keyMap); + entity = em.insert(entity); + MapFields entity2 = em.load(MapFields.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test(expected = EntityNotFoundException.class) + public void testUpdate_ThatDoesNotExist() { + LongId entity = new LongId(); + entity.setId(100); + entity.setField1("I'm 100L"); + // In case if it exists, delete it + em.delete(entity); + LongId entity2 = em.load(LongId.class, entity.getId()); + if (entity2 == null) { + try { + em.update(entity); + } catch (EntityNotFoundException exp) { + throw exp; + } catch (EntityManagerException exp) { + String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); + if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { + // Running on emulator that has a bug. + throw new EntityNotFoundException(exp); + } + } + } + } + + @Test + public void testUpdate_GeoLocationField() { + GeoLocationField omaha = GeoLocationField.OMAHA; + GeoLocationField entity = new GeoLocationField(omaha.getCity(), omaha.getCoordinates()); + entity = em.insert(entity); + GeoLocation newCoordinates = new GeoLocation(10, 10); + entity.setCoordinates(newCoordinates); + em.update(entity); + entity = em.load(GeoLocationField.class, entity.getId()); + assertTrue(entity.getCoordinates().equals(newCoordinates)); + } + + @Test + public void testUpdate_GeoLocationField_Null() { + GeoLocationField paris = GeoLocationField.PARIS; + GeoLocationField entity = new GeoLocationField(paris.getCity(), paris.getCoordinates()); + entity = em.insert(entity); + entity.setCoordinates(null); + em.update(entity); + entity = em.load(GeoLocationField.class, entity.getId()); + assertNull(entity.getCoordinates()); + } + + @Test + public void testUpdate_IgnoredField() { + IgnoreField entity = new IgnoreField(); + entity.setName("John Doe"); + entity.setComputed("This should not be persisted"); + entity = em.insert(entity); + entity = em.load(IgnoreField.class, entity.getId()); + entity.setName("John Smith"); + entity.setComputed("Wassup!"); + em.update(entity); + entity = em.load(IgnoreField.class, entity.getId()); + assertTrue(entity.getId() > 0 && entity.getName().equals("John Smith") + && entity.getComputed() == null); + } + + @Test + public void testUpsert_LongId_Insert() { + final String message = "Upsert created me"; + LongId entity = new LongId(); + entity.setField1(message); + entity = em.upsert(entity); + entity = em.load(LongId.class, entity.getId()); + assertTrue(message.equals(entity.getField1())); + } + + @Test + public void testUpsert_LongId_Update() { + final String message = "Upsert created me"; + final String message2 = "Upsert created me, then updated"; + LongId entity = new LongId(); + entity.setField1(message); + entity = em.upsert(entity); + entity = em.load(LongId.class, entity.getId()); + entity.setField1(message2); + em.upsert(entity); + entity = em.load(LongId.class, entity.getId()); + assertTrue(message2.equals(entity.getField1())); + } + + @Test + public void testUpsert_StringId_Insert() { + final String greetings = "Upsert created me"; + StringId entity = new StringId(); + entity.setGreetings(greetings); + entity = em.upsert(entity); + entity = em.load(StringId.class, entity.getId()); + assertTrue(greetings.equals(entity.getGreetings())); + + } + + @Test + public void testUpsert_StringId_Update() { + final String greetings1 = "Upsert created me"; + final String greetings2 = "Upsert first created me, then updated"; + StringId entity = new StringId(); + entity.setGreetings(greetings1); + entity = em.upsert(entity); + entity = em.load(StringId.class, entity.getId()); + entity.setGreetings(greetings2); + em.upsert(entity); + entity = em.load(StringId.class, entity.getId()); + assertTrue(greetings2.equals(entity.getGreetings())); + + } + + @Test + public void testUpsert_List_Insert() { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + StringField entity = new StringField(); + entity.setName("I'm StringField Entity " + i); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.size() == 5 && entities.get(0).getId() != 0); + } + + @Test(expected = EntityManagerException.class) + public void testDelete_UnsetId() { + StringField entity = new StringField(); + em.delete(entity); + } + + @Test + public void testDelete_Root() { + StringField entity = new StringField(); + entity.setName("Hello World!"); + entity = em.insert(entity); + entity = em.load(StringField.class, entity.getId()); + em.delete(entity); + StringField entity2 = em.load(StringField.class, entity.getId()); + assertTrue(entity != null && entity2 == null); + } + + @Test + public void testDelete_Child() { + ParentEntity parent = new ParentEntity(); + parent.setField1("Parent for Delete Test!"); + parent = em.insert(parent); + + ChildEntity child = new ChildEntity(); + child.setField1("Child for Delete Test"); + child.setParentKey(parent.getKey()); + child = em.insert(child); + + child = em.load(ChildEntity.class, parent.getKey(), child.getId()); + em.delete(child); + ChildEntity child2 = em.load(ChildEntity.class, parent.getKey(), child.getId()); + assertTrue(child != null && child2 == null); + } + + @Test + public void testDelete_Child_WithNoParent() { + ParentEntity parent = new ParentEntity(); + parent.setField1("Parent for Delete Test!"); + parent = em.insert(parent); + + ChildEntity child = new ChildEntity(); + child.setField1("Child for Delete Test"); + child.setParentKey(parent.getKey()); + child = em.insert(child); + + // Second Child with the same ID as the first one, but no parent. + ChildEntity child2 = new ChildEntity(); + child2.setId(child.getId()); + child2.setField1("Child with no parent"); + child2 = em.insert(child2); + + child2 = em.load(ChildEntity.class, child2.getId()); + em.delete(child2); + ChildEntity child3 = em.load(ChildEntity.class, child2.getId()); + assertTrue(child2 != null && child3 == null); + } + + @Test + public void testDelete_Grandchild() { + ParentEntity parent = new ParentEntity(); + parent.setField1("Parent for Delete Test!"); + parent = em.insert(parent); + + ChildEntity child = new ChildEntity(); + child.setField1("Child for Delete Test"); + child.setParentKey(parent.getKey()); + child = em.insert(child); + + GrandchildEntity grandchild = new GrandchildEntity(); + grandchild.setField1("Grandchild for Delete Test"); + grandchild.setParentKey(child.getKey()); + grandchild = em.insert(grandchild); + + grandchild = em.load(GrandchildEntity.class, child.getKey(), grandchild.getId()); + em.delete(grandchild); + GrandchildEntity grandchild2 = em.load(GrandchildEntity.class, child.getKey(), + grandchild.getId()); + assertTrue(grandchild != null && grandchild2 == null); + } + + /* + * @Test public void testDeleteAll() { List entities = new ArrayList<>(); for (int i = + * 0; i < 5; i++) { DeleteAll entity = new DeleteAll(); entity.setField1("Delete All " + i); + * entities.add(entity); } em.insert(entities); try { Thread.sleep(5000L); } catch + * (InterruptedException e) { e.printStackTrace(); } long deleteCount = + * em.deleteAll(DeleteAll.class); assertTrue(deleteCount == 5); } + */ + + @Test + public void testLoad_ThatDoesNotExist() { + long id = random.nextLong(); + StringField entity = new StringField(); + entity.setId(id); + em.delete(entity); + StringField entity2 = em.load(StringField.class, id); + assertNull(entity2); + } + + @Test + public void testLoad_Good() { + long id = random.nextLong(); + StringField entity = new StringField(); + entity.setId(id); + entity.setName("USA"); + em.delete(entity); + em.insert(entity); + StringField entity2 = em.load(StringField.class, entity.getId()); + assertTrue(entity.getId() == entity2.getId()); + } + + @Test + public void testLoad_ParentChild() { + ParentEntity parent = new ParentEntity(); + parent.setField1("Parent for load test"); + parent = em.insert(parent); + + ChildEntity child = new ChildEntity(); + child.setField1("Child for load test"); + child.setParentKey(parent.getKey()); + child = em.insert(child); + + GrandchildEntity grandchild = new GrandchildEntity(); + grandchild.setField1("Grandchild for laod test"); + grandchild.setParentKey(child.getKey()); + grandchild = em.insert(grandchild); + + ParentEntity parent2 = em.load(ParentEntity.class, parent.getId()); + ChildEntity child2 = em.load(ChildEntity.class, parent2.getKey(), child.getId()); + GrandchildEntity grandchild2 = em.load(GrandchildEntity.class, child2.getKey(), + grandchild.getId()); + + assertTrue(grandchild.getId() == grandchild2.getId() + && grandchild.getField1().equals(grandchild2.getField1()) + && grandchild.getParentKey().equals(grandchild2.getParentKey())); + } + + @Test + public void testLoad_IgnoredField() { + IgnoreField2 entity = new IgnoreField2(); + entity.setName("Hello World"); + entity.setComputed("Hola Mundo"); + entity = em.insert(entity); + entity = em.load(IgnoreField2.class, entity.getId()); + + // Load the previously inserted entity using IgnoreFeild.class + IgnoreField entity2 = em.load(IgnoreField.class, entity.getId()); + assertTrue(entity.getId() == entity2.getId() && entity.getComputed() != null + && entity2.getComputed() == null); + } + + @Test + public void testLoadById() { + List entities = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + LongId entity = new LongId(); + entity.setField1("Test for Loading Multiple Entities " + i); + entities.add(entity); + } + entities = em.insert(entities); + List identifiers = new ArrayList<>(); + for (LongId entity : entities) { + identifiers.add(entity.getId()); + } + List entities2 = em.loadById(LongId.class, identifiers); + assertEquals(entities, entities2); + } + + @Test + public void testLoadById_MissingKey() { + List entities = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + LongId entity = new LongId(); + entity.setField1("Test for Loading Multiple Entities " + i); + entities.add(entity); + } + entities = em.insert(entities); + List identifiers = new ArrayList<>(); + for (LongId entity : entities) { + identifiers.add(entity.getId()); + } + identifiers.add(0, -100L); + identifiers.add(3, -200L); + List entities2 = em.loadById(LongId.class, identifiers); + assertTrue(entities2.get(0) == null && entities2.get(1) != null && entities2.get(3) == null); + } + + @Test + public void testLoadByName() { + List entities = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + StringId entity = new StringId(); + entity.setGreetings("Test for Loading Multiple Entities " + i); + entities.add(entity); + } + entities = em.insert(entities); + List identifiers = new ArrayList<>(); + for (StringId entity : entities) { + identifiers.add(entity.getId()); + } + List entities2 = em.loadByName(StringId.class, identifiers); + assertEquals(entities, entities2); + } + + @Test + public void executeTest_SelectAll() { + EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Task order by __key__"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 50 && tasks.get(0).getId() == 1 + && tasks.get(tasks.size() - 1).getId() == 50); + } + + @Test + public void rexecuteTest_SelectPriorityFilter() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE priority = @1 order by __key__"); + request.addPositionalBinding(0); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 10 && tasks.get(0).getId() == 5 + && tasks.get(tasks.size() - 1).getId() == 50); + } + + @Test + public void executeTest_SelectPriorityAndCompleteFilter() { + EntityQueryRequest request = em.createEntityQueryRequest( + "SELECT * FROM Task WHERE priority = @1 AND complete = @2 order by __key__"); + request.addPositionalBinding(0); + request.addPositionalBinding(true); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 10 + && tasks.get(tasks.size() - 1).getId() == 50); + } + + @Test + public void testExecute_SelectPriorityAndCompleteFilter_Varargs() { + EntityQueryRequest request = em.createEntityQueryRequest( + "SELECT * FROM Task WHERE priority = @1 AND complete = @2 order by __key__"); + request.addPositionalBindings(0, true); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 10 + && tasks.get(tasks.size() - 1).getId() == 50); + } + + @Test + public void executeTest_SelectTaskNameFilter() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE name = @1 order by __key__"); + request.addPositionalBinding("My Task 13"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 1 && tasks.get(0).getId() == 13); + } + + @Test + public void executeTest_SelectTasksDueByTomorrow() { + Calendar cal = getToday(); + cal.add(Calendar.DATE, 1); + Date tomorrow = cal.getTime(); + + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE completionDate <= @1"); + request.addPositionalBinding(tomorrow); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 20); + } + + @Test + public void executeTest_SelectTasksDueByBetweenTomorrowAndDayAfter_NamedBindings() { + Calendar cal = getToday(); + cal.add(Calendar.DATE, 1); + Date tomorrow = cal.getTime(); + cal.add(Calendar.DATE, 1); + Date dayAfterTomorrow = cal.getTime(); + Map bindings = new HashMap<>(); + bindings.put("Tomorrow", tomorrow); + bindings.put("DayAfterTomorrow", dayAfterTomorrow); + + EntityQueryRequest request = em.createEntityQueryRequest( + "SELECT * FROM Task WHERE completionDate >= @Tomorrow AND completionDate <= @DayAfterTomorrow"); + request.setNamedBindings(bindings); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 20); + } + + @Test + public void runQueryTest_Pagination_Forward() { + final int pageSize = 5; + String query = "SELECT * FROM Task ORDER BY __key__"; + DatastoreCursor endCursor = null; + List tasks = null; + for (int i = 0; i < 5; i++) { + String pageQuery = query + " LIMIT @Limit"; + if (i > 0) { + pageQuery += " OFFSET @Offset"; + } + EntityQueryRequest request = em.createEntityQueryRequest(pageQuery); + request.setNamedBinding("Limit", pageSize); + if (i > 0) { + request.setNamedBinding("Offset", endCursor); + } + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + tasks = response.getResults(); + endCursor = response.getEndCursor(); + System.out.println("**** Page " + (i + 1) + "****"); + for (Task task : tasks) { + System.out.println(task.getId() + " ---> " + task.getName()); + } + } + assertTrue(tasks.size() == 5 && tasks.get(0).getId() == 21); + + } + + @Test + public void testExecute() { + EntityQueryRequest request = em.createEntityQueryRequest("SELECT * from Task"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + for (Task task : tasks) { + System.out.println(task.getId() + "--->" + task.getName()); + } + System.out.println("Start Cursor: " + response.getStartCursor()); + System.out.println("End Cursor: " + response.getEndCursor()); + assertTrue(tasks.size() == 50); + } + + @Test + public void testExecute_Limit_10() { + EntityQueryRequest request = em.createEntityQueryRequest("SELECT * from Task LIMIT @1"); + request.addPositionalBinding(10L); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + System.out.println("Start Cursor: " + response.getStartCursor()); + System.out.println("End Cursor: " + response.getEndCursor()); + for (Task task : tasks) { + System.out.println(task.getId() + "--->" + task.getName()); + } + assertTrue(tasks.size() == 10); + } + + @Test + public void testExecute_PositionalBinding() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * from Task WHERE priority=@1"); + request.addPositionalBinding(3); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + System.out.println("Start Cursor: " + response.getStartCursor()); + System.out.println("End Cursor: " + response.getEndCursor()); + for (Task task : tasks) { + System.out.println(task.getId() + "--->" + task.getName()); + } + assertTrue(tasks.size() == 10); + } + + @Test + public void testExecute_PositionalBindings() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * from Task WHERE priority=@1 AND complete=@2"); + request.addPositionalBinding(0); + request.addPositionalBinding(true); + + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + System.out.println("Start Cursor: " + response.getStartCursor()); + System.out.println("End Cursor: " + response.getEndCursor()); + for (Task task : tasks) { + System.out.println(task.getId() + "--->" + task.getName()); + } + assertTrue(tasks.size() == 5); + } + + @Test + public void testExecute_GeoLocation() { + em.deleteAll(GeoLocationField.class); + GeoLocationField jfk = GeoLocationField.NEW_YORK_CITY; + GeoLocationField oma = GeoLocationField.OMAHA; + GeoLocationField cdg = GeoLocationField.PARIS; + em.insert(jfk); + em.insert(oma); + em.insert(cdg); + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM CityCoordinates ORDER BY city"); + QueryResponse response = em.executeEntityQueryRequest(GeoLocationField.class, + request); + List cities = response.getResults(); + // This test fails sometimes if the below assertion is cities.size() == + // 3. + assertTrue(cities.size() > 0 && cities.get(0).getCoordinates().equals(jfk.getCoordinates())); + + } + + @Test + public void testExecuteProjectionQuery() { + ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Task"); + QueryResponse response = em.executeProjectionQueryRequest(Task.class, request); + List tasks = response.getResults(); + for (Task task : tasks) { + System.out.printf("Id: %d; Name: %s; Priority: %s; Complete: %s; Completion Date: %s\n", + task.getId(), task.getName(), task.getPriority(), task.isComplete(), + task.getCompletionDate()); + } + assertTrue(tasks.size() == 50); + } + + @Test + public void testExecuteProjectionQuery2() { + // Uses a different entity - with a subset of properties from the main + // entity + ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Task"); + QueryResponse response = em.executeProjectionQueryRequest(TaskName.class, request); + List tasks = response.getResults(); + for (TaskName task : tasks) { + System.out.printf("Id: %d; Name: %s; \n", task.getId(), task.getName()); + } + assertTrue(tasks.size() == 50); + } + + @Test + public void testExecuteKeyQuery() { + KeyQueryRequest request = em.createKeyQueryRequest("SELECT __key__ from Task"); + QueryResponse response = em.executeKeyQueryRequest(request); + List keys = response.getResults(); + for (DatastoreKey key : keys) { + System.out.printf("%-10s %20s %s\n", key.kind(), key.nameOrId(), key.getEncoded()); + } + assertTrue(keys.size() == 50); + } + + @Test(expected = EntityManagerException.class) + public void testUpdate_InvalidStringId() { + StringId entity = new StringId(); + entity.setGreetings("Good Night, this should never show up in the datastore"); + entity = em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testExecute_WithLiteral_Default() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + } + + @Test(expected = EntityManagerException.class) + public void testExecute_WithLiteral_False() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + } + + @Test + public void testExecute_WithLiteral_True() { + EntityQueryRequest request = em + .createEntityQueryRequest("SELECT * FROM Task WHERE priority = 0 order by __key__"); + request.setAllowLiterals(true); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + List tasks = response.getResults(); + assertTrue(tasks.size() == 10 && tasks.get(0).getId() == 5 + && tasks.get(tasks.size() - 1).getId() == 50); + } + + @Test(expected = EntityManagerException.class) + public void testExecute_WithSyntheticLiteral_Default() { + EntityQueryRequest request = em.createEntityQueryRequest( + "SELECT * FROM Task where completionDate > datetime('2016-08-10T00:00:00.000000z')"); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + } + + @Test + public void testExecute_WithSyntheticLiteral_True() { + EntityQueryRequest request = em.createEntityQueryRequest( + "SELECT * FROM Task where completionDate > datetime('2016-08-10T00:00:00.000000z')"); + request.setAllowLiterals(true); + QueryResponse response = em.executeEntityQueryRequest(Task.class, request); + // Let's not worry about the results + } + + @Test + public void testInsert_Embedded() { + Customer entity = Customer.createSampleCustomer1(); + entity = em.insert(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_Embedded_NullAddress() { + Customer entity = Customer.createSampleCustomer2(); + entity = em.insert(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_Embedded_NullZipCode() { + Customer entity = Customer.createSampleCustomer3(); + entity = em.insert(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_Embedded() { + Customer entity = Customer.createSampleCustomer1(); + entity = em.insert(entity); + entity = em.load(Customer.class, entity.getId()); + entity.setName("John Smith"); + entity.getBillingAddress().setCity("Lincoln"); + entity.getShippingAddress().getZipCode().setFiveDigits("65432"); + em.update(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_Embedded_NullAddress() { + Customer entity = Customer.createSampleCustomer2(); + entity = em.insert(entity); + entity = em.load(Customer.class, entity.getId()); + entity.setName("Super Customer Updated"); + entity.getBillingAddress().setCity("Lincoln"); + entity.getShippingAddress().getZipCode().setFiveDigits("65432"); + em.update(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_Embedded_NullZipCode() { + Customer entity = Customer.createSampleCustomer3(); + entity = em.insert(entity); + entity = em.load(Customer.class, entity.getId()); + entity.setName("Super Customer Updated"); + entity.getShippingAddress().getZipCode().setFiveDigits("65432"); + entity.getBillingAddress().getZipCode().setFiveDigits("65432"); + em.update(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testDelete_Embedded() { + Customer entity = Customer.createSampleCustomer1(); + entity = em.insert(entity); + entity = em.load(Customer.class, entity.getId()); + em.delete(entity); + Customer entity2 = em.load(Customer.class, entity.getId()); + assertTrue(entity != null && entity2 == null); + } + + @Test + public void testExecuteEntityQuery_Embedded() { + em.deleteAll(Customer.class); + List customers = new ArrayList<>(); + customers.add(Customer.createSampleCustomer1()); + customers.add(Customer.createSampleCustomer2()); + customers.add(Customer.createSampleCustomer3()); + em.insert(customers); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest("SELECT * FROM Customer"); + QueryResponse response = em.executeEntityQueryRequest(Customer.class, request); + List output = response.getResults(); + assertTrue(output.size() == 3); + } + + @Test + public void testExecuteProjectionQuery_Embedded() { + em.deleteAll(Customer.class); + List customers = new ArrayList<>(); + customers.add(Customer.createSampleCustomer1()); + customers.add(Customer.createSampleCustomer2()); + customers.add(Customer.createSampleCustomer3()); + em.insert(customers); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + ProjectionQueryRequest request = em.createProjectionQueryRequest("SELECT name FROM Customer"); + QueryResponse response = em.executeProjectionQueryRequest(Customer.class, request); + List output = response.getResults(); + assertTrue(output.size() == 3); + } + + @Test + public void testInsert_MappedSupperClass() { + SubClass1 entity = new SubClass1(); + entity.setName("John Doe"); + entity.setCreatedBy("user1"); + entity.setCreatedOn(new Date()); + entity.setModifiedBy("user2"); + entity.setModifiedOn(new Date()); + entity = em.insert(entity); + SubClass1 entity2 = em.load(SubClass1.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_MappedSupperClass2() { + SubClass2 entity = new SubClass2(); + entity.setName("John Doe"); + entity.setCreatedBy("user1"); + entity.setCreatedOn(new Date()); + entity.setModifiedBy("user2"); + entity.setModifiedOn(new Date()); + entity = em.insert(entity); + SubClass2 entity2 = em.load(SubClass2.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testUpdate_MappedSupperClass2() { + SubClass2 entity = new SubClass2(); + entity.setName("John Doe"); + entity.setCreatedBy("user1"); + entity.setCreatedOn(new Date()); + entity.setModifiedBy("user2"); + entity.setModifiedOn(new Date()); + entity = em.insert(entity); + SubClass2 entity2 = em.load(SubClass2.class, entity.getId()); + entity2.setName("John Smith"); + em.update(entity2); + SubClass2 entity3 = em.load(SubClass2.class, entity2.getId()); + assertTrue(entity3.equals(entity2)); + } + + @Test + public void testInsert_MappedSupperClass3() { + SubClass3 entity = new SubClass3(); + entity.setFieldx("I'm super super!"); + entity.setName("John Doe"); + entity.setCreatedBy("user1"); + entity.setCreatedOn(new Date()); + entity.setModifiedBy("user2"); + entity.setModifiedOn(new Date()); + entity = em.insert(entity); + SubClass3 entity2 = em.load(SubClass3.class, entity.getId()); + assertTrue(entity.equals(entity2) && entity2.getMyKey() != null); + } + + @Test + public void testInsert_MappedSupperClass4() { + SubClass4 entity = new SubClass4(); + entity.setFieldx("I'm super super!"); + entity.setName("John Doe"); + entity.setCreatedBy("user1"); + entity.setCreatedOn(new Date()); + entity.setModifiedBy("user2"); + entity.setModifiedOn(new Date()); + entity = em.insert(entity); + SubClass4 entity2 = em.load(SubClass4.class, entity.getId()); + assertTrue(entity.equals(entity2) && entity2.getCreatedBy() == null); + } + + @Test + public void testInsert_OptimisticLock1() { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Optimistic Lock Test Insert Single"); + OptimisticLock1 entity2 = em.insert(entity); + assertTrue(entity2.getId() != 0 && entity2.getVersion() == 1); + } + + @Test + public void testInsert_OptimisticLock1_Multiple() { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Optimistic Lock Test Insert Multiple " + i); + entities.add(entity); + } + List insertedEntities = em.insert(entities); + assertTrue(insertedEntities.get(0).getVersion() == 1 + && insertedEntities.get(1).getVersion() == 1 && insertedEntities.get(2).getVersion() == 1 + && insertedEntities.get(3).getVersion() == 1 && insertedEntities.get(4).getVersion() == 1); + } + + @Test + public void testUpdate_OptimisticLock1() { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Before Update!"); + OptimisticLock1 entity2 = em.insert(entity); + OptimisticLock1 entity3 = em.load(OptimisticLock1.class, entity2.getId()); + entity3.setName("After Update"); + OptimisticLock1 entity4 = em.update(entity3); + OptimisticLock1 entity5 = em.load(OptimisticLock1.class, entity4.getId()); + assertTrue(entity2.getVersion() == 1 && entity3.getVersion() == 1 && entity4.getVersion() == 2 + && entity5.getVersion() == 2); + } + + @Test(expected = EntityManagerException.class) + public void testUpdate_OptimisticLock2() { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Hello World!"); + entity = em.insert(entity); + OptimisticLock1 entity2 = em.load(OptimisticLock1.class, entity.getId()); + entity2.setName("Hello World! After Update!!"); + entity2 = em.update(entity2); + entity2 = em.update(entity2); + entity2 = em.update(entity2); + entity = em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpdate_OptimisticLock3() { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Hello World!"); + entity = em.insert(entity); + OptimisticLock1 entity2 = em.load(OptimisticLock1.class, entity.getId()); + entity2.setName("Hello World! After Update!!"); + entity2 = em.update(entity2); + em.delete(entity); + entity2 = em.update(entity2); + } + + @Test + public void testUpdate_OptimisticLock4() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Test Update Multiple " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); + List entities3 = em.loadById(OptimisticLock1.class, ids); + List entities4 = em.update(entities3); + assertEquals(1, entities2.get(0).getVersion()); + assertEquals(1, entities2.get(1).getVersion()); + assertEquals(1, entities3.get(0).getVersion()); + assertEquals(1, entities3.get(1).getVersion()); + assertEquals(2, entities4.get(0).getVersion()); + assertEquals(2, entities4.get(1).getVersion()); + } + + @Test(expected = OptimisticLockException.class) + public void testUpdate_OptimisticLock5() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Test Update Multiple " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); + List entities3 = em.loadById(OptimisticLock1.class, ids); + em.delete(entities3); + List entities4 = em.update(entities3); + } + + @Test(expected = OptimisticLockException.class) + public void testUpdate_OptimisticLock6() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + OptimisticLock1 entity = new OptimisticLock1(); + entity.setName("Test Update Multiple " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + List ids = Arrays.asList(entities2.get(0).getId(), entities2.get(1).getId()); + List entities3 = em.loadById(OptimisticLock1.class, ids); + List entities4 = em.update(entities3); + List entities5 = em.update(entities3); + } + + @Test + public void testRunInTransaction() { + final StringField entity = new StringField(); + entity.setName("Run in transaction test"); + final StringField insertedEntity = em.insert(entity); + StringField updatedEntity = em.executeInTransaction(new TransactionalTask() { + @Override + public StringField execute(DatastoreTransaction transaction) { + // StringField entity = new StringField(); + StringField loadedEntity = transaction.load(StringField.class, insertedEntity.getId()); + loadedEntity.setName("Updated from runInTransaction"); + loadedEntity = transaction.update(loadedEntity); + return loadedEntity; + } + }); + assertTrue(updatedEntity.getName().equals("Updated from runInTransaction")); + } + + @Test(expected = EntityManagerException.class) + public void testRunInTransaction_Failure() { + final StringField entity = new StringField(); + entity.setId(3001); + entity.setName("Run in transaction test"); + final StringField insertedEntity = em.insert(entity); + em.executeInTransaction(new TransactionalTask() { + @Override + public Void execute(DatastoreTransaction transaction) { + for (int i = 3000; i < 3005; i++) { + StringField entity = new StringField(); + entity.setId(i); + transaction.insert(entity); + } + return null; + } + }); + } + + @Test + public void testInsert_IndexedString_MaxLimit() { + StringField entity = new StringField(); + final int length = 1500; + entity.setName(TestUtils.getRandomString(length)); + StringField insertedEntity = em.insert(entity); + StringField loadedEntity = em.load(StringField.class, insertedEntity.getId()); + assertEquals(length, insertedEntity.getName().length()); + assertEquals(length, loadedEntity.getName().length()); + } + + @Test(expected = EntityManagerException.class) + public void testInsert_IndexedString_MaxLimit_Exceeded() { + StringField entity = new StringField(); + final int length = 1501; + entity.setName(TestUtils.getRandomString(length)); + StringField insertedEntity = em.insert(entity); + } + + @Test + public void testInsert_UnIndexedString_5K() { + UnindexedStringField entity = new UnindexedStringField(); + final int length = 5 * 1024; + entity.setHugeString(TestUtils.getRandomString(length)); + UnindexedStringField insertedEntity = em.insert(entity); + UnindexedStringField loadedEntity = em.load(UnindexedStringField.class, insertedEntity.getId()); + assertEquals(length, insertedEntity.getHugeString().length()); + assertEquals(length, loadedEntity.getHugeString().length()); + } + + @Test + public void testInsertEmbedded_Imploded1() { + Contact contact = Contact.createContact1(); + Contact insertedContact = em.insert(contact); + Contact loadedContact = em.load(Contact.class, insertedContact.getId()); + assertTrue(contact.equalsExceptId(insertedContact)); + assertTrue(insertedContact.equals(loadedContact)); + } + + @Test + public void testInsertEmbedded_Imploded2() { + Contact contact = Contact.createContact2(); + Contact insertedContact = em.insert(contact); + Contact loadedContact = em.load(Contact.class, insertedContact.getId()); + assertTrue(contact.equalsExceptId(insertedContact)); + assertTrue(insertedContact.equals(loadedContact)); + } + + @Test + public void testUpdateEmbedded_Imploded1() { + Contact contact = Contact.createContact2(); + contact = em.insert(contact); + contact = em.load(Contact.class, contact.getId()); + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("1"); + phone.setAreaCode("111"); + phone.setSubscriberNumber("2223333"); + contact.setMobileNumber(phone); + em.update(contact); + contact = em.load(Contact.class, contact.getId()); + assertEquals("2223333", contact.getMobileNumber().getSubscriberNumber()); + } + + @Test + public void testInsert_BigDecimal() { + BigDecimalField entity = new BigDecimalField(new BigDecimal(23.654)); + entity = em.insert(entity); + BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); + assertTrue(entity.getId() != 0); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_BigDecimal_Null() { + BigDecimalField entity = new BigDecimalField(); + entity = em.insert(entity); + BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); + assertTrue(entity.getId() != 0); + assertTrue(entity.equals(entity2) && entity2.getValue() == null); + } + + @Test + public void testUpdate_BigDecimal() { + BigDecimalField entity = new BigDecimalField(new BigDecimal("500")); + entity = em.insert(entity); + entity.setValue(new BigDecimal(0)); + entity = em.update(entity); + BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); + assertTrue(entity.getId() != 0); + assertTrue(entity.equals(entity2) && entity2.getValue().compareTo(BigDecimal.ZERO) == 0); + } + + @Test + public void testUpdate_BigDecimal_Null() { + BigDecimalField entity = new BigDecimalField(new BigDecimal("5000")); + entity = em.insert(entity); + entity.setValue(null); + entity = em.update(entity); + BigDecimalField entity2 = em.load(BigDecimalField.class, entity.getId()); + assertTrue(entity.getId() != 0); + assertTrue(entity.equals(entity2) && entity2.getValue() == null); + } + + @Test + public void testInsert_Item() { + Item entity = new Item(); + entity.setName("Candy"); + entity.setPrice(new BigDecimal("1")); + entity.setDiscount(BigDecimal.ZERO); + entity = em.insert(entity); + Item entity2 = em.load(Item.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test(expected = MappingException.class) + public void testInsert_Item_PrecisionLoss() { + Item entity = new Item(); + entity.setName("Candy"); + entity.setPrice(new BigDecimal("1.699")); + entity = em.insert(entity); + Item entity2 = em.load(Item.class, entity.getId()); + assertTrue(entity.equals(entity2)); + } + + @Test + public void testInsert_DeviceType() { + Visitor entity = new Visitor(DeviceType.TABLET); + entity = em.insert(entity); + Visitor entity2 = em.load(Visitor.class, entity.getId()); + assertTrue(entity.equals(entity2)); + + } + + @Test + public void testInsert_AccessorTestEntity() { + AccessorTestEntity entity = AccessorTestEntity.getSample1(); + AccessorTestEntity entity2 = em.insert(entity); + AccessorTestEntity entity3 = em.load(AccessorTestEntity.class, entity2.getId()); + assertTrue(entity.equalsExceptId(entity2)); + assertEquals(entity2, entity3); + } + + @Test + public void testArrayIndex1() { + ParentEntity parentEntity = new ParentEntity(); + parentEntity.setField1("ArrayIndexTest"); + parentEntity = em.insert(parentEntity); + ArrayIndex entity = ArrayIndex.getSampleEntity(); + entity.setParentKey(parentEntity.getKey()); + entity = em.insert(entity); + String gql = "SELECT * FROM ArrayIndex WHERE stringList=@1 AND __key__ HAS ANCESTOR @2"; + EntityQueryRequest request = em.createEntityQueryRequest(gql); + request.addPositionalBinding("Two"); + request.addPositionalBinding(parentEntity.getKey()); + QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); + List results = response.getResults(); + assertEquals(1, results.size()); + } + + @Test + public void testArrayIndex2() { + ParentEntity parentEntity = new ParentEntity(); + parentEntity.setField1("ArrayIndexTest"); + parentEntity = em.insert(parentEntity); + ArrayIndex entity = ArrayIndex.getSampleEntity(); + entity.setParentKey(parentEntity.getKey()); + entity = em.insert(entity); + String gql = "SELECT * FROM ArrayIndex WHERE unindexedStringList=@1 AND __key__ HAS ANCESTOR @2"; + EntityQueryRequest request = em.createEntityQueryRequest(gql); + request.addPositionalBinding("Two"); + request.addPositionalBinding(parentEntity.getKey()); + QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); + List results = response.getResults(); + assertEquals(0, results.size()); + } + + @Test + public void testArrayIndex3() { + ParentEntity parentEntity = new ParentEntity(); + parentEntity.setField1("ArrayIndexTest"); + parentEntity = em.insert(parentEntity); + ArrayIndex entity = ArrayIndex.getSampleEntity(); + entity.setParentKey(parentEntity.getKey()); + entity = em.insert(entity); + String gql = "SELECT * FROM ArrayIndex WHERE stringSet=@1 AND __key__ HAS ANCESTOR @2"; + EntityQueryRequest request = em.createEntityQueryRequest(gql); + request.addPositionalBinding("Two"); + request.addPositionalBinding(parentEntity.getKey()); + QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); + List results = response.getResults(); + assertEquals(1, results.size()); + } + + @Test + public void testArrayIndex4() { + ParentEntity parentEntity = new ParentEntity(); + parentEntity.setField1("ArrayIndexTest"); + parentEntity = em.insert(parentEntity); + ArrayIndex entity = ArrayIndex.getSampleEntity(); + entity.setParentKey(parentEntity.getKey()); + entity = em.insert(entity); + String gql = "SELECT * FROM ArrayIndex WHERE unindexedStringSet=@1 AND __key__ HAS ANCESTOR @2"; + EntityQueryRequest request = em.createEntityQueryRequest(gql); + request.addPositionalBinding("Two"); + request.addPositionalBinding(parentEntity.getKey()); + QueryResponse response = em.executeEntityQueryRequest(ArrayIndex.class, request); + List results = response.getResults(); + assertEquals(0, results.size()); + } + + @Test + public void testEntitySerializationWithKey() { + ParentEntity entity = new ParentEntity(); + entity.setField1("Serialization Test"); + entity = em.insert(entity); + ObjectOutputStream out = null; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + out = new ObjectOutputStream(bos); + out.writeObject(entity); + } catch (Exception exp) { + fail(exp.toString()); + } finally { + Utility.close(out); + } + ParentEntity entity2 = null; + ObjectInputStream in = null; + try { + in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); + entity2 = (ParentEntity) in.readObject(); + } catch (Exception exp) { + fail(exp.toString()); + } finally { + Utility.close(in); + } + assertEquals(entity, entity2); + } + + @Test + public void testInsertTimestamp_Calendar() { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Insert"); + AutoTimestampCalendar entity2 = em.insert(entity); + assertNotNull(entity2.getCreatedOn()); + assertNotNull(entity2.getModifiedOn()); + assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); + } + + @Test + public void testUpsertTimestamp_Calendar() { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Upsert"); + AutoTimestampCalendar entity2 = em.upsert(entity); + assertNull(entity2.getCreatedOn()); + assertNotNull(entity2.getModifiedOn()); + } + + @Test + public void testUpsertTimestamp_Calendar_2() { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Upsert with created date set on entity"); + entity.setCreatedOn(Calendar.getInstance()); + AutoTimestampCalendar entity2 = em.upsert(entity); + assertNotNull(entity2.getCreatedOn()); + assertNotNull(entity2.getModifiedOn()); + } + + @Test + public void testUpdateTimestamp_Calendar() { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Insert"); + AutoTimestampCalendar entity2 = em.insert(entity); + AutoTimestampCalendar entity3 = em.load(AutoTimestampCalendar.class, entity2.getId()); + entity3.setName("Update"); + AutoTimestampCalendar entity4 = em.update(entity3); + assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); + assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); + assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); + } + + @Test + public void testInsertTimestamp_Calendar_Multiple() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Insert " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + assertNotNull(entities2.get(0).getCreatedOn()); + assertNotNull(entities2.get(1).getCreatedOn()); + assertNotNull(entities2.get(0).getModifiedOn()); + assertNotNull(entities2.get(1).getModifiedOn()); + } + + @Test + public void testUpsertTimestamp_Calendar_Multiple() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Upsert " + i); + entities.add(entity); + } + List entities2 = em.upsert(entities); + assertNull(entities2.get(0).getCreatedOn()); + assertNull(entities2.get(1).getCreatedOn()); + assertNotNull(entities2.get(0).getModifiedOn()); + assertNotNull(entities2.get(1).getModifiedOn()); + } + + @Test + public void testUpdateTimestamp_Calendar_Multiple() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + AutoTimestampCalendar entity = new AutoTimestampCalendar(); + entity.setName("Insert Multiple " + i); + entities.add(entity); + } + List entities2 = em.insert(entities); + List keys = new ArrayList<>(entities2.size()); + for (int i = 0; i < entities2.size(); i++) { + keys.add(entities2.get(i).getId()); + } + List entities3 = em.loadById(AutoTimestampCalendar.class, keys); + for (int i = 0; i < entities3.size(); i++) { + entities3.get(i).setName("Update Multiple " + i); + keys.add(entities.get(i).getId()); + } + List entities4 = em.update(entities3); + + assertNotNull(entities4.get(0).getCreatedOn()); + assertNotNull(entities4.get(1).getCreatedOn()); + assertNotNull(entities4.get(0).getModifiedOn()); + assertNotNull(entities4.get(1).getModifiedOn()); + assertNotEquals(entities4.get(0).getCreatedOn(), entities4.get(0).getModifiedOn()); + assertNotEquals(entities4.get(1).getCreatedOn(), entities4.get(1).getModifiedOn()); + } + + @Test + public void testInsertTimestamp_Date() { + AutoTimestampDate entity = new AutoTimestampDate(); + entity.setName("Insert"); + AutoTimestampDate entity2 = em.insert(entity); + assertNotNull(entity2.getCreatedDate()); + assertNotNull(entity2.getModifiedDate()); + assertEquals(entity2.getCreatedDate(), entity2.getModifiedDate()); + } + + @Test + public void testUpsertTimestamp_Date() { + AutoTimestampDate entity = new AutoTimestampDate(); + entity.setName("Upsert"); + AutoTimestampDate entity2 = em.upsert(entity); + assertNull(entity2.getCreatedDate()); + assertNotNull(entity2.getModifiedDate()); + } + + @Test + public void testUpdateTimestamp_Date() { + AutoTimestampDate entity = new AutoTimestampDate(); + entity.setName("Insert"); + AutoTimestampDate entity2 = em.insert(entity); + AutoTimestampDate entity3 = em.load(AutoTimestampDate.class, entity2.getId()); + entity3.setName("Update"); + AutoTimestampDate entity4 = em.update(entity3); + assertEquals(entity2.getCreatedDate(), entity3.getCreatedDate()); + assertEquals(entity3.getCreatedDate(), entity4.getCreatedDate()); + assertNotEquals(entity3.getCreatedDate(), entity4.getModifiedDate()); + } + + @Test + public void testInsertTimestamp_Long() { + AutoTimestampLong entity = new AutoTimestampLong(); + entity.setName("Insert"); + AutoTimestampLong entity2 = em.insert(entity); + assertNotNull(entity2.getCreatedDate()); + assertNotNull(entity2.getModifiedDate()); + assertEquals(entity2.getCreatedDate(), entity2.getModifiedDate()); + } + + @Test + public void testUpsertTimestamp_Long() { + AutoTimestampLong entity = new AutoTimestampLong(); + entity.setName("Upsert"); + AutoTimestampLong entity2 = em.upsert(entity); + assertNull(entity2.getCreatedDate()); + assertNotNull(entity2.getModifiedDate()); + } + + @Test + public void testUpdateTimestamp_Long() { + AutoTimestampLong entity = new AutoTimestampLong(); + entity.setName("Insert"); + AutoTimestampLong entity2 = em.insert(entity); + AutoTimestampLong entity3 = em.load(AutoTimestampLong.class, entity2.getId()); + entity3.setName("Update"); + AutoTimestampLong entity4 = em.update(entity3); + assertEquals(entity2.getCreatedDate(), entity3.getCreatedDate()); + assertEquals(entity3.getCreatedDate(), entity4.getCreatedDate()); + assertNotEquals(entity3.getCreatedDate(), entity4.getModifiedDate()); + } + + @Test + public void testInsertTimestamp_OffsetDateTime() { + AutoTimestampOffsetDateTime entity = new AutoTimestampOffsetDateTime(); + entity.setName("Insert"); + AutoTimestampOffsetDateTime entity2 = em.insert(entity); + assertNotNull(entity2.getCreatedOn()); + assertNotNull(entity2.getModifiedOn()); + assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); + } + + @Test + public void testUpdateTimestamp_OffsetDateTime() { + AutoTimestampOffsetDateTime entity = new AutoTimestampOffsetDateTime(); + entity.setName("Insert"); + AutoTimestampOffsetDateTime entity2 = em.insert(entity); + AutoTimestampOffsetDateTime entity3 = em.load(AutoTimestampOffsetDateTime.class, + entity2.getId()); + entity3.setName("Update"); + AutoTimestampOffsetDateTime entity4 = em.update(entity3); + assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); + assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); + assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); + } + + @Test + public void testInsertTimestamp_ZonedDateTime() { + AutoTimestampZonedDateTime entity = new AutoTimestampZonedDateTime(); + entity.setName("Insert"); + AutoTimestampZonedDateTime entity2 = em.insert(entity); + assertNotNull(entity2.getCreatedOn()); + assertNotNull(entity2.getModifiedOn()); + assertEquals(entity2.getCreatedOn(), entity2.getModifiedOn()); + } + + @Test + public void testUpdateTimestamp_ZonedDateTime() { + AutoTimestampZonedDateTime entity = new AutoTimestampZonedDateTime(); + entity.setName("Insert"); + AutoTimestampZonedDateTime entity2 = em.insert(entity); + AutoTimestampZonedDateTime entity3 = em.load(AutoTimestampZonedDateTime.class, entity2.getId()); + entity3.setName("Update"); + AutoTimestampZonedDateTime entity4 = em.update(entity3); + assertEquals(entity2.getCreatedOn(), entity3.getCreatedOn()); + assertEquals(entity3.getCreatedOn(), entity4.getCreatedOn()); + assertNotEquals(entity3.getCreatedOn(), entity4.getModifiedOn()); + } + + @Test(expected = EntityManagerException.class) + public void testInsertProjectedEntity() { + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe"); + em.insert(entity); + } + + @Test(expected = EntityManagerException.class) + public void testInsertProjectedEntity_List() { + List entities = new ArrayList<>(5); + for (int i = 0; i < 5; i++) { + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe " + i); + entities.add(entity); + } + entities = em.insert(entities); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateProjectedEntity() { + Contact contact = Contact.createContact1(); + contact = em.insert(contact); + ContactProjection entity = em.load(ContactProjection.class, contact.getId()); + entity.setLastName("Doe Updated"); + em.update(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpdateProjectedEntity_List() { + List contacts = new ArrayList<>(5); + List ids = new ArrayList<>(5); + for (int i = 0; i < 5; i++) { + contacts.add(Contact.createContact1()); + } + contacts = em.insert(contacts); + for (Contact contact : contacts) { + ids.add(contact.getId()); + } + + List entities = em.loadById(ContactProjection.class, ids); + em.update(entities); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertProjectedEntity() { + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe"); + em.upsert(entity); + } + + @Test(expected = EntityManagerException.class) + public void testUpsertProjectedEntity_List() { + List entities = new ArrayList<>(5); + for (int i = 0; i < 5; i++) { + ContactProjection entity = new ContactProjection(); + entity.setLastName("Doe " + i); + entities.add(entity); + } + entities = em.upsert(entities); + } + + @Test + public void testDeleteProjectedEntity() { + Contact entity = Contact.createContact1(); + entity = em.insert(entity); + ContactProjection projectedEntity = em.load(ContactProjection.class, entity.getId()); + em.delete(projectedEntity); + entity = em.load(Contact.class, entity.getId()); + assertNull(entity); + assertNotNull(projectedEntity); + } + + @Test + public void testDeleteProjectedEntity_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + entities.add(Contact.createContact1()); + } + entities = em.insert(entities); + List ids = new ArrayList<>(5); + for (Contact entity : entities) { + ids.add(entity.getId()); + } + List projectedEntities = em.loadById(ContactProjection.class, ids); + em.delete(projectedEntities); + entities = em.loadById(Contact.class, ids); + assertNull(entities.get(0)); + assertNull(entities.get(1)); + assertNull(entities.get(2)); + assertNull(entities.get(3)); + assertNull(entities.get(4)); + } + + @Test + public void testQueryByLocalDate_PositionalBinding() { + em.deleteAll(LocalDateField.class); + LocalDateField entity = new LocalDateField(); + LocalDate birthDate = LocalDate.of(2007, 1, 12); + entity.setBirthDate(birthDate); + entity = em.insert(entity); + String query = "SELECT * FROM LocalDateField WHERE birthDate=@1"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBindings(birthDate); + QueryResponse response = em.executeEntityQueryRequest(LocalDateField.class, + request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByLocalDate_NamedBinding() { + em.deleteAll(LocalDateField.class); + LocalDateField entity = new LocalDateField(); + LocalDate birthDate = LocalDate.of(2007, 1, 12); + entity.setBirthDate(birthDate); + entity = em.insert(entity); + String query = "SELECT * FROM LocalDateField WHERE birthDate=@BirthDate"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.setNamedBinding("BirthDate", birthDate); + QueryResponse response = em.executeEntityQueryRequest(LocalDateField.class, + request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByLocalTime_PositionalBinding() { + em.deleteAll(LocalTimeField.class); + LocalTimeField entity = new LocalTimeField(); + LocalTime time = LocalTime.of(0, 0, 0, 1); + entity.setStartTime(time); + entity = em.insert(entity); + String query = "SELECT * FROM LocalTimeField WHERE startTime=@1"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBindings(time); + QueryResponse response = em.executeEntityQueryRequest(LocalTimeField.class, + request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByLocalTime_NamedBinding() { + em.deleteAll(LocalTimeField.class); + LocalTimeField entity = new LocalTimeField(); + LocalTime time = LocalTime.of(0, 0, 0, 1); + entity.setStartTime(time); + entity = em.insert(entity); + String query = "SELECT * FROM LocalTimeField WHERE startTime=@Time"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.setNamedBinding("Time", time); + QueryResponse response = em.executeEntityQueryRequest(LocalTimeField.class, + request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByLocalDateTime_PositionalBinding() { + em.deleteAll(LocalDateTimeField.class); + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime timestamp = LocalDateTime.of(2007, 1, 12, 10, 30, 3, 456789); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM LocalDateTimeField WHERE timestamp=@1"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBindings(timestamp); + QueryResponse response = em + .executeEntityQueryRequest(LocalDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByLocalDateTime_NamedBinding() { + em.deleteAll(LocalDateTimeField.class); + LocalDateTimeField entity = new LocalDateTimeField(); + LocalDateTime timestamp = LocalDateTime.of(1947, 8, 15, 0, 0, 0, 999999999); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM LocalDateTimeField WHERE timestamp=@ts"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.setNamedBinding("ts", timestamp); + QueryResponse response = em + .executeEntityQueryRequest(LocalDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByOffsetDateTime_PositionalBinding() { + em.deleteAll(OffsetDateTimeField.class); + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime timestamp = OffsetDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, + ZoneOffset.of("Z")); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM OffsetDateTimeField WHERE timestamp=@1"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBindings(timestamp); + QueryResponse response = em + .executeEntityQueryRequest(OffsetDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByOffsetDateTime_NamedBinding() { + em.deleteAll(OffsetDateTimeField.class); + OffsetDateTimeField entity = new OffsetDateTimeField(); + OffsetDateTime timestamp = OffsetDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, + ZoneOffset.of("Z")); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM OffsetDateTimeField WHERE timestamp=@Search"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.setNamedBinding("Search", timestamp); + QueryResponse response = em + .executeEntityQueryRequest(OffsetDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByZonedDateTime_PositionalBinding() { + em.deleteAll(ZonedDateTimeField.class); + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime timestamp = ZonedDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, + ZoneOffset.of("Z")); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM ZonedDateTimeField WHERE timestamp=@1"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBindings(timestamp); + QueryResponse response = em + .executeEntityQueryRequest(ZonedDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + @Test + public void testQueryByZonedDateTime_NamedBinding() { + em.deleteAll(ZonedDateTimeField.class); + ZonedDateTimeField entity = new ZonedDateTimeField(); + ZonedDateTime timestamp = ZonedDateTime.of(2007, 1, 12, 10, 30, 3, 456789012, + ZoneOffset.of("Z")); + entity.setTimestamp(timestamp); + entity = em.insert(entity); + String query = "SELECT * FROM ZonedDateTimeField WHERE timestamp=@Timestamp"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.setNamedBinding("Timestamp", timestamp); + QueryResponse response = em + .executeEntityQueryRequest(ZonedDateTimeField.class, request); + List entities = response.getResults(); + System.out.println(entities); + assertTrue(entities.size() == 1); + } + + // Test for a single entity + @Test + public void testAllocateId_1() { + StringField entity = new StringField(); + DatastoreKey key = em.allocateId(entity); + assertEquals(StringField.class.getSimpleName(), key.kind()); + assertTrue(key.id() > 0); + } + + // Test for single entity with a parent + @Test + public void testAllocateId_2() { + ParentEntity parentEntity = new ParentEntity(); + parentEntity.setField1("Test for allocate Id"); + parentEntity = em.insert(parentEntity); + ChildEntity childEntity = new ChildEntity(); + childEntity.setParentKey(parentEntity.getKey()); + DatastoreKey key = em.allocateId(childEntity); + assertEquals(ChildEntity.class.getSimpleName(), key.kind()); + assertEquals(key.parent(), parentEntity.getKey()); + assertTrue(key.id() > 0); + } + + // Test for multiple entities of different types + @Test + public void testAllocateId_3() { + StringField stringField = new StringField(); + LongField longField = new LongField(); + BooleanField booleanField = new BooleanField(); + User user = User.getSample1(); + List entities = new ArrayList<>(); + entities.add(stringField); + entities.add(longField); + entities.add(booleanField); + entities.add(user); + List keys = em.allocateId(entities); + assertEquals(StringField.class.getSimpleName(), keys.get(0).kind()); + assertTrue(keys.get(0).id() > 0); + assertEquals(LongField.class.getSimpleName(), keys.get(1).kind()); + assertTrue(keys.get(1).id() > 0); + assertEquals(BooleanField.class.getSimpleName(), keys.get(2).kind()); + assertTrue(keys.get(2).id() > 0); + assertEquals(User.class.getSimpleName(), keys.get(3).kind()); + assertTrue(keys.get(3).id() > 0); + } + + // Test with a String ID + @Test(expected = IllegalArgumentException.class) + public void testAllocateId_4() { + StringId entity = new StringId(); + DatastoreKey key = em.allocateId(entity); + } + + // Test with a non-zero ID + @Test(expected = IllegalArgumentException.class) + public void testAllocateId_5() { + StringField entity = new StringField(); + entity.setId(12345); + DatastoreKey key = em.allocateId(entity); + } + + // Test with a non-null ID + @Test(expected = IllegalArgumentException.class) + public void testAllocateId_6() { + LongObjectId entity = new LongObjectId(); + entity.setId(12345L); + DatastoreKey key = em.allocateId(entity); + } + + // Test with a non-null, but zero ID + @Test + public void testAllocateId_7() { + LongObjectId entity = new LongObjectId(); + entity.setId(0L); + DatastoreKey key = em.allocateId(entity); + assertEquals(LongObjectId.class.getSimpleName(), key.kind()); + assertTrue(key.id() > 0); + } + + @Test + public void testInsert_WrappedLongIdEntity() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample1(); + WrappedLongIdEntity entity2 = em.insert(entity); + assertTrue(entity2.getId().getValue() > 0); + } + + @Test + public void testUpsert_WrappedLongIdEntity() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample2(); + WrappedLongIdEntity entity2 = em.upsert(entity); + assertTrue(entity2.getId().getValue() > 0); + } + + @Test + public void testUpdate_WrappedLongIdEntity() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); + WrappedLongIdEntity entity2 = em.insert(entity); + assertTrue(entity2.getId().getValue() > 0); + entity2.setName(entity2.getName() + " - updated"); + WrappedLongIdEntity entity3 = em.update(entity2); + WrappedLongIdEntity entity4 = em.load(WrappedLongIdEntity.class, entity2.getId().getValue()); + assertEquals(entity3, entity4); + } + + @Test + public void testInsert_WrappedLongObjectIdEntity() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample1(); + WrappedLongObjectIdEntity entity2 = em.insert(entity); + assertTrue(entity2.getId().getValue() > 0); + } + + @Test + public void testUpsert_WrappedLongObjectIdEntity() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample2(); + WrappedLongObjectIdEntity entity2 = em.upsert(entity); + assertTrue(entity2.getId().getValue() > 0); + } + + @Test + public void testUpdate_WrappedLongObjectIdEntity() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample3(); + WrappedLongObjectIdEntity entity2 = em.upsert(entity); + assertTrue(entity2.getId().getValue() > 0); + entity2.setName(entity2.getName() + " - updated"); + WrappedLongObjectIdEntity entity3 = em.update(entity2); + WrappedLongObjectIdEntity entity4 = em.load(WrappedLongObjectIdEntity.class, + entity3.getId().getValue()); + assertEquals(entity3, entity4); + } + + @Test + public void testInsert_User() { + User entity = User.getSample1(); + User entity2 = em.insert(entity); + assertTrue(entity2.getId().getValue() > 0); + assertEquals(entity.getName(), entity.getName()); + } + + @Test + public void testUpsert_User() { + User entity = User.getSample2(); + User entity2 = em.insert(entity); + assertEquals(0, entity.getId().getValue()); + assertTrue(entity2.getId().getValue() > 0); + assertEquals(entity.getName(), entity.getName()); + } + + @Test + public void testInsertUserContact() { + User user = User.getSample2(); + User user2 = em.insert(user); + UserContact uc = new UserContact(); + uc.setUserKey(user2.getKey()); + uc.setContactName("John Doe"); + UserContact uc2 = em.insert(uc); + assertTrue(uc2.getId() > 0); + assertEquals(uc2.getUserKey(), user2.getKey()); + } + + @Test + public void testLoad_ByKey() { + ParentEntity entity = new ParentEntity(); + entity.setField1("test for load by key"); + entity = em.insert(entity); + ParentEntity entity2 = em.load(ParentEntity.class, entity.getKey()); + assertEquals(entity, entity2); + } + + @Test + public void testLoad_ByKeys() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ParentEntity entity = new ParentEntity(); + entity.setField1("test for load by key " + i); + entities.add(entity); + } + entities = em.insert(entities); + List keys = new ArrayList<>(entities.size()); + for (ParentEntity entity : entities) { + keys.add(entity.getKey()); + } + List loadedEntities = em.loadByKey(ParentEntity.class, keys); + assertEquals(entities, loadedEntities); + } + + @Test + public void testInsert_NestedMapEntity() { + NestedMapEntity entity = NestedMapEntity.getSample1(); + NestedMapEntity entity2 = em.insert(entity); + NestedMapEntity entity3 = em.load(NestedMapEntity.class, entity2.getId()); + assertEquals(entity.getNestedMap(), entity2.getNestedMap()); + assertEquals(entity2, entity3); + } + + @Test + public void testUpdate_NestedMapEntity() { + NestedMapEntity entity = NestedMapEntity.getSample1(); + NestedMapEntity entity2 = em.insert(entity); + NestedMapEntity entity3 = em.load(NestedMapEntity.class, entity2.getId()); + assertEquals(entity.getNestedMap(), entity2.getNestedMap()); + assertEquals(entity2, entity3); + entity3.getNestedMap().put("double", 1.0); + NestedMapEntity entity4 = em.update(entity3); + NestedMapEntity entity5 = em.load(NestedMapEntity.class, entity4.getId()); + assertEquals(entity3, entity4); + assertEquals(entity4, entity5); + } + + @Test + public void testInsert_ImmutablePerson() { + ImmutablePerson entity = ImmutablePerson.getSample1(); + ImmutablePerson entity2 = em.insert(entity); + ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); + assertTrue(entity.equalsExceptAutoGeneratedFields(entity2)); + assertEquals(entity2, entity3); + + // Checks listeners + assertTrue(entity.isPreInsertFired()); + assertFalse(entity.isPostInsertFired()); + assertFalse(entity.isPostLoadFired()); + + assertTrue(entity2.isPostInsertFired()); + assertFalse(entity2.isPreInsertFired()); + assertFalse(entity2.isPostLoadFired()); + + assertTrue(entity3.isPostLoadFired()); + assertFalse(entity3.isPreInsertFired()); + assertFalse(entity3.isPostInsertFired()); + + } + + @Test + public void testInsert_ImmutablePerson_AllNulls() { + ImmutablePerson entity = ImmutablePerson.getSample2(); + ImmutablePerson entity2 = em.insert(entity); + ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); + // assertTrue(entity.equalsExceptId(entity2)); + assertEquals(entity2, entity3); + + } + + @Test + public void testInsert_ImmutableSubClass() { + ImmutableSubClass entity = ImmutableSubClass.newBuilder().setName("Immutable SubClass").build(); + ImmutableSubClass entity2 = em.insert(entity); + ImmutableSubClass entity3 = em.load(ImmutableSubClass.class, entity2.getId()); + assertTrue(entity.equalsExceptGeneratedValues(entity2)); + assertEquals(entity2, entity3); + } + + @Test + public void testUpdate_ImmutableSubClass() { + ImmutableSubClass entity = ImmutableSubClass.newBuilder() + .setName("Immutable SubClass for Update").build(); + ImmutableSubClass entity2 = em.insert(entity); + ImmutableSubClass entity3 = em.update(entity2); + ImmutableSubClass entity4 = em.load(ImmutableSubClass.class, entity2.getId()); + assertTrue(entity.equalsExceptGeneratedValues(entity2)); + assertEquals(0L, entity2.getVersion()); + assertEquals(1L, entity3.getVersion()); + assertEquals(entity3, entity4); + } + + @Test + public void testDelete_ImmutableSubClass() { + ImmutableSubClass entity = ImmutableSubClass.newBuilder() + .setName("Immutable SubClass for Delete").build(); + ImmutableSubClass entity2 = em.insert(entity); + ImmutableSubClass entity3 = em.load(ImmutableSubClass.class, entity2.getId()); + em.delete(entity3); + ImmutableSubClass entity4 = em.load(ImmutableSubClass.class, entity3.getId()); + assertNull(entity4); + } + + @Test(expected = EntityAlreadyExistsException.class) + public void testDuplicateKey() { + StringField entity = new StringField(); + entity.setName("Dup Test"); + entity = em.insert(entity); + try { + entity = em.insert(entity); + } catch (EntityAlreadyExistsException exp) { + throw exp; + } catch (EntityManagerException exp) { + String host = ((DefaultEntityManager) em).getDatastore().getOptions().getHost(); + if (!ConnectionParameters.DEFAULT_SERVICE_URL.equals(host)) { + // Running on emulator that has a bug. + throw new EntityAlreadyExistsException(exp); + } + } + } + + private static Calendar getToday() { + Calendar today = Calendar.getInstance(); + today.set(Calendar.HOUR_OF_DAY, 0); + today.set(Calendar.MINUTE, 0); + today.set(Calendar.SECOND, 0); + today.set(Calendar.MILLISECOND, 0); + return today; + } } diff --git a/src/test/java/com/jmethods/catatumbo/ExcludeDefaultListenerTest.java b/src/test/java/com/jmethods/catatumbo/ExcludeDefaultListenerTest.java index dd4d6ba..7037fe2 100644 --- a/src/test/java/com/jmethods/catatumbo/ExcludeDefaultListenerTest.java +++ b/src/test/java/com/jmethods/catatumbo/ExcludeDefaultListenerTest.java @@ -33,204 +33,204 @@ */ public class ExcludeDefaultListenerTest { - private static EntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - em.setDefaultListeners(Subtractor.class); - } - - @Test - public void testPreAndPostInsert() { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - assertTrue(entity.getProduct() == 35); - assertTrue(entity.getProduct2() == 70); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreAndPostInsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 2, i + 4); - entities.add(entity); - } - entities = em.insert(entities); - assertTrue(entities.get(0).getSum() == 6); - assertTrue(entities.get(0).getSum2() == 12); - assertTrue(entities.get(0).getProduct() == 8); - assertTrue(entities.get(0).getProduct2() == 16); - assertTrue(entities.get(1).getSum() == 8); - assertTrue(entities.get(1).getSum2() == 16); - assertTrue(entities.get(1).getProduct() == 15); - assertTrue(entities.get(1).getProduct2() == 30); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPreAndPostUpdate() { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - assertTrue(entity.getProduct() == 18); - assertTrue(entity.getProduct2() == 54); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreAndPost_Update_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - entities = em.update(entities); - assertTrue(entities.get(0).getSum() == 1); - assertTrue(entities.get(0).getSum2() == 3); - assertTrue(entities.get(0).getProduct() == 0); - assertTrue(entities.get(0).getProduct2() == 0); - assertTrue(entities.get(1).getSum() == 3); - assertTrue(entities.get(1).getSum2() == 9); - assertTrue(entities.get(1).getProduct() == 2); - assertTrue(entities.get(1).getProduct2() == 6); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPreAndPostUpsert() { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - assertTrue(entity.getProduct() == 64); - assertTrue(entity.getProduct2() == 256); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreAndPostUpsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 6, i + 2); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.get(0).getSum() == 8); - assertTrue(entities.get(0).getSum2() == 32); - assertTrue(entities.get(0).getProduct() == 12); - assertTrue(entities.get(0).getProduct2() == 48); - assertTrue(entities.get(1).getSum() == 10); - assertTrue(entities.get(1).getSum2() == 40); - assertTrue(entities.get(1).getProduct() == 21); - assertTrue(entities.get(1).getProduct2() == 84); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPreAndPostDelete() { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - assertTrue(entity.getProduct() == 2); - assertTrue(entity.getProduct2() == 10); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreAndPostDelete_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 1, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - em.delete(entities); - assertTrue(entities.get(0).getSum() == 2); - assertTrue(entities.get(0).getSum2() == 10); - assertTrue(entities.get(0).getProduct() == 1); - assertTrue(entities.get(0).getProduct2() == 5); - assertTrue(entities.get(1).getSum() == 4); - assertTrue(entities.get(1).getSum2() == 20); - assertTrue(entities.get(1).getProduct() == 4); - assertTrue(entities.get(1).getProduct2() == 20); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPostLoad() { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(6, 9); - entity = em.insert(entity); - entity = em.load(ExternalCalculatorEntity3.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - assertTrue(entity.getProduct() == 54); - assertTrue(entity.getProduct2() == 54 * 6); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreAndPostLoad_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 5, i + 6); - entities.add(entity); - } - entities = em.insert(entities); - List ids = new ArrayList<>(); - for (ExternalCalculatorEntity3 entity : entities) { - ids.add(entity.getId()); - } - entities = em.loadById(ExternalCalculatorEntity3.class, ids); - assertTrue(entities.get(0).getSum() == 11); - assertTrue(entities.get(0).getSum2() == 66); - assertTrue(entities.get(0).getProduct() == 30); - assertTrue(entities.get(0).getProduct2() == 180); - assertTrue(entities.get(1).getSum() == 13); - assertTrue(entities.get(1).getSum2() == 78); - assertTrue(entities.get(1).getProduct() == 42); - assertTrue(entities.get(1).getProduct2() == 42 * 6); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPreAndPostLoad_Query() { - em.deleteAll(ExternalCalculatorEntity3.class); - ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(8, 9); - entity = em.insert(entity); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest( - String.format("SELECT * FROM %s WHERE __key__ = @1", ExternalCalculatorEntity3.class.getSimpleName())); - request.addPositionalBinding(entity.getKey()); - QueryResponse response = em - .executeEntityQueryRequest(ExternalCalculatorEntity3.class, request); - List entities = response.getResults(); - assertTrue(entities.get(0).getSum() == 17); - assertTrue(entities.get(0).getSum2() == 17 * 6); - assertTrue(entities.get(0).getProduct() == 72); - assertTrue(entities.get(0).getProduct2() == 72 * 6); - assertTrue(entities.get(0).getDifference() == 0); - } + private static EntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + em.setDefaultListeners(Subtractor.class); + } + + @Test + public void testPreAndPostInsert() { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + assertTrue(entity.getProduct() == 35); + assertTrue(entity.getProduct2() == 70); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreAndPostInsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 2, i + 4); + entities.add(entity); + } + entities = em.insert(entities); + assertTrue(entities.get(0).getSum() == 6); + assertTrue(entities.get(0).getSum2() == 12); + assertTrue(entities.get(0).getProduct() == 8); + assertTrue(entities.get(0).getProduct2() == 16); + assertTrue(entities.get(1).getSum() == 8); + assertTrue(entities.get(1).getSum2() == 16); + assertTrue(entities.get(1).getProduct() == 15); + assertTrue(entities.get(1).getProduct2() == 30); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPreAndPostUpdate() { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + assertTrue(entity.getProduct() == 18); + assertTrue(entity.getProduct2() == 54); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreAndPost_Update_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + entities = em.update(entities); + assertTrue(entities.get(0).getSum() == 1); + assertTrue(entities.get(0).getSum2() == 3); + assertTrue(entities.get(0).getProduct() == 0); + assertTrue(entities.get(0).getProduct2() == 0); + assertTrue(entities.get(1).getSum() == 3); + assertTrue(entities.get(1).getSum2() == 9); + assertTrue(entities.get(1).getProduct() == 2); + assertTrue(entities.get(1).getProduct2() == 6); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPreAndPostUpsert() { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + assertTrue(entity.getProduct() == 64); + assertTrue(entity.getProduct2() == 256); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreAndPostUpsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 6, i + 2); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.get(0).getSum() == 8); + assertTrue(entities.get(0).getSum2() == 32); + assertTrue(entities.get(0).getProduct() == 12); + assertTrue(entities.get(0).getProduct2() == 48); + assertTrue(entities.get(1).getSum() == 10); + assertTrue(entities.get(1).getSum2() == 40); + assertTrue(entities.get(1).getProduct() == 21); + assertTrue(entities.get(1).getProduct2() == 84); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPreAndPostDelete() { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + assertTrue(entity.getProduct() == 2); + assertTrue(entity.getProduct2() == 10); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreAndPostDelete_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 1, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + em.delete(entities); + assertTrue(entities.get(0).getSum() == 2); + assertTrue(entities.get(0).getSum2() == 10); + assertTrue(entities.get(0).getProduct() == 1); + assertTrue(entities.get(0).getProduct2() == 5); + assertTrue(entities.get(1).getSum() == 4); + assertTrue(entities.get(1).getSum2() == 20); + assertTrue(entities.get(1).getProduct() == 4); + assertTrue(entities.get(1).getProduct2() == 20); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPostLoad() { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(6, 9); + entity = em.insert(entity); + entity = em.load(ExternalCalculatorEntity3.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + assertTrue(entity.getProduct() == 54); + assertTrue(entity.getProduct2() == 54 * 6); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreAndPostLoad_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(i + 5, i + 6); + entities.add(entity); + } + entities = em.insert(entities); + List ids = new ArrayList<>(); + for (ExternalCalculatorEntity3 entity : entities) { + ids.add(entity.getId()); + } + entities = em.loadById(ExternalCalculatorEntity3.class, ids); + assertTrue(entities.get(0).getSum() == 11); + assertTrue(entities.get(0).getSum2() == 66); + assertTrue(entities.get(0).getProduct() == 30); + assertTrue(entities.get(0).getProduct2() == 180); + assertTrue(entities.get(1).getSum() == 13); + assertTrue(entities.get(1).getSum2() == 78); + assertTrue(entities.get(1).getProduct() == 42); + assertTrue(entities.get(1).getProduct2() == 42 * 6); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPreAndPostLoad_Query() { + em.deleteAll(ExternalCalculatorEntity3.class); + ExternalCalculatorEntity3 entity = new ExternalCalculatorEntity3(8, 9); + entity = em.insert(entity); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest(String.format( + "SELECT * FROM %s WHERE __key__ = @1", ExternalCalculatorEntity3.class.getSimpleName())); + request.addPositionalBinding(entity.getKey()); + QueryResponse response = em + .executeEntityQueryRequest(ExternalCalculatorEntity3.class, request); + List entities = response.getResults(); + assertTrue(entities.get(0).getSum() == 17); + assertTrue(entities.get(0).getSum2() == 17 * 6); + assertTrue(entities.get(0).getProduct() == 72); + assertTrue(entities.get(0).getProduct2() == 72 * 6); + assertTrue(entities.get(0).getDifference() == 0); + } } diff --git a/src/test/java/com/jmethods/catatumbo/ExternalListenerTest.java b/src/test/java/com/jmethods/catatumbo/ExternalListenerTest.java index f6a2f62..3826e79 100644 --- a/src/test/java/com/jmethods/catatumbo/ExternalListenerTest.java +++ b/src/test/java/com/jmethods/catatumbo/ExternalListenerTest.java @@ -29,58 +29,58 @@ */ public class ExternalListenerTest { - private static EntityManager em; + private static EntityManager em; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } - @Test - public void testPreAndPostInsert() { - ExternalCalculatorEntity entity = new ExternalCalculatorEntity(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - } + @Test + public void testPreAndPostInsert() { + ExternalCalculatorEntity entity = new ExternalCalculatorEntity(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + } - @Test - public void testPreAndPostUpdate() { - ExternalCalculatorEntity entity = new ExternalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - } + @Test + public void testPreAndPostUpdate() { + ExternalCalculatorEntity entity = new ExternalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + } - @Test - public void testPreAndPostUpsert() { - ExternalCalculatorEntity entity = new ExternalCalculatorEntity(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - } + @Test + public void testPreAndPostUpsert() { + ExternalCalculatorEntity entity = new ExternalCalculatorEntity(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + } - @Test - public void testPreAndPostDelete() { - ExternalCalculatorEntity entity = new ExternalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - } + @Test + public void testPreAndPostDelete() { + ExternalCalculatorEntity entity = new ExternalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + } - @Test - public void testPostLoad() { - ExternalCalculatorEntity entity = new ExternalCalculatorEntity(6, 9); - entity = em.insert(entity); - entity = em.load(ExternalCalculatorEntity.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - } + @Test + public void testPostLoad() { + ExternalCalculatorEntity entity = new ExternalCalculatorEntity(6, 9); + entity = em.insert(entity); + entity = em.load(ExternalCalculatorEntity.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + } } diff --git a/src/test/java/com/jmethods/catatumbo/IndexerFactoryTest.java b/src/test/java/com/jmethods/catatumbo/IndexerFactoryTest.java index 5ac2cc9..3567198 100644 --- a/src/test/java/com/jmethods/catatumbo/IndexerFactoryTest.java +++ b/src/test/java/com/jmethods/catatumbo/IndexerFactoryTest.java @@ -29,18 +29,18 @@ */ public class IndexerFactoryTest { - @Test - public void testGetIndexer_LowerCaseStringIndexer() { - Indexer i1 = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); - Indexer i2 = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); - assertTrue(i1 == i2); - } - - @Test - public void testGetIndexer_UpperCaseSringListIndexer() { - Indexer i1 = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); - Indexer i2 = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); - assertTrue(i1 == i2); - } + @Test + public void testGetIndexer_LowerCaseStringIndexer() { + Indexer i1 = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); + Indexer i2 = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); + assertTrue(i1 == i2); + } + + @Test + public void testGetIndexer_UpperCaseSringListIndexer() { + Indexer i1 = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); + Indexer i2 = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); + assertTrue(i1 == i2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/InternalListenerTest.java b/src/test/java/com/jmethods/catatumbo/InternalListenerTest.java index 388fc2d..e8e6545 100644 --- a/src/test/java/com/jmethods/catatumbo/InternalListenerTest.java +++ b/src/test/java/com/jmethods/catatumbo/InternalListenerTest.java @@ -32,171 +32,171 @@ */ public class InternalListenerTest { - private static EntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } - - @Test - public void testPreInsert() { - InternalCalculatorEntity entity = new InternalCalculatorEntity(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getProduct() == 35); - assertTrue(entity.getDifference() == 2); - } - - @Test - public void testPreInsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 2, i + 4); - entities.add(entity); - } - entities = em.insert(entities); - assertTrue(entities.get(0).getSum() == 6); - assertTrue(entities.get(0).getProduct() == 8); - assertTrue(entities.get(1).getSum() == 8); - assertTrue(entities.get(1).getProduct() == 15); - assertTrue(entities.get(0).getDifference() == -2); - assertTrue(entities.get(1).getDifference() == -2); - } - - @Test - public void testPreUpdate() { - InternalCalculatorEntity entity = new InternalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getProduct() == 18); - assertTrue(entity.getDifference() == 7); - } - - @Test - public void testPreUpdate_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - InternalCalculatorEntity entity = new InternalCalculatorEntity(i, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - entities = em.update(entities); - assertTrue(entities.get(0).getSum() == 1); - assertTrue(entities.get(0).getProduct() == 0); - assertTrue(entities.get(1).getSum() == 3); - assertTrue(entities.get(1).getProduct() == 2); - assertTrue(entities.get(0).getDifference() == -1); - assertTrue(entities.get(1).getDifference() == -1); - } - - @Test - public void testPreUpsert() { - InternalCalculatorEntity entity = new InternalCalculatorEntity(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getProduct() == 64); - assertTrue(entity.getDifference() == 0); - } - - @Test - public void testPreUpsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 6, i + 2); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.get(0).getSum() == 8); - assertTrue(entities.get(0).getProduct() == 12); - assertTrue(entities.get(1).getSum() == 10); - assertTrue(entities.get(1).getProduct() == 21); - assertTrue(entities.get(0).getDifference() == 4); - assertTrue(entities.get(1).getDifference() == 4); - } - - @Test - public void testPreDelete() { - InternalCalculatorEntity entity = new InternalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getProduct() == 2); - assertTrue(entity.getDifference() == -1); - } - - @Test - public void testPreDelete_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 1, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - em.delete(entities); - assertTrue(entities.get(0).getSum() == 2); - assertTrue(entities.get(0).getProduct() == 1); - assertTrue(entities.get(1).getSum() == 4); - assertTrue(entities.get(1).getProduct() == 4); - assertTrue(entities.get(0).getDifference() == 0); - assertTrue(entities.get(1).getDifference() == 0); - } - - @Test - public void testPostLoad() { - InternalCalculatorEntity entity = new InternalCalculatorEntity(6, 9); - entity = em.insert(entity); - entity = em.load(InternalCalculatorEntity.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getProduct() == 54); - assertTrue(entity.getDifference() == -3); - } - - @Test - public void testPostLoad_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 5, i + 6); - entities.add(entity); - } - entities = em.insert(entities); - List ids = new ArrayList<>(); - for (InternalCalculatorEntity entity : entities) { - ids.add(entity.getId()); - } - entities = em.loadById(InternalCalculatorEntity.class, ids); - assertTrue(entities.get(0).getSum() == 11); - assertTrue(entities.get(0).getProduct() == 30); - assertTrue(entities.get(1).getSum() == 13); - assertTrue(entities.get(1).getProduct() == 42); - assertTrue(entities.get(0).getDifference() == -1); - assertTrue(entities.get(1).getDifference() == -1); - } - - @Test - public void testPostLoad_Query() { - em.deleteAll(InternalCalculatorEntity.class); - InternalCalculatorEntity entity = new InternalCalculatorEntity(8, 9); - entity = em.insert(entity); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest( - String.format("SELECT * FROM %s LIMIT 1", InternalCalculatorEntity.class.getSimpleName())); - request.setAllowLiterals(true); - QueryResponse response = em.executeEntityQueryRequest(InternalCalculatorEntity.class, - request); - List entities = response.getResults(); - assertTrue(entities.get(0).getSum() == 17); - assertTrue(entities.get(0).getProduct() == 72); - assertTrue(entities.get(0).getDifference() == -1); - } + private static EntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } + + @Test + public void testPreInsert() { + InternalCalculatorEntity entity = new InternalCalculatorEntity(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getProduct() == 35); + assertTrue(entity.getDifference() == 2); + } + + @Test + public void testPreInsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 2, i + 4); + entities.add(entity); + } + entities = em.insert(entities); + assertTrue(entities.get(0).getSum() == 6); + assertTrue(entities.get(0).getProduct() == 8); + assertTrue(entities.get(1).getSum() == 8); + assertTrue(entities.get(1).getProduct() == 15); + assertTrue(entities.get(0).getDifference() == -2); + assertTrue(entities.get(1).getDifference() == -2); + } + + @Test + public void testPreUpdate() { + InternalCalculatorEntity entity = new InternalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getProduct() == 18); + assertTrue(entity.getDifference() == 7); + } + + @Test + public void testPreUpdate_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + InternalCalculatorEntity entity = new InternalCalculatorEntity(i, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + entities = em.update(entities); + assertTrue(entities.get(0).getSum() == 1); + assertTrue(entities.get(0).getProduct() == 0); + assertTrue(entities.get(1).getSum() == 3); + assertTrue(entities.get(1).getProduct() == 2); + assertTrue(entities.get(0).getDifference() == -1); + assertTrue(entities.get(1).getDifference() == -1); + } + + @Test + public void testPreUpsert() { + InternalCalculatorEntity entity = new InternalCalculatorEntity(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getProduct() == 64); + assertTrue(entity.getDifference() == 0); + } + + @Test + public void testPreUpsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 6, i + 2); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.get(0).getSum() == 8); + assertTrue(entities.get(0).getProduct() == 12); + assertTrue(entities.get(1).getSum() == 10); + assertTrue(entities.get(1).getProduct() == 21); + assertTrue(entities.get(0).getDifference() == 4); + assertTrue(entities.get(1).getDifference() == 4); + } + + @Test + public void testPreDelete() { + InternalCalculatorEntity entity = new InternalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getProduct() == 2); + assertTrue(entity.getDifference() == -1); + } + + @Test + public void testPreDelete_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 1, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + em.delete(entities); + assertTrue(entities.get(0).getSum() == 2); + assertTrue(entities.get(0).getProduct() == 1); + assertTrue(entities.get(1).getSum() == 4); + assertTrue(entities.get(1).getProduct() == 4); + assertTrue(entities.get(0).getDifference() == 0); + assertTrue(entities.get(1).getDifference() == 0); + } + + @Test + public void testPostLoad() { + InternalCalculatorEntity entity = new InternalCalculatorEntity(6, 9); + entity = em.insert(entity); + entity = em.load(InternalCalculatorEntity.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getProduct() == 54); + assertTrue(entity.getDifference() == -3); + } + + @Test + public void testPostLoad_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + InternalCalculatorEntity entity = new InternalCalculatorEntity(i + 5, i + 6); + entities.add(entity); + } + entities = em.insert(entities); + List ids = new ArrayList<>(); + for (InternalCalculatorEntity entity : entities) { + ids.add(entity.getId()); + } + entities = em.loadById(InternalCalculatorEntity.class, ids); + assertTrue(entities.get(0).getSum() == 11); + assertTrue(entities.get(0).getProduct() == 30); + assertTrue(entities.get(1).getSum() == 13); + assertTrue(entities.get(1).getProduct() == 42); + assertTrue(entities.get(0).getDifference() == -1); + assertTrue(entities.get(1).getDifference() == -1); + } + + @Test + public void testPostLoad_Query() { + em.deleteAll(InternalCalculatorEntity.class); + InternalCalculatorEntity entity = new InternalCalculatorEntity(8, 9); + entity = em.insert(entity); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest( + String.format("SELECT * FROM %s LIMIT 1", InternalCalculatorEntity.class.getSimpleName())); + request.setAllowLiterals(true); + QueryResponse response = em + .executeEntityQueryRequest(InternalCalculatorEntity.class, request); + List entities = response.getResults(); + assertTrue(entities.get(0).getSum() == 17); + assertTrue(entities.get(0).getProduct() == 72); + assertTrue(entities.get(0).getDifference() == -1); + } } diff --git a/src/test/java/com/jmethods/catatumbo/ListenerInheritanceTest.java b/src/test/java/com/jmethods/catatumbo/ListenerInheritanceTest.java index 34ba4f3..3a2e193 100644 --- a/src/test/java/com/jmethods/catatumbo/ListenerInheritanceTest.java +++ b/src/test/java/com/jmethods/catatumbo/ListenerInheritanceTest.java @@ -37,55 +37,57 @@ * */ public class ListenerInheritanceTest { - private static EntityManager em; + private static EntityManager em; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - em.setDefaultListeners(AnimalListener.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + em.setDefaultListeners(AnimalListener.class); + } - @Test - public void testPreInsert_Cat() { - Cat cat = new Cat(); - cat = em.insert(cat); - String preInsertClassName = PreInsert.class.getSimpleName(); - String expected = Animal.class.getSimpleName() + "." + preInsertClassName + "->" + Pet.class.getSimpleName() - + "." + preInsertClassName + "->" + Cat.class.getSimpleName() + "." + preInsertClassName; - assertEquals(expected, cat.getValue()); - } + @Test + public void testPreInsert_Cat() { + Cat cat = new Cat(); + cat = em.insert(cat); + String preInsertClassName = PreInsert.class.getSimpleName(); + String expected = Animal.class.getSimpleName() + "." + preInsertClassName + "->" + + Pet.class.getSimpleName() + "." + preInsertClassName + "->" + Cat.class.getSimpleName() + + "." + preInsertClassName; + assertEquals(expected, cat.getValue()); + } - @Test - public void testPreAndPostInsert_Dog() { - Dog dog = new Dog(); - dog = em.insert(dog); - String preInsertClassName = PreInsert.class.getSimpleName(); - String postInsertClassName = PostInsert.class.getSimpleName(); - String expected = Dog.class.getSimpleName() + "." + preInsertClassName + "->" + Dog.class.getSimpleName() + "." - + postInsertClassName; - assertEquals(expected, dog.getValue()); - } + @Test + public void testPreAndPostInsert_Dog() { + Dog dog = new Dog(); + dog = em.insert(dog); + String preInsertClassName = PreInsert.class.getSimpleName(); + String postInsertClassName = PostInsert.class.getSimpleName(); + String expected = Dog.class.getSimpleName() + "." + preInsertClassName + "->" + + Dog.class.getSimpleName() + "." + postInsertClassName; + assertEquals(expected, dog.getValue()); + } - @Test - public void testPreInsert_Lion() { - Lion lion = new Lion(); - lion = em.insert(lion); - String preInsertClassName = PreInsert.class.getSimpleName(); - String expected = WildAnimal.class.getSimpleName() + "." + preInsertClassName + "->" - + Lion.class.getSimpleName() + "." + preInsertClassName; - assertEquals(expected, lion.getValue()); - } + @Test + public void testPreInsert_Lion() { + Lion lion = new Lion(); + lion = em.insert(lion); + String preInsertClassName = PreInsert.class.getSimpleName(); + String expected = WildAnimal.class.getSimpleName() + "." + preInsertClassName + "->" + + Lion.class.getSimpleName() + "." + preInsertClassName; + assertEquals(expected, lion.getValue()); + } - @Test - public void testPreInsert_Cow() { - Cow cow = new Cow(); - cow = em.insert(cow); - String preInsertClassName = PreInsert.class.getSimpleName(); - String expected = AnimalListener.class.getSimpleName() + "." + preInsertClassName + "->" - + FarmAnimalListener.class.getSimpleName() + "." + preInsertClassName + "->" - + Animal.class.getSimpleName() + "." + preInsertClassName + "->" + FarmAnimal.class.getSimpleName() - + "." + preInsertClassName + "->" + Cow.class.getSimpleName() + "." + preInsertClassName; - assertEquals(expected, cow.getValue()); - } + @Test + public void testPreInsert_Cow() { + Cow cow = new Cow(); + cow = em.insert(cow); + String preInsertClassName = PreInsert.class.getSimpleName(); + String expected = AnimalListener.class.getSimpleName() + "." + preInsertClassName + "->" + + FarmAnimalListener.class.getSimpleName() + "." + preInsertClassName + "->" + + Animal.class.getSimpleName() + "." + preInsertClassName + "->" + + FarmAnimal.class.getSimpleName() + "." + preInsertClassName + "->" + + Cow.class.getSimpleName() + "." + preInsertClassName; + assertEquals(expected, cow.getValue()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/MapperFactoryTest.java b/src/test/java/com/jmethods/catatumbo/MapperFactoryTest.java index 113737d..85502e4 100644 --- a/src/test/java/com/jmethods/catatumbo/MapperFactoryTest.java +++ b/src/test/java/com/jmethods/catatumbo/MapperFactoryTest.java @@ -50,220 +50,220 @@ */ public class MapperFactoryTest { - @Test - public void testGetMapper_Boolean() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Boolean.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(boolean.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(Boolean.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(boolean.class); - assertTrue(mapper1 instanceof BooleanMapper); - assertTrue(mapper2 instanceof BooleanMapper); - assertTrue(mapper3 instanceof BooleanMapper); - assertTrue(mapper4 instanceof BooleanMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Char() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(char.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Character.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(char.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Character.class); - assertTrue(mapper1 instanceof CharMapper); - assertTrue(mapper2 instanceof CharMapper); - assertTrue(mapper3 instanceof CharMapper); - assertTrue(mapper4 instanceof CharMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Short() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(short.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Short.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(short.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Short.class); - assertTrue(mapper1 instanceof ShortMapper); - assertTrue(mapper2 instanceof ShortMapper); - assertTrue(mapper3 instanceof ShortMapper); - assertTrue(mapper4 instanceof ShortMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Integer() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(int.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Integer.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(int.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Integer.class); - assertTrue(mapper1 instanceof IntegerMapper); - assertTrue(mapper2 instanceof IntegerMapper); - assertTrue(mapper3 instanceof IntegerMapper); - assertTrue(mapper4 instanceof IntegerMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Long() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(long.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Long.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(long.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Long.class); - assertTrue(mapper1 instanceof LongMapper); - assertTrue(mapper2 instanceof LongMapper); - assertTrue(mapper3 instanceof LongMapper); - assertTrue(mapper4 instanceof LongMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Float() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(float.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Float.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(float.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Float.class); - assertTrue(mapper1 instanceof FloatMapper); - assertTrue(mapper2 instanceof FloatMapper); - assertTrue(mapper3 instanceof FloatMapper); - assertTrue(mapper4 instanceof FloatMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_Double() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(double.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Double.class); - Mapper mapper3 = MapperFactory.getInstance().getMapper(double.class); - Mapper mapper4 = MapperFactory.getInstance().getMapper(Double.class); - assertTrue(mapper1 instanceof DoubleMapper); - assertTrue(mapper2 instanceof DoubleMapper); - assertTrue(mapper3 instanceof DoubleMapper); - assertTrue(mapper4 instanceof DoubleMapper); - assertTrue(mapper1 == mapper2); - assertTrue(mapper2 == mapper3); - assertTrue(mapper3 == mapper4); - - } - - @Test - public void testGetMapper_String() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(String.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(String.class); - assertTrue(mapper1 instanceof StringMapper); - assertTrue(mapper2 instanceof StringMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_ByteArray() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(byte[].class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(byte[].class); - assertTrue(mapper1 instanceof ByteArrayMapper); - assertTrue(mapper2 instanceof ByteArrayMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_CharArray() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(char[].class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(char[].class); - assertTrue(mapper1 instanceof CharArrayMapper); - assertTrue(mapper2 instanceof CharArrayMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_GeoLocation() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(GeoLocation.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(GeoLocation.class); - assertTrue(mapper1 instanceof GeoLocationMapper); - assertTrue(mapper2 instanceof GeoLocationMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_DatastoreKey() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(DatastoreKey.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(DatastoreKey.class); - assertTrue(mapper1 instanceof KeyMapper); - assertTrue(mapper2 instanceof KeyMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_Date() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Date.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Date.class); - assertTrue(mapper1 instanceof DateMapper); - assertTrue(mapper2 instanceof DateMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_Calendar() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Calendar.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Calendar.class); - assertTrue(mapper1 instanceof CalendarMapper); - assertTrue(mapper2 instanceof CalendarMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_Enum_1() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Color.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Color.class); - assertTrue(mapper1 instanceof EnumMapper); - assertTrue(mapper2 instanceof EnumMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_Enum_2() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Size.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Size.class); - assertTrue(mapper1 instanceof EnumMapper); - assertTrue(mapper2 instanceof EnumMapper); - assertTrue(mapper1 == mapper2); - } - - @Test(expected = NoSuitableMapperException.class) - public void testGetMapper_Object() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Object.class); - } - - @Test - public void testGetMapper_Map() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(Map.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(Map.class); - assertTrue(mapper1 instanceof MapMapper); - assertTrue(mapper2 instanceof MapMapper); - assertTrue(mapper1 == mapper2); - } - - @Test - public void testGetMapper_TreeMap() { - Mapper mapper1 = MapperFactory.getInstance().getMapper(TreeMap.class); - Mapper mapper2 = MapperFactory.getInstance().getMapper(TreeMap.class); - assertTrue(mapper1 instanceof MapMapper); - assertTrue(mapper2 instanceof MapMapper); - assertTrue(mapper1 == mapper2); - } + @Test + public void testGetMapper_Boolean() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Boolean.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(boolean.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(Boolean.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(boolean.class); + assertTrue(mapper1 instanceof BooleanMapper); + assertTrue(mapper2 instanceof BooleanMapper); + assertTrue(mapper3 instanceof BooleanMapper); + assertTrue(mapper4 instanceof BooleanMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Char() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(char.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Character.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(char.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Character.class); + assertTrue(mapper1 instanceof CharMapper); + assertTrue(mapper2 instanceof CharMapper); + assertTrue(mapper3 instanceof CharMapper); + assertTrue(mapper4 instanceof CharMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Short() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(short.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Short.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(short.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Short.class); + assertTrue(mapper1 instanceof ShortMapper); + assertTrue(mapper2 instanceof ShortMapper); + assertTrue(mapper3 instanceof ShortMapper); + assertTrue(mapper4 instanceof ShortMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Integer() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(int.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Integer.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(int.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Integer.class); + assertTrue(mapper1 instanceof IntegerMapper); + assertTrue(mapper2 instanceof IntegerMapper); + assertTrue(mapper3 instanceof IntegerMapper); + assertTrue(mapper4 instanceof IntegerMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Long() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(long.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Long.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(long.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Long.class); + assertTrue(mapper1 instanceof LongMapper); + assertTrue(mapper2 instanceof LongMapper); + assertTrue(mapper3 instanceof LongMapper); + assertTrue(mapper4 instanceof LongMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Float() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(float.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Float.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(float.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Float.class); + assertTrue(mapper1 instanceof FloatMapper); + assertTrue(mapper2 instanceof FloatMapper); + assertTrue(mapper3 instanceof FloatMapper); + assertTrue(mapper4 instanceof FloatMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_Double() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(double.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Double.class); + Mapper mapper3 = MapperFactory.getInstance().getMapper(double.class); + Mapper mapper4 = MapperFactory.getInstance().getMapper(Double.class); + assertTrue(mapper1 instanceof DoubleMapper); + assertTrue(mapper2 instanceof DoubleMapper); + assertTrue(mapper3 instanceof DoubleMapper); + assertTrue(mapper4 instanceof DoubleMapper); + assertTrue(mapper1 == mapper2); + assertTrue(mapper2 == mapper3); + assertTrue(mapper3 == mapper4); + + } + + @Test + public void testGetMapper_String() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(String.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(String.class); + assertTrue(mapper1 instanceof StringMapper); + assertTrue(mapper2 instanceof StringMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_ByteArray() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(byte[].class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(byte[].class); + assertTrue(mapper1 instanceof ByteArrayMapper); + assertTrue(mapper2 instanceof ByteArrayMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_CharArray() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(char[].class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(char[].class); + assertTrue(mapper1 instanceof CharArrayMapper); + assertTrue(mapper2 instanceof CharArrayMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_GeoLocation() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(GeoLocation.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(GeoLocation.class); + assertTrue(mapper1 instanceof GeoLocationMapper); + assertTrue(mapper2 instanceof GeoLocationMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_DatastoreKey() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(DatastoreKey.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(DatastoreKey.class); + assertTrue(mapper1 instanceof KeyMapper); + assertTrue(mapper2 instanceof KeyMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_Date() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Date.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Date.class); + assertTrue(mapper1 instanceof DateMapper); + assertTrue(mapper2 instanceof DateMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_Calendar() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Calendar.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Calendar.class); + assertTrue(mapper1 instanceof CalendarMapper); + assertTrue(mapper2 instanceof CalendarMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_Enum_1() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Color.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Color.class); + assertTrue(mapper1 instanceof EnumMapper); + assertTrue(mapper2 instanceof EnumMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_Enum_2() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Size.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Size.class); + assertTrue(mapper1 instanceof EnumMapper); + assertTrue(mapper2 instanceof EnumMapper); + assertTrue(mapper1 == mapper2); + } + + @Test(expected = NoSuitableMapperException.class) + public void testGetMapper_Object() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Object.class); + } + + @Test + public void testGetMapper_Map() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(Map.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(Map.class); + assertTrue(mapper1 instanceof MapMapper); + assertTrue(mapper2 instanceof MapMapper); + assertTrue(mapper1 == mapper2); + } + + @Test + public void testGetMapper_TreeMap() { + Mapper mapper1 = MapperFactory.getInstance().getMapper(TreeMap.class); + Mapper mapper2 = MapperFactory.getInstance().getMapper(TreeMap.class); + assertTrue(mapper1 instanceof MapMapper); + assertTrue(mapper2 instanceof MapMapper); + assertTrue(mapper1 == mapper2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/OptionalFieldsTest.java b/src/test/java/com/jmethods/catatumbo/OptionalFieldsTest.java index 1e291b4..e23d296 100644 --- a/src/test/java/com/jmethods/catatumbo/OptionalFieldsTest.java +++ b/src/test/java/com/jmethods/catatumbo/OptionalFieldsTest.java @@ -45,146 +45,146 @@ public class OptionalFieldsTest { - private static EntityManager em = null; - private static Datastore datastore; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - datastore = ((DefaultEntityManager) em).getDatastore(); - } - - @Test - public void testInsert1() { - OptionalFieldsEntity entity = OptionalFieldsEntity.getSample1(); - OptionalFieldsEntity entity2 = em.insert(entity); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); - OptionalFieldsEntity entity3 = em.load(OptionalFieldsEntity.class, entity2.getId()); - assertTrue(nativeEntity.contains("mandatoryString")); - assertTrue(nativeEntity.contains("$city")); - assertTrue(nativeEntity.contains("FIELD2")); - assertTrue(nativeEntity.contains("city")); - assertTrue(nativeEntity.contains("field1")); - assertTrue(nativeEntity.contains("line1")); - assertTrue(nativeEntity.contains("line2")); - assertFalse(nativeEntity.contains("optionalBlob")); - assertFalse(nativeEntity.contains("optionalDate")); - assertFalse(nativeEntity.contains("optionalInteger")); - assertFalse(nativeEntity.contains("optionalList")); - assertFalse(nativeEntity.contains("optionalLong")); - assertFalse(nativeEntity.contains("optionalMap")); - assertFalse(nativeEntity.contains("optionalPhone")); - assertFalse(nativeEntity.contains("optionalSet")); - assertFalse(nativeEntity.contains("optionalShort")); - assertFalse(nativeEntity.contains("optionalString")); - assertTrue(nativeEntity.contains("state")); - assertTrue(nativeEntity.contains("zip")); - // Zipx is optional in the embeddable - assertFalse(nativeEntity.contains("zipx")); - - assertTrue(nativeEntity.contains("faxno")); - - assertTrue(entity.equalsExceptId(entity2)); - assertEquals(entity2, entity3); - } - - @Test - public void testInsert2() { - OptionalFieldsEntity entity = OptionalFieldsEntity.getSample2(); - OptionalFieldsEntity entity2 = em.insert(entity); - OptionalFieldsEntity entity3 = em.load(OptionalFieldsEntity.class, entity2.getId()); - assertTrue(entity.equalsExceptId(entity2)); - assertEquals(entity2, entity3); - } - - @Test - public void testInsert_PhoneList() { - OptionalFieldsEntity2 entity = OptionalFieldsEntity2.getSample1(); - OptionalFieldsEntity2 entity2 = em.insert(entity); - OptionalFieldsEntity2 entity3 = em.load(OptionalFieldsEntity2.class, entity2.getId()); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); - - List entityValues = nativeEntity.getList("phoneNumbers"); - assertTrue(entityValues.get(0).get().contains("countryCode")); - assertTrue(entityValues.get(1).get().contains("countryCode")); - assertFalse(entityValues.get(2).get().contains("countryCode")); - - assertEquals(entity.getPhoneNumbers(), entity2.getPhoneNumbers()); - assertEquals(entity.getPhoneNumbers(), entity3.getPhoneNumbers()); - } - - @Test - public void testInsert_SubClass() { - OptionalSubClass entity = new OptionalSubClass(); - OptionalSubClass entity2 = em.insert(entity); - OptionalSubClass entity3 = em.load(OptionalSubClass.class, entity2.getId()); - - Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); - assertFalse(nativeEntity.contains("createdBy")); - } - - @Test - public void testInsert_OptionalFieldsEntity3() { - OptionalFieldsEntity3 entity = new OptionalFieldsEntity3(); - entity = em.insert(entity); - Entity nativeEntity = datastore.get(entity.getKey().nativeKey()); - assertTrue(nativeEntity.contains("ccode")); - assertFalse(nativeEntity.contains("acode")); - } - - @Test - public void testInsert_OptionalVersion() { - OptionalVersion entity = new OptionalVersion(); - entity = em.insert(entity); - entity = em.update(entity); - entity = em.load(OptionalVersion.class, entity.getId()); - assertEquals(1L, entity.getVersion()); - } - - @Test - public void testInsert_OptionalCreationTimestamp() { - long now = System.currentTimeMillis(); - OptionalCreatedTimestamp entity = new OptionalCreatedTimestamp(); - entity = em.insert(entity); - entity = em.load(OptionalCreatedTimestamp.class, entity.getId()); - assertTrue(entity.getCreationTimestamp() >= now); - } - - @Test - public void testInsert_OptionalUpdatedTimestamp() { - long now = System.currentTimeMillis(); - OptionalUpdatedTimestamp entity = new OptionalUpdatedTimestamp(); - entity = em.insert(entity); - entity = em.load(OptionalUpdatedTimestamp.class, entity.getId()); - assertTrue(entity.getModificationTimestamp().getTime() >= now); - now = System.currentTimeMillis(); - entity = em.update(entity); - assertTrue(entity.getModificationTimestamp().getTime() >= now); - } - - @Test - public void testInsert_Immutable() { - ImmutablePerson entity = ImmutablePerson.getSample3(); - ImmutablePerson entity2 = em.insert(entity); - ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); - assertFalse(nativeEntity.contains("fourDigits")); - assertTrue(entity.equalsExceptAutoGeneratedFields(entity2)); - assertEquals(entity2, entity3); - - } - - @Test - public void testInsert_Immutable2() { - ImmutablePerson entity = ImmutablePerson.getSample2(); - ImmutablePerson entity2 = em.insert(entity); - ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); - com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); - assertFalse(nativeEntity.contains("fourDigits")); - assertFalse(nativeEntity.contains("phoneNumber")); - assertFalse(nativeEntity.contains("otherNumbers")); - assertEquals(entity2, entity3); - - } + private static EntityManager em = null; + private static Datastore datastore; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + datastore = ((DefaultEntityManager) em).getDatastore(); + } + + @Test + public void testInsert1() { + OptionalFieldsEntity entity = OptionalFieldsEntity.getSample1(); + OptionalFieldsEntity entity2 = em.insert(entity); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); + OptionalFieldsEntity entity3 = em.load(OptionalFieldsEntity.class, entity2.getId()); + assertTrue(nativeEntity.contains("mandatoryString")); + assertTrue(nativeEntity.contains("$city")); + assertTrue(nativeEntity.contains("FIELD2")); + assertTrue(nativeEntity.contains("city")); + assertTrue(nativeEntity.contains("field1")); + assertTrue(nativeEntity.contains("line1")); + assertTrue(nativeEntity.contains("line2")); + assertFalse(nativeEntity.contains("optionalBlob")); + assertFalse(nativeEntity.contains("optionalDate")); + assertFalse(nativeEntity.contains("optionalInteger")); + assertFalse(nativeEntity.contains("optionalList")); + assertFalse(nativeEntity.contains("optionalLong")); + assertFalse(nativeEntity.contains("optionalMap")); + assertFalse(nativeEntity.contains("optionalPhone")); + assertFalse(nativeEntity.contains("optionalSet")); + assertFalse(nativeEntity.contains("optionalShort")); + assertFalse(nativeEntity.contains("optionalString")); + assertTrue(nativeEntity.contains("state")); + assertTrue(nativeEntity.contains("zip")); + // Zipx is optional in the embeddable + assertFalse(nativeEntity.contains("zipx")); + + assertTrue(nativeEntity.contains("faxno")); + + assertTrue(entity.equalsExceptId(entity2)); + assertEquals(entity2, entity3); + } + + @Test + public void testInsert2() { + OptionalFieldsEntity entity = OptionalFieldsEntity.getSample2(); + OptionalFieldsEntity entity2 = em.insert(entity); + OptionalFieldsEntity entity3 = em.load(OptionalFieldsEntity.class, entity2.getId()); + assertTrue(entity.equalsExceptId(entity2)); + assertEquals(entity2, entity3); + } + + @Test + public void testInsert_PhoneList() { + OptionalFieldsEntity2 entity = OptionalFieldsEntity2.getSample1(); + OptionalFieldsEntity2 entity2 = em.insert(entity); + OptionalFieldsEntity2 entity3 = em.load(OptionalFieldsEntity2.class, entity2.getId()); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); + + List entityValues = nativeEntity.getList("phoneNumbers"); + assertTrue(entityValues.get(0).get().contains("countryCode")); + assertTrue(entityValues.get(1).get().contains("countryCode")); + assertFalse(entityValues.get(2).get().contains("countryCode")); + + assertEquals(entity.getPhoneNumbers(), entity2.getPhoneNumbers()); + assertEquals(entity.getPhoneNumbers(), entity3.getPhoneNumbers()); + } + + @Test + public void testInsert_SubClass() { + OptionalSubClass entity = new OptionalSubClass(); + OptionalSubClass entity2 = em.insert(entity); + OptionalSubClass entity3 = em.load(OptionalSubClass.class, entity2.getId()); + + Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); + assertFalse(nativeEntity.contains("createdBy")); + } + + @Test + public void testInsert_OptionalFieldsEntity3() { + OptionalFieldsEntity3 entity = new OptionalFieldsEntity3(); + entity = em.insert(entity); + Entity nativeEntity = datastore.get(entity.getKey().nativeKey()); + assertTrue(nativeEntity.contains("ccode")); + assertFalse(nativeEntity.contains("acode")); + } + + @Test + public void testInsert_OptionalVersion() { + OptionalVersion entity = new OptionalVersion(); + entity = em.insert(entity); + entity = em.update(entity); + entity = em.load(OptionalVersion.class, entity.getId()); + assertEquals(1L, entity.getVersion()); + } + + @Test + public void testInsert_OptionalCreationTimestamp() { + long now = System.currentTimeMillis(); + OptionalCreatedTimestamp entity = new OptionalCreatedTimestamp(); + entity = em.insert(entity); + entity = em.load(OptionalCreatedTimestamp.class, entity.getId()); + assertTrue(entity.getCreationTimestamp() >= now); + } + + @Test + public void testInsert_OptionalUpdatedTimestamp() { + long now = System.currentTimeMillis(); + OptionalUpdatedTimestamp entity = new OptionalUpdatedTimestamp(); + entity = em.insert(entity); + entity = em.load(OptionalUpdatedTimestamp.class, entity.getId()); + assertTrue(entity.getModificationTimestamp().getTime() >= now); + now = System.currentTimeMillis(); + entity = em.update(entity); + assertTrue(entity.getModificationTimestamp().getTime() >= now); + } + + @Test + public void testInsert_Immutable() { + ImmutablePerson entity = ImmutablePerson.getSample3(); + ImmutablePerson entity2 = em.insert(entity); + ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); + assertFalse(nativeEntity.contains("fourDigits")); + assertTrue(entity.equalsExceptAutoGeneratedFields(entity2)); + assertEquals(entity2, entity3); + + } + + @Test + public void testInsert_Immutable2() { + ImmutablePerson entity = ImmutablePerson.getSample2(); + ImmutablePerson entity2 = em.insert(entity); + ImmutablePerson entity3 = em.load(ImmutablePerson.class, entity2.getId()); + com.google.cloud.datastore.Entity nativeEntity = datastore.get(entity2.getKey().nativeKey()); + assertFalse(nativeEntity.contains("fourDigits")); + assertFalse(nativeEntity.contains("phoneNumber")); + assertFalse(nativeEntity.contains("otherNumbers")); + assertEquals(entity2, entity3); + + } } diff --git a/src/test/java/com/jmethods/catatumbo/SecondaryIndexTest.java b/src/test/java/com/jmethods/catatumbo/SecondaryIndexTest.java index e8394d2..8678773 100644 --- a/src/test/java/com/jmethods/catatumbo/SecondaryIndexTest.java +++ b/src/test/java/com/jmethods/catatumbo/SecondaryIndexTest.java @@ -43,99 +43,106 @@ */ public class SecondaryIndexTest { - private static EntityManager em; + private static EntityManager em; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } - @Test - public void testInsertStringIndex() { - StringIndex entity = StringIndex.getSample1(); - entity = em.insert(entity); - StringIndex loadedEntity = em.load(StringIndex.class, entity.getId()); - StringIndex2 entity2 = em.load(StringIndex2.class, entity.getId()); - assertEquals(entity, loadedEntity); - assertEquals(entity.getFirstName(), entity2.getFirstName()); - assertEquals(entity.getLastName(), entity2.getLastName()); - assertEquals(entity.getEmail(), entity2.getEmail()); - assertEquals(entity2.getFirstNameIndex(), entity.getFirstName().toLowerCase(Locale.ENGLISH)); - assertEquals(entity2.getLastNameIndex(), entity.getLastName().toUpperCase(Locale.ENGLISH)); - assertEquals(entity2.getEmailIndex(), entity.getEmail().toLowerCase(Locale.ENGLISH)); - } + @Test + public void testInsertStringIndex() { + StringIndex entity = StringIndex.getSample1(); + entity = em.insert(entity); + StringIndex loadedEntity = em.load(StringIndex.class, entity.getId()); + StringIndex2 entity2 = em.load(StringIndex2.class, entity.getId()); + assertEquals(entity, loadedEntity); + assertEquals(entity.getFirstName(), entity2.getFirstName()); + assertEquals(entity.getLastName(), entity2.getLastName()); + assertEquals(entity.getEmail(), entity2.getEmail()); + assertEquals(entity2.getFirstNameIndex(), entity.getFirstName().toLowerCase(Locale.ENGLISH)); + assertEquals(entity2.getLastNameIndex(), entity.getLastName().toUpperCase(Locale.ENGLISH)); + assertEquals(entity2.getEmailIndex(), entity.getEmail().toLowerCase(Locale.ENGLISH)); + } - @Test - public void testInsertStringIndex_Null() { - StringIndex entity = new StringIndex(); - entity = em.insert(entity); - StringIndex loadedEntity = em.load(StringIndex.class, entity.getId()); - StringIndex2 entity2 = em.load(StringIndex2.class, entity.getId()); - assertEquals(entity, loadedEntity); - assertEquals(entity.getFirstName(), entity2.getFirstName()); - assertEquals(entity.getLastName(), entity2.getLastName()); - assertEquals(entity.getEmail(), entity2.getEmail()); - assertNull(entity2.getFirstNameIndex()); - assertNull(entity2.getLastNameIndex()); - assertNull(entity2.getEmailIndex()); - } + @Test + public void testInsertStringIndex_Null() { + StringIndex entity = new StringIndex(); + entity = em.insert(entity); + StringIndex loadedEntity = em.load(StringIndex.class, entity.getId()); + StringIndex2 entity2 = em.load(StringIndex2.class, entity.getId()); + assertEquals(entity, loadedEntity); + assertEquals(entity.getFirstName(), entity2.getFirstName()); + assertEquals(entity.getLastName(), entity2.getLastName()); + assertEquals(entity.getEmail(), entity2.getEmail()); + assertNull(entity2.getFirstNameIndex()); + assertNull(entity2.getLastNameIndex()); + assertNull(entity2.getEmailIndex()); + } - @Test - public void testInsertStringListIndex() { - StringListIndex entity = StringListIndex.getSample1(); - entity = em.insert(entity); - StringListIndex loadedEntity = em.load(StringListIndex.class, entity.getId()); - StringListIndex2 entity2 = em.load(StringListIndex2.class, entity.getId()); - assertEquals(entity, loadedEntity); - assertEquals(entity.getColors().get(0).toLowerCase(Locale.ENGLISH), entity2.getColorsIndex().get(0)); - assertEquals(entity.getColors().get(1).toLowerCase(Locale.ENGLISH), entity2.getColorsIndex().get(1)); - assertEquals(entity.getColors().get(2).toLowerCase(Locale.ENGLISH), entity2.getColorsIndex().get(2)); - assertEquals(entity.getSizes().get(0).toUpperCase(Locale.ENGLISH), entity2.getSizesIndex().get(0)); - assertEquals(entity.getSizes().get(1).toUpperCase(Locale.ENGLISH), entity2.getSizesIndex().get(1)); - assertEquals(entity.getSizes().get(2).toUpperCase(Locale.ENGLISH), entity2.getSizesIndex().get(2)); - assertEquals(entity.getSizes().get(3), entity2.getSizesIndex().get(3)); - } + @Test + public void testInsertStringListIndex() { + StringListIndex entity = StringListIndex.getSample1(); + entity = em.insert(entity); + StringListIndex loadedEntity = em.load(StringListIndex.class, entity.getId()); + StringListIndex2 entity2 = em.load(StringListIndex2.class, entity.getId()); + assertEquals(entity, loadedEntity); + assertEquals(entity.getColors().get(0).toLowerCase(Locale.ENGLISH), + entity2.getColorsIndex().get(0)); + assertEquals(entity.getColors().get(1).toLowerCase(Locale.ENGLISH), + entity2.getColorsIndex().get(1)); + assertEquals(entity.getColors().get(2).toLowerCase(Locale.ENGLISH), + entity2.getColorsIndex().get(2)); + assertEquals(entity.getSizes().get(0).toUpperCase(Locale.ENGLISH), + entity2.getSizesIndex().get(0)); + assertEquals(entity.getSizes().get(1).toUpperCase(Locale.ENGLISH), + entity2.getSizesIndex().get(1)); + assertEquals(entity.getSizes().get(2).toUpperCase(Locale.ENGLISH), + entity2.getSizesIndex().get(2)); + assertEquals(entity.getSizes().get(3), entity2.getSizesIndex().get(3)); + } - @Test - public void testInsertStringSetIndex() { - StringSetIndex entity = StringSetIndex.getSample1(); - entity = em.insert(entity); - StringSetIndex loadedEntity = em.load(StringSetIndex.class, entity.getId()); - StringSetIndex2 entity2 = em.load(StringSetIndex2.class, entity.getId()); - assertEquals(entity, loadedEntity); - Iterator colors1 = entity.getColors().iterator(); - Iterator colors2 = entity2.getColorsIndex().iterator(); - Iterator sizes1 = entity.getSizes().iterator(); - Iterator sizes2 = entity2.getSizesIndex().iterator(); - assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); - assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); - assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); - assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); - assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); - assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); - assertEquals(sizes1.next(), sizes2.next()); - } + @Test + public void testInsertStringSetIndex() { + StringSetIndex entity = StringSetIndex.getSample1(); + entity = em.insert(entity); + StringSetIndex loadedEntity = em.load(StringSetIndex.class, entity.getId()); + StringSetIndex2 entity2 = em.load(StringSetIndex2.class, entity.getId()); + assertEquals(entity, loadedEntity); + Iterator colors1 = entity.getColors().iterator(); + Iterator colors2 = entity2.getColorsIndex().iterator(); + Iterator sizes1 = entity.getSizes().iterator(); + Iterator sizes2 = entity2.getSizesIndex().iterator(); + assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); + assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); + assertEquals(colors1.next().toLowerCase(Locale.ENGLISH), colors2.next()); + assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); + assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); + assertEquals(sizes1.next().toUpperCase(Locale.ENGLISH), sizes2.next()); + assertEquals(sizes1.next(), sizes2.next()); + } - @Test - public void testInsertEmbeddedListIndex() { - ParentEntity parent = new ParentEntity(); - parent.setField1("SecondaryIndex Test"); - parent = em.insert(parent); - EmbeddedListIndex entity = new EmbeddedListIndex(); - entity.setParentKey(parent.getKey()); - List
addresses = new ArrayList<>(); - addresses.add(Address.getSample1()); - addresses.add(Address.getSample2()); - addresses.add(Address.getSample3()); - entity.setAddresses(addresses); - entity = em.insert(entity); - String query = "SELECT * FROM EmbeddedListIndex WHERE __key__ HAS ANCESTOR @1 AND addresses.$city=@2"; - EntityQueryRequest request = em.createEntityQueryRequest(query); - request.addPositionalBinding(parent.getKey()); - request.addPositionalBinding("lincoln"); - QueryResponse response = em.executeEntityQueryRequest(EmbeddedListIndex.class, request); - List entities = response.getResults(); - assertEquals(1, entities.size()); - } + @Test + public void testInsertEmbeddedListIndex() { + ParentEntity parent = new ParentEntity(); + parent.setField1("SecondaryIndex Test"); + parent = em.insert(parent); + EmbeddedListIndex entity = new EmbeddedListIndex(); + entity.setParentKey(parent.getKey()); + List
addresses = new ArrayList<>(); + addresses.add(Address.getSample1()); + addresses.add(Address.getSample2()); + addresses.add(Address.getSample3()); + entity.setAddresses(addresses); + entity = em.insert(entity); + String query = "SELECT * FROM EmbeddedListIndex WHERE __key__ HAS ANCESTOR @1 AND addresses.$city=@2"; + EntityQueryRequest request = em.createEntityQueryRequest(query); + request.addPositionalBinding(parent.getKey()); + request.addPositionalBinding("lincoln"); + QueryResponse response = em + .executeEntityQueryRequest(EmbeddedListIndex.class, request); + List entities = response.getResults(); + assertEquals(1, entities.size()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/TenantTest.java b/src/test/java/com/jmethods/catatumbo/TenantTest.java index e48a0da..cf93464 100644 --- a/src/test/java/com/jmethods/catatumbo/TenantTest.java +++ b/src/test/java/com/jmethods/catatumbo/TenantTest.java @@ -27,17 +27,17 @@ */ public class TenantTest { - @Test - public void test1() { - assertNull(Tenant.getNamespace()); - } + @Test + public void test1() { + assertNull(Tenant.getNamespace()); + } - @Test - public void test2() { - String oldNamespace = Tenant.getNamespace(); - Tenant.setNamespace(Thread.currentThread().getName()); - assertEquals(Thread.currentThread().getName(), Tenant.getNamespace()); - Tenant.setNamespace(oldNamespace); - } + @Test + public void test2() { + String oldNamespace = Tenant.getNamespace(); + Tenant.setNamespace(Thread.currentThread().getName()); + assertEquals(Thread.currentThread().getName(), Tenant.getNamespace()); + Tenant.setNamespace(oldNamespace); + } } diff --git a/src/test/java/com/jmethods/catatumbo/TestUtils.java b/src/test/java/com/jmethods/catatumbo/TestUtils.java index dd89f2a..cfa3c5c 100644 --- a/src/test/java/com/jmethods/catatumbo/TestUtils.java +++ b/src/test/java/com/jmethods/catatumbo/TestUtils.java @@ -31,92 +31,94 @@ */ public class TestUtils { - private static final String ENV_PREFIX = "CATATUMBO_"; - public static final String ENV_SERVICE_URL = ENV_PREFIX + "SERVICE_URL"; - public static final String ENV_PROJECT_ID = ENV_PREFIX + "PROJECT_ID"; - public static final String ENV_NAMESPACE = ENV_PREFIX + "NAMESPACE"; - public static final String ENV_CREDENTIALS = ENV_PREFIX + "CREDENTIALS"; - public static final String ENV_CONNECTION_TIMEOUT = ENV_PREFIX + "CONNECTION_TIMEOUT"; - public static final String ENV_READ_TIMEOUT = ENV_PREFIX + "READ_TIMEOUT"; - public static final String ENV_CI = "CI"; - public static final String ENV_TRAVIS = "TRAVIS"; - private static DatastoreOptions options; - static { + private static final String ENV_PREFIX = "CATATUMBO_"; + public static final String ENV_SERVICE_URL = ENV_PREFIX + "SERVICE_URL"; + public static final String ENV_PROJECT_ID = ENV_PREFIX + "PROJECT_ID"; + public static final String ENV_NAMESPACE = ENV_PREFIX + "NAMESPACE"; + public static final String ENV_CREDENTIALS = ENV_PREFIX + "CREDENTIALS"; + public static final String ENV_CONNECTION_TIMEOUT = ENV_PREFIX + "CONNECTION_TIMEOUT"; + public static final String ENV_READ_TIMEOUT = ENV_PREFIX + "READ_TIMEOUT"; + public static final String ENV_CI = "CI"; + public static final String ENV_TRAVIS = "TRAVIS"; + private static DatastoreOptions options; + static { - if (isCI()) { - LocalDatastoreHelper helper = LocalDatastoreHelper.create(1.0); - try { - helper.start(); - } catch (Throwable t) { - t.printStackTrace(); - throw new IllegalStateException("Failed to start Datastore Emulator"); - } - options = helper.getOptions(); - } - } + if (isCI()) { + LocalDatastoreHelper helper = LocalDatastoreHelper.create(1.0); + try { + helper.start(); + } catch (Throwable t) { + t.printStackTrace(); + throw new IllegalStateException("Failed to start Datastore Emulator"); + } + options = helper.getOptions(); + } + } - public static EntityManager getEntityManager() throws FileNotFoundException { - if (isCI()) { - return getCIEntityManager(); - } - ConnectionParameters parameters = new ConnectionParameters(); - parameters.setServiceURL(System.getenv(ENV_SERVICE_URL)); - parameters.setProjectId(System.getenv(ENV_PROJECT_ID)); - parameters.setNamespace(System.getenv(ENV_NAMESPACE)); - String jsonCredentialsPath = System.getenv(ENV_CREDENTIALS); - if (!Utility.isNullOrEmpty(jsonCredentialsPath)) { - parameters.setJsonCredentialsFile(jsonCredentialsPath); - } - String connectionTimeout = System.getenv(ENV_CONNECTION_TIMEOUT); - if (!Utility.isNullOrEmpty(connectionTimeout)) { - parameters.setConnectionTimeout(Integer.parseInt(connectionTimeout)); - } - String readTimeout = System.getenv(ENV_READ_TIMEOUT); - if (!Utility.isNullOrEmpty(readTimeout)) { - parameters.setReadTimeout(Integer.parseInt(readTimeout)); - } - System.out.println(parameters); - EntityManager em = EntityManagerFactory.getInstance().createEntityManager(parameters); - Datastore ds = ((DefaultEntityManager) em).getDatastore(); - DatastoreOptions options = ds.getOptions(); - HttpTransportOptions httpTransportOptions = (HttpTransportOptions) options.getTransportOptions(); - System.out.println("***************************"); - System.out.println("DATASTORE INFORMATION"); - System.out.printf("Host: %s%n", options.getHost()); - System.out.printf("Project Id: %s%n", options.getProjectId()); - System.out.printf("Namespace: %s%n", options.getNamespace()); - System.out.printf("Credentials: %s%n", options.getCredentials()); - System.out.printf("Connection Timeout: %d%n", httpTransportOptions.getConnectTimeout()); - System.out.printf("Read Timeout: %d%n", httpTransportOptions.getReadTimeout()); - System.out.println("***************************"); - return em; + public static EntityManager getEntityManager() throws FileNotFoundException { + if (isCI()) { + return getCIEntityManager(); + } + ConnectionParameters parameters = new ConnectionParameters(); + parameters.setServiceURL(System.getenv(ENV_SERVICE_URL)); + parameters.setProjectId(System.getenv(ENV_PROJECT_ID)); + parameters.setNamespace(System.getenv(ENV_NAMESPACE)); + String jsonCredentialsPath = System.getenv(ENV_CREDENTIALS); + if (!Utility.isNullOrEmpty(jsonCredentialsPath)) { + parameters.setJsonCredentialsFile(jsonCredentialsPath); + } + String connectionTimeout = System.getenv(ENV_CONNECTION_TIMEOUT); + if (!Utility.isNullOrEmpty(connectionTimeout)) { + parameters.setConnectionTimeout(Integer.parseInt(connectionTimeout)); + } + String readTimeout = System.getenv(ENV_READ_TIMEOUT); + if (!Utility.isNullOrEmpty(readTimeout)) { + parameters.setReadTimeout(Integer.parseInt(readTimeout)); + } + System.out.println(parameters); + EntityManager em = EntityManagerFactory.getInstance().createEntityManager(parameters); + Datastore ds = ((DefaultEntityManager) em).getDatastore(); + DatastoreOptions options = ds.getOptions(); + HttpTransportOptions httpTransportOptions = (HttpTransportOptions) options + .getTransportOptions(); + System.out.println("***************************"); + System.out.println("DATASTORE INFORMATION"); + System.out.printf("Host: %s%n", options.getHost()); + System.out.printf("Project Id: %s%n", options.getProjectId()); + System.out.printf("Namespace: %s%n", options.getNamespace()); + System.out.printf("Credentials: %s%n", options.getCredentials()); + System.out.printf("Connection Timeout: %d%n", httpTransportOptions.getConnectTimeout()); + System.out.printf("Read Timeout: %d%n", httpTransportOptions.getReadTimeout()); + System.out.println("***************************"); + return em; - } + } - public static EntityManager getCIEntityManager() { - return EntityManagerFactory.getInstance().createLocalEntityManager(options.getHost(), options.getProjectId()); - } + public static EntityManager getCIEntityManager() { + return EntityManagerFactory.getInstance().createLocalEntityManager(options.getHost(), + options.getProjectId()); + } - public static boolean isCI() { - return Boolean.parseBoolean(System.getenv("CI")); - } + public static boolean isCI() { + return Boolean.parseBoolean(System.getenv("CI")); + } - public static String getRandomString(int length) { - Random random = new Random(); - StringBuilder buffer = new StringBuilder(length); - for (int i = 0; i < length; i++) { - char c = (char) ('a' + random.nextInt(26)); - buffer.append(c); - } - return buffer.toString(); + public static String getRandomString(int length) { + Random random = new Random(); + StringBuilder buffer = new StringBuilder(length); + for (int i = 0; i < length; i++) { + char c = (char) ('a' + random.nextInt(26)); + buffer.append(c); + } + return buffer.toString(); - } + } - public static byte[] getRandomBytes(int length) { - Random random = new Random(); - byte[] output = new byte[length]; - random.nextBytes(output); - return output; - } + public static byte[] getRandomBytes(int length) { + Random random = new Random(); + byte[] output = new byte[length]; + random.nextBytes(output); + return output; + } } diff --git a/src/test/java/com/jmethods/catatumbo/TwoDefaultListenersTest.java b/src/test/java/com/jmethods/catatumbo/TwoDefaultListenersTest.java index 3175a9c..0bdd0b6 100644 --- a/src/test/java/com/jmethods/catatumbo/TwoDefaultListenersTest.java +++ b/src/test/java/com/jmethods/catatumbo/TwoDefaultListenersTest.java @@ -35,189 +35,189 @@ */ public class TwoDefaultListenersTest { - private static EntityManager em; - private static Random random = new Random(); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - em.setDefaultListeners(Adder.class, Multiplier.class); - } - - @Test - public void testPreAndPostInsert() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - assertTrue(entity.getProduct() == 35); - assertTrue(entity.getProduct2() == 70); - } - - @Test - public void testPreAndPostInsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 2, i + 4); - entities.add(entity); - } - entities = em.insert(entities); - assertTrue(entities.get(0).getSum() == 6); - assertTrue(entities.get(0).getSum2() == 12); - assertTrue(entities.get(0).getProduct() == 8); - assertTrue(entities.get(0).getProduct2() == 16); - assertTrue(entities.get(1).getSum() == 8); - assertTrue(entities.get(1).getSum2() == 16); - assertTrue(entities.get(1).getProduct() == 15); - assertTrue(entities.get(1).getProduct2() == 30); - } - - @Test - public void testPreAndPostUpdate() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - assertTrue(entity.getProduct() == 18); - assertTrue(entity.getProduct2() == 54); - } - - @Test - public void testPreAndPost_Update_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - entities = em.update(entities); - assertTrue(entities.get(0).getSum() == 1); - assertTrue(entities.get(0).getSum2() == 3); - assertTrue(entities.get(0).getProduct() == 0); - assertTrue(entities.get(0).getProduct2() == 0); - assertTrue(entities.get(1).getSum() == 3); - assertTrue(entities.get(1).getSum2() == 9); - assertTrue(entities.get(1).getProduct() == 2); - assertTrue(entities.get(1).getProduct2() == 6); - } - - @Test - public void testPreAndPostUpsert() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - assertTrue(entity.getProduct() == 64); - assertTrue(entity.getProduct2() == 256); - } - - @Test - public void testPreAndPostUpsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 6, i + 2); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.get(0).getSum() == 8); - assertTrue(entities.get(0).getSum2() == 32); - assertTrue(entities.get(0).getProduct() == 12); - assertTrue(entities.get(0).getProduct2() == 48); - assertTrue(entities.get(1).getSum() == 10); - assertTrue(entities.get(1).getSum2() == 40); - assertTrue(entities.get(1).getProduct() == 21); - assertTrue(entities.get(1).getProduct2() == 84); - } - - @Test - public void testPreAndPostDelete() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - assertTrue(entity.getProduct() == 2); - assertTrue(entity.getProduct2() == 10); - } - - @Test - public void testPreAndPostDelete_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 1, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - em.delete(entities); - assertTrue(entities.get(0).getSum() == 2); - assertTrue(entities.get(0).getSum2() == 10); - assertTrue(entities.get(0).getProduct() == 1); - assertTrue(entities.get(0).getProduct2() == 5); - assertTrue(entities.get(1).getSum() == 4); - assertTrue(entities.get(1).getSum2() == 20); - assertTrue(entities.get(1).getProduct() == 4); - assertTrue(entities.get(1).getProduct2() == 20); - } - - @Test - public void testPostLoad() { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(6, 9); - entity = em.insert(entity); - entity = em.load(GlobalCalculatorEntity.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - assertTrue(entity.getProduct() == 54); - assertTrue(entity.getProduct2() == 54 * 6); - } - - @Test - public void testPreAndPostLoad_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 5, i + 6); - entities.add(entity); - } - entities = em.insert(entities); - List ids = new ArrayList<>(); - for (GlobalCalculatorEntity entity : entities) { - ids.add(entity.getId()); - } - entities = em.loadById(GlobalCalculatorEntity.class, ids); - assertTrue(entities.get(0).getSum() == 11); - assertTrue(entities.get(0).getSum2() == 66); - assertTrue(entities.get(0).getProduct() == 30); - assertTrue(entities.get(0).getProduct2() == 180); - assertTrue(entities.get(1).getSum() == 13); - assertTrue(entities.get(1).getSum2() == 78); - assertTrue(entities.get(1).getProduct() == 42); - assertTrue(entities.get(1).getProduct2() == 42 * 6); - } - - @Test - public void testPreAndPostLoad_Query() { - em.deleteAll(GlobalCalculatorEntity.class); - GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 9); - entity = em.insert(entity); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest( - String.format("SELECT * FROM %s WHERE __key__ = @1", GlobalCalculatorEntity.class.getSimpleName())); - request.addPositionalBinding(entity.getKey()); - QueryResponse response = em.executeEntityQueryRequest(GlobalCalculatorEntity.class, - request); - List entities = response.getResults(); - assertTrue(entities.get(0).getSum() == 17); - assertTrue(entities.get(0).getSum2() == 17 * 6); - assertTrue(entities.get(0).getProduct() == 72); - assertTrue(entities.get(0).getProduct2() == 72 * 6); - } + private static EntityManager em; + private static Random random = new Random(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + em.setDefaultListeners(Adder.class, Multiplier.class); + } + + @Test + public void testPreAndPostInsert() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + assertTrue(entity.getProduct() == 35); + assertTrue(entity.getProduct2() == 70); + } + + @Test + public void testPreAndPostInsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 2, i + 4); + entities.add(entity); + } + entities = em.insert(entities); + assertTrue(entities.get(0).getSum() == 6); + assertTrue(entities.get(0).getSum2() == 12); + assertTrue(entities.get(0).getProduct() == 8); + assertTrue(entities.get(0).getProduct2() == 16); + assertTrue(entities.get(1).getSum() == 8); + assertTrue(entities.get(1).getSum2() == 16); + assertTrue(entities.get(1).getProduct() == 15); + assertTrue(entities.get(1).getProduct2() == 30); + } + + @Test + public void testPreAndPostUpdate() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + assertTrue(entity.getProduct() == 18); + assertTrue(entity.getProduct2() == 54); + } + + @Test + public void testPreAndPost_Update_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + entities = em.update(entities); + assertTrue(entities.get(0).getSum() == 1); + assertTrue(entities.get(0).getSum2() == 3); + assertTrue(entities.get(0).getProduct() == 0); + assertTrue(entities.get(0).getProduct2() == 0); + assertTrue(entities.get(1).getSum() == 3); + assertTrue(entities.get(1).getSum2() == 9); + assertTrue(entities.get(1).getProduct() == 2); + assertTrue(entities.get(1).getProduct2() == 6); + } + + @Test + public void testPreAndPostUpsert() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + assertTrue(entity.getProduct() == 64); + assertTrue(entity.getProduct2() == 256); + } + + @Test + public void testPreAndPostUpsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 6, i + 2); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.get(0).getSum() == 8); + assertTrue(entities.get(0).getSum2() == 32); + assertTrue(entities.get(0).getProduct() == 12); + assertTrue(entities.get(0).getProduct2() == 48); + assertTrue(entities.get(1).getSum() == 10); + assertTrue(entities.get(1).getSum2() == 40); + assertTrue(entities.get(1).getProduct() == 21); + assertTrue(entities.get(1).getProduct2() == 84); + } + + @Test + public void testPreAndPostDelete() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + assertTrue(entity.getProduct() == 2); + assertTrue(entity.getProduct2() == 10); + } + + @Test + public void testPreAndPostDelete_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 1, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + em.delete(entities); + assertTrue(entities.get(0).getSum() == 2); + assertTrue(entities.get(0).getSum2() == 10); + assertTrue(entities.get(0).getProduct() == 1); + assertTrue(entities.get(0).getProduct2() == 5); + assertTrue(entities.get(1).getSum() == 4); + assertTrue(entities.get(1).getSum2() == 20); + assertTrue(entities.get(1).getProduct() == 4); + assertTrue(entities.get(1).getProduct2() == 20); + } + + @Test + public void testPostLoad() { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(6, 9); + entity = em.insert(entity); + entity = em.load(GlobalCalculatorEntity.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + assertTrue(entity.getProduct() == 54); + assertTrue(entity.getProduct2() == 54 * 6); + } + + @Test + public void testPreAndPostLoad_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(i + 5, i + 6); + entities.add(entity); + } + entities = em.insert(entities); + List ids = new ArrayList<>(); + for (GlobalCalculatorEntity entity : entities) { + ids.add(entity.getId()); + } + entities = em.loadById(GlobalCalculatorEntity.class, ids); + assertTrue(entities.get(0).getSum() == 11); + assertTrue(entities.get(0).getSum2() == 66); + assertTrue(entities.get(0).getProduct() == 30); + assertTrue(entities.get(0).getProduct2() == 180); + assertTrue(entities.get(1).getSum() == 13); + assertTrue(entities.get(1).getSum2() == 78); + assertTrue(entities.get(1).getProduct() == 42); + assertTrue(entities.get(1).getProduct2() == 42 * 6); + } + + @Test + public void testPreAndPostLoad_Query() { + em.deleteAll(GlobalCalculatorEntity.class); + GlobalCalculatorEntity entity = new GlobalCalculatorEntity(8, 9); + entity = em.insert(entity); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest(String.format( + "SELECT * FROM %s WHERE __key__ = @1", GlobalCalculatorEntity.class.getSimpleName())); + request.addPositionalBinding(entity.getKey()); + QueryResponse response = em + .executeEntityQueryRequest(GlobalCalculatorEntity.class, request); + List entities = response.getResults(); + assertTrue(entities.get(0).getSum() == 17); + assertTrue(entities.get(0).getSum2() == 17 * 6); + assertTrue(entities.get(0).getProduct() == 72); + assertTrue(entities.get(0).getProduct2() == 72 * 6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/TwoExternalListenersTest.java b/src/test/java/com/jmethods/catatumbo/TwoExternalListenersTest.java index e5a095f..4615213 100644 --- a/src/test/java/com/jmethods/catatumbo/TwoExternalListenersTest.java +++ b/src/test/java/com/jmethods/catatumbo/TwoExternalListenersTest.java @@ -32,187 +32,187 @@ */ public class TwoExternalListenersTest { - private static EntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = TestUtils.getEntityManager(); - } - - @Test - public void testPreAndPostInsert() { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(7, 5); - entity = em.insert(entity); - assertTrue(entity.getSum() == 12); - assertTrue(entity.getSum2() == 24); - assertTrue(entity.getProduct() == 35); - assertTrue(entity.getProduct2() == 70); - } - - @Test - public void testPreAndPostInsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 2, i + 4); - entities.add(entity); - } - entities = em.insert(entities); - assertTrue(entities.get(0).getSum() == 6); - assertTrue(entities.get(0).getSum2() == 12); - assertTrue(entities.get(0).getProduct() == 8); - assertTrue(entities.get(0).getProduct2() == 16); - assertTrue(entities.get(1).getSum() == 8); - assertTrue(entities.get(1).getSum2() == 16); - assertTrue(entities.get(1).getProduct() == 15); - assertTrue(entities.get(1).getProduct2() == 30); - } - - @Test - public void testPreAndPostUpdate() { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(); - entity = em.insert(entity); - entity.setOperand1(9); - entity.setOperand2(2); - entity = em.update(entity); - assertTrue(entity.getSum() == 11); - assertTrue(entity.getSum2() == 33); - assertTrue(entity.getProduct() == 18); - assertTrue(entity.getProduct2() == 54); - } - - @Test - public void testPreAndPost_Update_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - entities = em.update(entities); - assertTrue(entities.get(0).getSum() == 1); - assertTrue(entities.get(0).getSum2() == 3); - assertTrue(entities.get(0).getProduct() == 0); - assertTrue(entities.get(0).getProduct2() == 0); - assertTrue(entities.get(1).getSum() == 3); - assertTrue(entities.get(1).getSum2() == 9); - assertTrue(entities.get(1).getProduct() == 2); - assertTrue(entities.get(1).getProduct2() == 6); - } - - @Test - public void testPreAndPostUpsert() { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(8, 8); - entity = em.upsert(entity); - assertTrue(entity.getSum() == 16); - assertTrue(entity.getSum2() == 64); - assertTrue(entity.getProduct() == 64); - assertTrue(entity.getProduct2() == 256); - } - - @Test - public void testPreAndPostUpsert_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 6, i + 2); - entities.add(entity); - } - entities = em.upsert(entities); - assertTrue(entities.get(0).getSum() == 8); - assertTrue(entities.get(0).getSum2() == 32); - assertTrue(entities.get(0).getProduct() == 12); - assertTrue(entities.get(0).getProduct2() == 48); - assertTrue(entities.get(1).getSum() == 10); - assertTrue(entities.get(1).getSum2() == 40); - assertTrue(entities.get(1).getProduct() == 21); - assertTrue(entities.get(1).getProduct2() == 84); - } - - @Test - public void testPreAndPostDelete() { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(); - entity = em.insert(entity); - entity.setOperand1(1); - entity.setOperand2(2); - em.delete(entity); - assertTrue(entity.getSum() == 3); - assertTrue(entity.getSum2() == 15); - assertTrue(entity.getProduct() == 2); - assertTrue(entity.getProduct2() == 10); - } - - @Test - public void testPreAndPostDelete_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 1, i + 1); - entities.add(entity); - } - entities = em.insert(entities); - em.delete(entities); - assertTrue(entities.get(0).getSum() == 2); - assertTrue(entities.get(0).getSum2() == 10); - assertTrue(entities.get(0).getProduct() == 1); - assertTrue(entities.get(0).getProduct2() == 5); - assertTrue(entities.get(1).getSum() == 4); - assertTrue(entities.get(1).getSum2() == 20); - assertTrue(entities.get(1).getProduct() == 4); - assertTrue(entities.get(1).getProduct2() == 20); - } - - @Test - public void testPostLoad() { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(6, 9); - entity = em.insert(entity); - entity = em.load(ExternalCalculatorEntity2.class, entity.getId()); - assertTrue(entity.getSum() == 15); - assertTrue(entity.getSum2() == 90); - assertTrue(entity.getProduct() == 54); - assertTrue(entity.getProduct2() == 54 * 6); - } - - @Test - public void testPreAndPostLoad_List() { - List entities = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 5, i + 6); - entities.add(entity); - } - entities = em.insert(entities); - List ids = new ArrayList<>(); - for (ExternalCalculatorEntity2 entity : entities) { - ids.add(entity.getId()); - } - entities = em.loadById(ExternalCalculatorEntity2.class, ids); - assertTrue(entities.get(0).getSum() == 11); - assertTrue(entities.get(0).getSum2() == 66); - assertTrue(entities.get(0).getProduct() == 30); - assertTrue(entities.get(0).getProduct2() == 180); - assertTrue(entities.get(1).getSum() == 13); - assertTrue(entities.get(1).getSum2() == 78); - assertTrue(entities.get(1).getProduct() == 42); - assertTrue(entities.get(1).getProduct2() == 42 * 6); - } - - @Test - public void testPreAndPostLoad_Query() { - em.deleteAll(ExternalCalculatorEntity2.class); - ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(8, 9); - entity = em.insert(entity); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - EntityQueryRequest request = em.createEntityQueryRequest( - String.format("SELECT * FROM %s WHERE __key__=@1", ExternalCalculatorEntity2.class.getSimpleName())); - request.addPositionalBinding(entity.getKey()); - QueryResponse response = em - .executeEntityQueryRequest(ExternalCalculatorEntity2.class, request); - List entities = response.getResults(); - assertTrue(entities.get(0).getSum() == 17); - assertTrue(entities.get(0).getSum2() == 17 * 6); - assertTrue(entities.get(0).getProduct() == 72); - assertTrue(entities.get(0).getProduct2() == 72 * 6); - } + private static EntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = TestUtils.getEntityManager(); + } + + @Test + public void testPreAndPostInsert() { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(7, 5); + entity = em.insert(entity); + assertTrue(entity.getSum() == 12); + assertTrue(entity.getSum2() == 24); + assertTrue(entity.getProduct() == 35); + assertTrue(entity.getProduct2() == 70); + } + + @Test + public void testPreAndPostInsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 2, i + 4); + entities.add(entity); + } + entities = em.insert(entities); + assertTrue(entities.get(0).getSum() == 6); + assertTrue(entities.get(0).getSum2() == 12); + assertTrue(entities.get(0).getProduct() == 8); + assertTrue(entities.get(0).getProduct2() == 16); + assertTrue(entities.get(1).getSum() == 8); + assertTrue(entities.get(1).getSum2() == 16); + assertTrue(entities.get(1).getProduct() == 15); + assertTrue(entities.get(1).getProduct2() == 30); + } + + @Test + public void testPreAndPostUpdate() { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(); + entity = em.insert(entity); + entity.setOperand1(9); + entity.setOperand2(2); + entity = em.update(entity); + assertTrue(entity.getSum() == 11); + assertTrue(entity.getSum2() == 33); + assertTrue(entity.getProduct() == 18); + assertTrue(entity.getProduct2() == 54); + } + + @Test + public void testPreAndPost_Update_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + entities = em.update(entities); + assertTrue(entities.get(0).getSum() == 1); + assertTrue(entities.get(0).getSum2() == 3); + assertTrue(entities.get(0).getProduct() == 0); + assertTrue(entities.get(0).getProduct2() == 0); + assertTrue(entities.get(1).getSum() == 3); + assertTrue(entities.get(1).getSum2() == 9); + assertTrue(entities.get(1).getProduct() == 2); + assertTrue(entities.get(1).getProduct2() == 6); + } + + @Test + public void testPreAndPostUpsert() { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(8, 8); + entity = em.upsert(entity); + assertTrue(entity.getSum() == 16); + assertTrue(entity.getSum2() == 64); + assertTrue(entity.getProduct() == 64); + assertTrue(entity.getProduct2() == 256); + } + + @Test + public void testPreAndPostUpsert_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 6, i + 2); + entities.add(entity); + } + entities = em.upsert(entities); + assertTrue(entities.get(0).getSum() == 8); + assertTrue(entities.get(0).getSum2() == 32); + assertTrue(entities.get(0).getProduct() == 12); + assertTrue(entities.get(0).getProduct2() == 48); + assertTrue(entities.get(1).getSum() == 10); + assertTrue(entities.get(1).getSum2() == 40); + assertTrue(entities.get(1).getProduct() == 21); + assertTrue(entities.get(1).getProduct2() == 84); + } + + @Test + public void testPreAndPostDelete() { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(); + entity = em.insert(entity); + entity.setOperand1(1); + entity.setOperand2(2); + em.delete(entity); + assertTrue(entity.getSum() == 3); + assertTrue(entity.getSum2() == 15); + assertTrue(entity.getProduct() == 2); + assertTrue(entity.getProduct2() == 10); + } + + @Test + public void testPreAndPostDelete_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 1, i + 1); + entities.add(entity); + } + entities = em.insert(entities); + em.delete(entities); + assertTrue(entities.get(0).getSum() == 2); + assertTrue(entities.get(0).getSum2() == 10); + assertTrue(entities.get(0).getProduct() == 1); + assertTrue(entities.get(0).getProduct2() == 5); + assertTrue(entities.get(1).getSum() == 4); + assertTrue(entities.get(1).getSum2() == 20); + assertTrue(entities.get(1).getProduct() == 4); + assertTrue(entities.get(1).getProduct2() == 20); + } + + @Test + public void testPostLoad() { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(6, 9); + entity = em.insert(entity); + entity = em.load(ExternalCalculatorEntity2.class, entity.getId()); + assertTrue(entity.getSum() == 15); + assertTrue(entity.getSum2() == 90); + assertTrue(entity.getProduct() == 54); + assertTrue(entity.getProduct2() == 54 * 6); + } + + @Test + public void testPreAndPostLoad_List() { + List entities = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(i + 5, i + 6); + entities.add(entity); + } + entities = em.insert(entities); + List ids = new ArrayList<>(); + for (ExternalCalculatorEntity2 entity : entities) { + ids.add(entity.getId()); + } + entities = em.loadById(ExternalCalculatorEntity2.class, ids); + assertTrue(entities.get(0).getSum() == 11); + assertTrue(entities.get(0).getSum2() == 66); + assertTrue(entities.get(0).getProduct() == 30); + assertTrue(entities.get(0).getProduct2() == 180); + assertTrue(entities.get(1).getSum() == 13); + assertTrue(entities.get(1).getSum2() == 78); + assertTrue(entities.get(1).getProduct() == 42); + assertTrue(entities.get(1).getProduct2() == 42 * 6); + } + + @Test + public void testPreAndPostLoad_Query() { + em.deleteAll(ExternalCalculatorEntity2.class); + ExternalCalculatorEntity2 entity = new ExternalCalculatorEntity2(8, 9); + entity = em.insert(entity); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + EntityQueryRequest request = em.createEntityQueryRequest(String.format( + "SELECT * FROM %s WHERE __key__=@1", ExternalCalculatorEntity2.class.getSimpleName())); + request.addPositionalBinding(entity.getKey()); + QueryResponse response = em + .executeEntityQueryRequest(ExternalCalculatorEntity2.class, request); + List entities = response.getResults(); + assertTrue(entities.get(0).getSum() == 17); + assertTrue(entities.get(0).getSum2() == 17 * 6); + assertTrue(entities.get(0).getProduct() == 72); + assertTrue(entities.get(0).getProduct2() == 72 * 6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/custommappers/ByteMapper.java b/src/test/java/com/jmethods/catatumbo/custommappers/ByteMapper.java index 6ca02e5..dd7bfcd 100644 --- a/src/test/java/com/jmethods/catatumbo/custommappers/ByteMapper.java +++ b/src/test/java/com/jmethods/catatumbo/custommappers/ByteMapper.java @@ -24,32 +24,32 @@ import com.jmethods.catatumbo.MappingException; /** - * An implementation of {@link Mapper} for mapping primitive and wrapper byte - * types to/from the Cloud Datastore. + * An implementation of {@link Mapper} for mapping primitive and wrapper byte types to/from the + * Cloud Datastore. * * @author Sai Pullabhotla * */ public class ByteMapper implements Mapper { - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - return LongValue.newBuilder((byte) input); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + return LongValue.newBuilder((byte) input); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - Long l = ((LongValue) input).get(); - if (l < Byte.MIN_VALUE || l > Byte.MAX_VALUE) { - throw new MappingException(String.format("Value %d is out of range for byte type", l)); - } - return l.byteValue(); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + Long l = ((LongValue) input).get(); + if (l < Byte.MIN_VALUE || l > Byte.MAX_VALUE) { + throw new MappingException(String.format("Value %d is out of range for byte type", l)); + } + return l.byteValue(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/custommappers/CurrencyMapper.java b/src/test/java/com/jmethods/catatumbo/custommappers/CurrencyMapper.java index 0699479..19d33ae 100644 --- a/src/test/java/com/jmethods/catatumbo/custommappers/CurrencyMapper.java +++ b/src/test/java/com/jmethods/catatumbo/custommappers/CurrencyMapper.java @@ -27,54 +27,54 @@ import com.jmethods.catatumbo.MappingException;; /** - * A custom mapper for testing the custom mapper functionality. This mapper maps - * a BigDecimal type to an Integer property in the Cloud Datastore. + * A custom mapper for testing the custom mapper functionality. This mapper maps a BigDecimal type + * to an Integer property in the Cloud Datastore. * * @author Sai Pullabhotla * */ public class CurrencyMapper implements Mapper { - /** - * Fractional digits - */ - private int fractionalDigits; + /** + * Fractional digits + */ + private int fractionalDigits; - /** - * Creates a new instance of CurrencyMapper. - * - * @param field - * the field to which this mapper is to be attached. - */ - public CurrencyMapper(Field field) { - if (!field.getType().equals(BigDecimal.class)) { - throw new IllegalArgumentException("Field type must be BigDecimal"); - } - this.fractionalDigits = 2; - } + /** + * Creates a new instance of CurrencyMapper. + * + * @param field + * the field to which this mapper is to be attached. + */ + public CurrencyMapper(Field field) { + if (!field.getType().equals(BigDecimal.class)) { + throw new IllegalArgumentException("Field type must be BigDecimal"); + } + this.fractionalDigits = 2; + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - try { - BigDecimal n = (BigDecimal) input; - n = n.movePointRight(fractionalDigits); - return LongValue.newBuilder(n.longValueExact()); - } catch (Exception e) { - throw new MappingException(e); - } - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + try { + BigDecimal n = (BigDecimal) input; + n = n.movePointRight(fractionalDigits); + return LongValue.newBuilder(n.longValueExact()); + } catch (Exception e) { + throw new MappingException(e); + } + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - BigDecimal n = new BigDecimal(((LongValue) input).get()); - n = n.movePointLeft(fractionalDigits); - return n; - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + BigDecimal n = new BigDecimal(((LongValue) input).get()); + n = n.movePointLeft(fractionalDigits); + return n; + } } diff --git a/src/test/java/com/jmethods/catatumbo/custommappers/DeviceTypeMapper.java b/src/test/java/com/jmethods/catatumbo/custommappers/DeviceTypeMapper.java index 3b21854..fb2e209 100644 --- a/src/test/java/com/jmethods/catatumbo/custommappers/DeviceTypeMapper.java +++ b/src/test/java/com/jmethods/catatumbo/custommappers/DeviceTypeMapper.java @@ -29,29 +29,29 @@ */ public class DeviceTypeMapper implements Mapper { - /** - * Creates a new instance of DeviceTypeMapper. - */ - public DeviceTypeMapper() { - System.out.println("Creating DeviceTypeMapper"); - } + /** + * Creates a new instance of DeviceTypeMapper. + */ + public DeviceTypeMapper() { + System.out.println("Creating DeviceTypeMapper"); + } - @Override - public ValueBuilder toDatastore(Object input) { - if (input == null) { - return NullValue.newBuilder(); - } - String s = ((DeviceType) input).toString().toLowerCase(); - return StringValue.newBuilder(s); - } + @Override + public ValueBuilder toDatastore(Object input) { + if (input == null) { + return NullValue.newBuilder(); + } + String s = ((DeviceType) input).toString().toLowerCase(); + return StringValue.newBuilder(s); + } - @Override - public Object toModel(Value input) { - if (input instanceof NullValue) { - return null; - } - String s = ((StringValue) input).get(); - return Enum.valueOf(DeviceType.class, s.toUpperCase()); - } + @Override + public Object toModel(Value input) { + if (input instanceof NullValue) { + return null; + } + String s = ((StringValue) input).get(); + return Enum.valueOf(DeviceType.class, s.toUpperCase()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AccessorTestEntity.java b/src/test/java/com/jmethods/catatumbo/entities/AccessorTestEntity.java index 7fa14b2..2646489 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AccessorTestEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AccessorTestEntity.java @@ -27,269 +27,270 @@ @Entity public class AccessorTestEntity { - @Identifier - private long id; - - private int a; - private int ab; - @Property(name = "xy") - private int xY; - private int URL; - private int IPAddress; - private int a1; - private int $name; - private int myLongVariableName; - private int $12; - private int $$$; - private int _a; - private int _eventId; - private int __; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the a - */ - public int getA() { - return a; - } - - /** - * @param a - * the a to set - */ - public void setA(int a) { - this.a = a; - } - - /** - * @return the ab - */ - public int getAb() { - return ab; - } - - /** - * @param ab - * the ab to set - */ - public void setAb(int ab) { - this.ab = ab; - } - - /** - * @return the xY - */ - public int getxY() { - return xY; - } - - /** - * @param xY - * the xY to set - */ - public void setxY(int xY) { - this.xY = xY; - } - - /** - * @return the uRL - */ - public int getURL() { - return URL; - } - - /** - * @param uRL - * the uRL to set - */ - public void setURL(int uRL) { - URL = uRL; - } - - /** - * @return the iPAddress - */ - public int getIPAddress() { - return IPAddress; - } - - /** - * @param iPAddress - * the iPAddress to set - */ - public void setIPAddress(int iPAddress) { - IPAddress = iPAddress; - } - - /** - * @return the a1 - */ - public int getA1() { - return a1; - } - - /** - * @param a1 - * the a1 to set - */ - public void setA1(int a1) { - this.a1 = a1; - } - - /** - * @return the $name - */ - public int get$name() { - return $name; - } - - /** - * @param $name - * the $name to set - */ - public void set$name(int $name) { - this.$name = $name; - } - - /** - * @return the myLongVariableName - */ - public int getMyLongVariableName() { - return myLongVariableName; - } - - /** - * @param myLongVariableName - * the myLongVariableName to set - */ - public void setMyLongVariableName(int myLongVariableName) { - this.myLongVariableName = myLongVariableName; - } - - /** - * @return the $12 - */ - public int get$12() { - return $12; - } - - /** - * @param $12 - * the $12 to set - */ - public void set$12(int $12) { - this.$12 = $12; - } - - /** - * @return the $$$ - */ - public int get$$$() { - return $$$; - } - - /** - * @param $$$ - * the $$$ to set - */ - public void set$$$(int $$$) { - this.$$$ = $$$; - } - - /** - * @return the _a - */ - public int get_a() { - return _a; - } - - /** - * @param _a - * the _a to set - */ - public void set_a(int _a) { - this._a = _a; - } - - /** - * @return the _eventId - */ - public int get_eventId() { - return _eventId; - } - - /** - * @param _eventId - * the _eventId to set - */ - public void set_eventId(int _eventId) { - this._eventId = _eventId; - } - - /** - * @return the __ - */ - public int get__() { - return __; - } - - /** - * @param __ - * the __ to set - */ - public void set__(int __) { - this.__ = __; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof AccessorTestEntity)) { - return false; - } - if (obj == this) { - return true; - } - AccessorTestEntity that = (AccessorTestEntity) obj; - return this.id == that.id && this.equalsExceptId(that); - } - - public boolean equalsExceptId(AccessorTestEntity that) { - return this.$$$ == that.$$$ && this.$12 == that.$12 && this.$name == that.$name && this.__ == that.__ - && this._a == that._a && this._eventId == that._eventId && this.a == that.a && this.a1 == that.a1 - && this.ab == that.ab && this.IPAddress == that.IPAddress - && this.myLongVariableName == that.myLongVariableName && this.URL == that.URL && this.xY == that.xY; - } - - public static AccessorTestEntity getSample1() { - AccessorTestEntity entity = new AccessorTestEntity(); - entity.$$$ = 1; - entity.$12 = 2; - entity.$name = 3; - entity.__ = 4; - entity._a = 5; - entity._eventId = 6; - entity.a = 7; - entity.a1 = 8; - entity.ab = 9; - entity.IPAddress = 10; - entity.myLongVariableName = 11; - entity.URL = 12; - entity.xY = 13; - return entity; - } + @Identifier + private long id; + + private int a; + private int ab; + @Property(name = "xy") + private int xY; + private int URL; + private int IPAddress; + private int a1; + private int $name; + private int myLongVariableName; + private int $12; + private int $$$; + private int _a; + private int _eventId; + private int __; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the a + */ + public int getA() { + return a; + } + + /** + * @param a + * the a to set + */ + public void setA(int a) { + this.a = a; + } + + /** + * @return the ab + */ + public int getAb() { + return ab; + } + + /** + * @param ab + * the ab to set + */ + public void setAb(int ab) { + this.ab = ab; + } + + /** + * @return the xY + */ + public int getxY() { + return xY; + } + + /** + * @param xY + * the xY to set + */ + public void setxY(int xY) { + this.xY = xY; + } + + /** + * @return the uRL + */ + public int getURL() { + return URL; + } + + /** + * @param uRL + * the uRL to set + */ + public void setURL(int uRL) { + URL = uRL; + } + + /** + * @return the iPAddress + */ + public int getIPAddress() { + return IPAddress; + } + + /** + * @param iPAddress + * the iPAddress to set + */ + public void setIPAddress(int iPAddress) { + IPAddress = iPAddress; + } + + /** + * @return the a1 + */ + public int getA1() { + return a1; + } + + /** + * @param a1 + * the a1 to set + */ + public void setA1(int a1) { + this.a1 = a1; + } + + /** + * @return the $name + */ + public int get$name() { + return $name; + } + + /** + * @param $name + * the $name to set + */ + public void set$name(int $name) { + this.$name = $name; + } + + /** + * @return the myLongVariableName + */ + public int getMyLongVariableName() { + return myLongVariableName; + } + + /** + * @param myLongVariableName + * the myLongVariableName to set + */ + public void setMyLongVariableName(int myLongVariableName) { + this.myLongVariableName = myLongVariableName; + } + + /** + * @return the $12 + */ + public int get$12() { + return $12; + } + + /** + * @param $12 + * the $12 to set + */ + public void set$12(int $12) { + this.$12 = $12; + } + + /** + * @return the $$$ + */ + public int get$$$() { + return $$$; + } + + /** + * @param $$$ + * the $$$ to set + */ + public void set$$$(int $$$) { + this.$$$ = $$$; + } + + /** + * @return the _a + */ + public int get_a() { + return _a; + } + + /** + * @param _a + * the _a to set + */ + public void set_a(int _a) { + this._a = _a; + } + + /** + * @return the _eventId + */ + public int get_eventId() { + return _eventId; + } + + /** + * @param _eventId + * the _eventId to set + */ + public void set_eventId(int _eventId) { + this._eventId = _eventId; + } + + /** + * @return the __ + */ + public int get__() { + return __; + } + + /** + * @param __ + * the __ to set + */ + public void set__(int __) { + this.__ = __; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof AccessorTestEntity)) { + return false; + } + if (obj == this) { + return true; + } + AccessorTestEntity that = (AccessorTestEntity) obj; + return this.id == that.id && this.equalsExceptId(that); + } + + public boolean equalsExceptId(AccessorTestEntity that) { + return this.$$$ == that.$$$ && this.$12 == that.$12 && this.$name == that.$name + && this.__ == that.__ && this._a == that._a && this._eventId == that._eventId + && this.a == that.a && this.a1 == that.a1 && this.ab == that.ab + && this.IPAddress == that.IPAddress && this.myLongVariableName == that.myLongVariableName + && this.URL == that.URL && this.xY == that.xY; + } + + public static AccessorTestEntity getSample1() { + AccessorTestEntity entity = new AccessorTestEntity(); + entity.$$$ = 1; + entity.$12 = 2; + entity.$name = 3; + entity.__ = 4; + entity._a = 5; + entity._eventId = 6; + entity.a = 7; + entity.a1 = 8; + entity.ab = 9; + entity.IPAddress = 10; + entity.myLongVariableName = 11; + entity.URL = 12; + entity.xY = 13; + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Account.java b/src/test/java/com/jmethods/catatumbo/entities/Account.java index 9bd3207..68cdbf1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Account.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Account.java @@ -27,72 +27,72 @@ */ @Entity public class Account { - @Identifier - private long id; - private String email; - private String name; - @Version - @Property(name = "ENTITY_VERSION") - private long version = 1; + @Identifier + private long id; + private String email; + private String name; + @Version + @Property(name = "ENTITY_VERSION") + private long version = 1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the email - */ - public String getEmail() { - return email; - } + /** + * @return the email + */ + public String getEmail() { + return email; + } - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } + /** + * @param email + * the email to set + */ + public void setEmail(String email) { + this.email = email; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the version - */ - public long getVersion() { - return version; - } + /** + * @return the version + */ + public long getVersion() { + return version; + } - /** - * @param version - * the version to set - */ - public void setVersion(long version) { - this.version = version; - } + /** + * @param version + * the version to set + */ + public void setVersion(long version) { + this.version = version; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Address.java b/src/test/java/com/jmethods/catatumbo/entities/Address.java index dfe50e0..115e415 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Address.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Address.java @@ -31,168 +31,168 @@ @Embeddable public class Address { - private static String test; - - @Property(name = "line1", indexed = false) - private String street1; - - @Property(name = "line2", indexed = false) - private String street2; - - @SecondaryIndex - private String city; - - private String state; - - @Embedded(name = "postal_code") - private ZipCode zipCode; - - @Ignore - private String printableAddress; - - /** - * @return the street1 - */ - public String getStreet1() { - return street1; - } - - /** - * @param street1 - * the street to set - */ - public void setStreet1(String street1) { - this.street1 = street1; - } - - /** - * @return the street2 - */ - public String getStreet2() { - return street2; - } - - /** - * @param street2 - * the street2 to set - */ - public void setStreet2(String street2) { - this.street2 = street2; - } - - /** - * @return the city - */ - public String getCity() { - return city; - } - - /** - * @param city - * the city to set - */ - public void setCity(String city) { - this.city = city; - } - - /** - * @return the state - */ - public String getState() { - return state; - } - - /** - * @param state - * the state to set - */ - public void setState(String state) { - this.state = state; - } - - /** - * @return the printableAddress - */ - public String getPrintableAddress() { - return printableAddress; - } - - /** - * @param printableAddress - * the printableAddress to set - */ - public void setPrintableAddress(String printableAddress) { - this.printableAddress = printableAddress; - } - - /** - * @return the zipCode - */ - public ZipCode getZipCode() { - return zipCode; - } - - /** - * @param zipCode - * the zipCode to set - */ - public void setZipCode(ZipCode zipCode) { - this.zipCode = zipCode; - } - - @Override - public String toString() { - return street1 + "\n" + street2 + "\n" + city + "\n" + state + "\n" + zipCode; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Address)) { - return false; - } - Address that = (Address) obj; - return Objects.equals(this.street1, that.street1) && Objects.equals(this.street2, that.street2) - && Objects.equals(this.city, that.city) && Objects.equals(this.state, that.state) - && Objects.equals(this.zipCode, that.zipCode); - } - - @Override - public int hashCode() { - return Objects.hash(street1, street2, city, state, zipCode); - } - - public static Address getSample1() { - Address address = new Address(); - address.setStreet1("1 Main St."); - address.setStreet2("Apt 1"); - address.setCity("Omaha"); - address.setState("NE"); - ZipCode zip = new ZipCode(); - zip.setFiveDigits("55555"); - zip.setFourDigits("4444"); - zip.setAnotherEmbeddable(new AnotherEmbeddable("Field 1", "Field 2")); - address.setZipCode(zip); - return address; - } - - public static Address getSample2() { - Address address = new Address(); - address.setStreet1("2 Secondary St."); - address.setCity("Lincoln"); - address.setState("NE"); - ZipCode workZipCode = new ZipCode(); - workZipCode.setFiveDigits("99999"); - workZipCode.setFourDigits("0000"); - address.setZipCode(workZipCode); - return address; - } - - public static Address getSample3() { - Address address = new Address(); - address.setStreet1("3 Third St."); - address.setCity("San Jose"); - address.setState("CA"); - return address; - } + private static String test; + + @Property(name = "line1", indexed = false) + private String street1; + + @Property(name = "line2", indexed = false) + private String street2; + + @SecondaryIndex + private String city; + + private String state; + + @Embedded(name = "postal_code") + private ZipCode zipCode; + + @Ignore + private String printableAddress; + + /** + * @return the street1 + */ + public String getStreet1() { + return street1; + } + + /** + * @param street1 + * the street to set + */ + public void setStreet1(String street1) { + this.street1 = street1; + } + + /** + * @return the street2 + */ + public String getStreet2() { + return street2; + } + + /** + * @param street2 + * the street2 to set + */ + public void setStreet2(String street2) { + this.street2 = street2; + } + + /** + * @return the city + */ + public String getCity() { + return city; + } + + /** + * @param city + * the city to set + */ + public void setCity(String city) { + this.city = city; + } + + /** + * @return the state + */ + public String getState() { + return state; + } + + /** + * @param state + * the state to set + */ + public void setState(String state) { + this.state = state; + } + + /** + * @return the printableAddress + */ + public String getPrintableAddress() { + return printableAddress; + } + + /** + * @param printableAddress + * the printableAddress to set + */ + public void setPrintableAddress(String printableAddress) { + this.printableAddress = printableAddress; + } + + /** + * @return the zipCode + */ + public ZipCode getZipCode() { + return zipCode; + } + + /** + * @param zipCode + * the zipCode to set + */ + public void setZipCode(ZipCode zipCode) { + this.zipCode = zipCode; + } + + @Override + public String toString() { + return street1 + "\n" + street2 + "\n" + city + "\n" + state + "\n" + zipCode; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Address)) { + return false; + } + Address that = (Address) obj; + return Objects.equals(this.street1, that.street1) && Objects.equals(this.street2, that.street2) + && Objects.equals(this.city, that.city) && Objects.equals(this.state, that.state) + && Objects.equals(this.zipCode, that.zipCode); + } + + @Override + public int hashCode() { + return Objects.hash(street1, street2, city, state, zipCode); + } + + public static Address getSample1() { + Address address = new Address(); + address.setStreet1("1 Main St."); + address.setStreet2("Apt 1"); + address.setCity("Omaha"); + address.setState("NE"); + ZipCode zip = new ZipCode(); + zip.setFiveDigits("55555"); + zip.setFourDigits("4444"); + zip.setAnotherEmbeddable(new AnotherEmbeddable("Field 1", "Field 2")); + address.setZipCode(zip); + return address; + } + + public static Address getSample2() { + Address address = new Address(); + address.setStreet1("2 Secondary St."); + address.setCity("Lincoln"); + address.setState("NE"); + ZipCode workZipCode = new ZipCode(); + workZipCode.setFiveDigits("99999"); + workZipCode.setFourDigits("0000"); + address.setZipCode(workZipCode); + return address; + } + + public static Address getSample3() { + Address address = new Address(); + address.setStreet1("3 Third St."); + address.setCity("San Jose"); + address.setState("CA"); + return address; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AddressMap.java b/src/test/java/com/jmethods/catatumbo/entities/AddressMap.java index 2deb86d..1a3ed92 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AddressMap.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AddressMap.java @@ -30,70 +30,70 @@ @Entity public class AddressMap { - @Identifier - private long id; + @Identifier + private long id; - private Map addresses; + private Map addresses; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the addresses - */ - public Map getAddresses() { - return addresses; - } + /** + * @return the addresses + */ + public Map getAddresses() { + return addresses; + } - /** - * @param addresses - * the addresses to set - */ - public void setAddresses(Map addresses) { - this.addresses = addresses; - } + /** + * @param addresses + * the addresses to set + */ + public void setAddresses(Map addresses) { + this.addresses = addresses; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof AddressMap)) { - return false; - } - if (this == obj) { - return true; - } - AddressMap that = (AddressMap) obj; - return this.id == that.id && Objects.equals(this.addresses, that.addresses); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof AddressMap)) { + return false; + } + if (this == obj) { + return true; + } + AddressMap that = (AddressMap) obj; + return this.id == that.id && Objects.equals(this.addresses, that.addresses); + } - public static AddressMap getSample1() { - AddressMap entity = new AddressMap(); - Map addresses = new HashMap<>(); - addresses.put("home", Address.getSample1()); - addresses.put("work", Address.getSample2()); - entity.setAddresses(addresses); - return entity; - } + public static AddressMap getSample1() { + AddressMap entity = new AddressMap(); + Map addresses = new HashMap<>(); + addresses.put("home", Address.getSample1()); + addresses.put("work", Address.getSample2()); + entity.setAddresses(addresses); + return entity; + } - public static AddressMap getSample2() { - AddressMap entity = new AddressMap(); - Map addresses = new HashMap<>(); - addresses.put("home", Address.getSample1()); - addresses.put("work", Address.getSample2()); - addresses.put("nullZip", Address.getSample3()); - entity.setAddresses(addresses); - return entity; - } + public static AddressMap getSample2() { + AddressMap entity = new AddressMap(); + Map addresses = new HashMap<>(); + addresses.put("home", Address.getSample1()); + addresses.put("work", Address.getSample2()); + addresses.put("nullZip", Address.getSample3()); + entity.setAddresses(addresses); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Animal.java b/src/test/java/com/jmethods/catatumbo/entities/Animal.java index 46cf574..7e0a669 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Animal.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Animal.java @@ -27,47 +27,47 @@ @MappedSuperClass public class Animal { - @Identifier - private long id; + @Identifier + private long id; - protected String value = ""; + protected String value = ""; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the value - */ - public String getValue() { - return value; - } + /** + * @return the value + */ + public String getValue() { + return value; + } - /** - * @param value - * the value to set - */ - public void setValue(String value) { - this.value = value; - } + /** + * @param value + * the value to set + */ + public void setValue(String value) { + this.value = value; + } - @PreInsert - public void insertingAnimal() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Animal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingAnimal() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Animal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AnotherEmbeddable.java b/src/test/java/com/jmethods/catatumbo/entities/AnotherEmbeddable.java index 60c5bb4..5913aff 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AnotherEmbeddable.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AnotherEmbeddable.java @@ -28,67 +28,67 @@ @Embeddable public class AnotherEmbeddable { - private String field1; - @Property(name = "FIELD2") - private String field2; + private String field1; + @Property(name = "FIELD2") + private String field2; - /** - * - */ - public AnotherEmbeddable() { - // TODO Auto-generated constructor stub - } + /** + * + */ + public AnotherEmbeddable() { + // TODO Auto-generated constructor stub + } - public AnotherEmbeddable(String field1, String field2) { - this.field1 = field1; - this.field2 = field2; - } + public AnotherEmbeddable(String field1, String field2) { + this.field1 = field1; + this.field2 = field2; + } - /** - * @return the field1 - */ - public String getField1() { - return field1; - } + /** + * @return the field1 + */ + public String getField1() { + return field1; + } - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } - /** - * @return the field2 - */ - public String getField2() { - return field2; - } + /** + * @return the field2 + */ + public String getField2() { + return field2; + } - /** - * @param field2 - * the field2 to set - */ - public void setField2(String field2) { - this.field2 = field2; - } + /** + * @param field2 + * the field2 to set + */ + public void setField2(String field2) { + this.field2 = field2; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof AnotherEmbeddable)) { - return false; - } - if (this == obj) { - return true; - } - AnotherEmbeddable that = (AnotherEmbeddable) obj; - return Objects.equals(this.field1, that.field1) && Objects.equals(this.field2, that.field2); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof AnotherEmbeddable)) { + return false; + } + if (this == obj) { + return true; + } + AnotherEmbeddable that = (AnotherEmbeddable) obj; + return Objects.equals(this.field1, that.field1) && Objects.equals(this.field2, that.field2); + } - @Override - public int hashCode() { - return Objects.hash(field1, field2); - } + @Override + public int hashCode() { + return Objects.hash(field1, field2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ArrayIndex.java b/src/test/java/com/jmethods/catatumbo/entities/ArrayIndex.java index c547d67..0224657 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ArrayIndex.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ArrayIndex.java @@ -34,116 +34,116 @@ @Entity public class ArrayIndex { - @Identifier - private long id; - @ParentKey - private DatastoreKey parentKey; - - private List stringList; - @Property(indexed = false) - private List unindexedStringList; - private Set stringSet; - @Property(indexed = false) - private Set unindexedStringSet; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the parentKey - */ - public DatastoreKey getParentKey() { - return parentKey; - } - - /** - * @param parentKey - * the parentKey to set - */ - public void setParentKey(DatastoreKey parentKey) { - this.parentKey = parentKey; - } - - /** - * @return the stringList - */ - public List getStringList() { - return stringList; - } - - /** - * @param stringList - * the stringList to set - */ - public void setStringList(List stringList) { - this.stringList = stringList; - } - - /** - * @return the unindexedStringList - */ - public List getUnindexedStringList() { - return unindexedStringList; - } - - /** - * @param unindexedStringList - * the unindexedStringList to set - */ - public void setUnindexedStringList(List unindexedStringList) { - this.unindexedStringList = unindexedStringList; - } - - /** - * @return the stringSet - */ - public Set getStringSet() { - return stringSet; - } - - /** - * @param stringSet - * the stringSet to set - */ - public void setStringSet(Set stringSet) { - this.stringSet = stringSet; - } - - /** - * @return the unindexedStringSet - */ - public Set getUnindexedStringSet() { - return unindexedStringSet; - } - - /** - * @param unindexedStringSet - * the unindexedStringSet to set - */ - public void setUnindexedStringSet(Set unindexedStringSet) { - this.unindexedStringSet = unindexedStringSet; - } - - public static ArrayIndex getSampleEntity() { - List items = Arrays.asList("One", "Two", "Three"); - ArrayIndex entity = new ArrayIndex(); - entity.setStringList(items); - entity.setUnindexedStringList(items); - entity.setStringSet(new HashSet<>(items)); - entity.setUnindexedStringSet(new HashSet<>(items)); - return entity; - } + @Identifier + private long id; + @ParentKey + private DatastoreKey parentKey; + + private List stringList; + @Property(indexed = false) + private List unindexedStringList; + private Set stringSet; + @Property(indexed = false) + private Set unindexedStringSet; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the parentKey + */ + public DatastoreKey getParentKey() { + return parentKey; + } + + /** + * @param parentKey + * the parentKey to set + */ + public void setParentKey(DatastoreKey parentKey) { + this.parentKey = parentKey; + } + + /** + * @return the stringList + */ + public List getStringList() { + return stringList; + } + + /** + * @param stringList + * the stringList to set + */ + public void setStringList(List stringList) { + this.stringList = stringList; + } + + /** + * @return the unindexedStringList + */ + public List getUnindexedStringList() { + return unindexedStringList; + } + + /** + * @param unindexedStringList + * the unindexedStringList to set + */ + public void setUnindexedStringList(List unindexedStringList) { + this.unindexedStringList = unindexedStringList; + } + + /** + * @return the stringSet + */ + public Set getStringSet() { + return stringSet; + } + + /** + * @param stringSet + * the stringSet to set + */ + public void setStringSet(Set stringSet) { + this.stringSet = stringSet; + } + + /** + * @return the unindexedStringSet + */ + public Set getUnindexedStringSet() { + return unindexedStringSet; + } + + /** + * @param unindexedStringSet + * the unindexedStringSet to set + */ + public void setUnindexedStringSet(Set unindexedStringSet) { + this.unindexedStringSet = unindexedStringSet; + } + + public static ArrayIndex getSampleEntity() { + List items = Arrays.asList("One", "Two", "Three"); + ArrayIndex entity = new ArrayIndex(); + entity.setStringList(items); + entity.setUnindexedStringList(items); + entity.setStringSet(new HashSet<>(items)); + entity.setUnindexedStringSet(new HashSet<>(items)); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampCalendar.java b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampCalendar.java index ab8a7d1..1ae5367 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampCalendar.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampCalendar.java @@ -30,87 +30,87 @@ @Entity public class AutoTimestampCalendar { - @Identifier - private long id; - - private String name; - - @CreatedTimestamp - private Calendar createdOn; - - @UpdatedTimestamp - private Calendar modifiedOn; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the createdOn - */ - public Calendar getCreatedOn() { - return createdOn; - } - - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(Calendar createdOn) { - this.createdOn = createdOn; - } - - /** - * @return the modifiedOn - */ - public Calendar getModifiedOn() { - return modifiedOn; - } - - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(Calendar modifiedOn) { - this.modifiedOn = modifiedOn; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "AutoTimestampCalendar [id=" + id + ", name=" + name + ", createdOn=" - + (createdOn != null ? createdOn.getTime() : null) + ", modifiedOn=" - + (modifiedOn != null ? modifiedOn.getTime() : null) + "]"; - } + @Identifier + private long id; + + private String name; + + @CreatedTimestamp + private Calendar createdOn; + + @UpdatedTimestamp + private Calendar modifiedOn; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the createdOn + */ + public Calendar getCreatedOn() { + return createdOn; + } + + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(Calendar createdOn) { + this.createdOn = createdOn; + } + + /** + * @return the modifiedOn + */ + public Calendar getModifiedOn() { + return modifiedOn; + } + + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(Calendar modifiedOn) { + this.modifiedOn = modifiedOn; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AutoTimestampCalendar [id=" + id + ", name=" + name + ", createdOn=" + + (createdOn != null ? createdOn.getTime() : null) + ", modifiedOn=" + + (modifiedOn != null ? modifiedOn.getTime() : null) + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampDate.java b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampDate.java index 06bd480..41cafc4 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampDate.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampDate.java @@ -31,88 +31,88 @@ @Entity public class AutoTimestampDate { - @Identifier - private long id; - - private String name; - - @CreatedTimestamp - @Property(name = "CREATED_TS", indexed = false) - private Date createdDate; - - @UpdatedTimestamp - @Property(name = "UPDATED_TS", indexed = true) - private Date modifiedDate; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @param createdDate - * the createdDate to set - */ - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @param modifiedDate - * the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "AutoTimestampDate [id=" + id + ", name=" + name + ", createdDate=" + createdDate + ", modifiedDate=" - + modifiedDate + "]"; - } + @Identifier + private long id; + + private String name; + + @CreatedTimestamp + @Property(name = "CREATED_TS", indexed = false) + private Date createdDate; + + @UpdatedTimestamp + @Property(name = "UPDATED_TS", indexed = true) + private Date modifiedDate; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * @param modifiedDate + * the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AutoTimestampDate [id=" + id + ", name=" + name + ", createdDate=" + createdDate + + ", modifiedDate=" + modifiedDate + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampLong.java b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampLong.java index 84638da..9daf9ba 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampLong.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampLong.java @@ -29,88 +29,88 @@ @Entity public class AutoTimestampLong { - @Identifier - private long id; - - private String name; - - @CreatedTimestamp - @Property(name = "CREATED_TS", indexed = false) - private Long createdDate; - - @UpdatedTimestamp - @Property(name = "UPDATED_TS", indexed = true) - private Long modifiedDate; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the createdDate - */ - public Long getCreatedDate() { - return createdDate; - } - - /** - * @param createdDate - * the createdDate to set - */ - public void setCreatedDate(Long createdDate) { - this.createdDate = createdDate; - } - - /** - * @return the modifiedDate - */ - public Long getModifiedDate() { - return modifiedDate; - } - - /** - * @param modifiedDate - * the modifiedDate to set - */ - public void setModifiedDate(Long modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "AutoTimestampDate [id=" + id + ", name=" + name + ", createdDate=" + createdDate + ", modifiedDate=" - + modifiedDate + "]"; - } + @Identifier + private long id; + + private String name; + + @CreatedTimestamp + @Property(name = "CREATED_TS", indexed = false) + private Long createdDate; + + @UpdatedTimestamp + @Property(name = "UPDATED_TS", indexed = true) + private Long modifiedDate; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the createdDate + */ + public Long getCreatedDate() { + return createdDate; + } + + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(Long createdDate) { + this.createdDate = createdDate; + } + + /** + * @return the modifiedDate + */ + public Long getModifiedDate() { + return modifiedDate; + } + + /** + * @param modifiedDate + * the modifiedDate to set + */ + public void setModifiedDate(Long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AutoTimestampDate [id=" + id + ", name=" + name + ", createdDate=" + createdDate + + ", modifiedDate=" + modifiedDate + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampOffsetDateTime.java b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampOffsetDateTime.java index dfc864d..d6cf232 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampOffsetDateTime.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampOffsetDateTime.java @@ -30,81 +30,81 @@ @Entity public class AutoTimestampOffsetDateTime { - @Identifier - private long id; - - private String name; - - @CreatedTimestamp - private OffsetDateTime createdOn; - - @UpdatedTimestamp - private OffsetDateTime modifiedOn; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the createdOn - */ - public OffsetDateTime getCreatedOn() { - return createdOn; - } - - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(OffsetDateTime createdOn) { - this.createdOn = createdOn; - } - - /** - * @return the modifiedOn - */ - public OffsetDateTime getModifiedOn() { - return modifiedOn; - } - - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(OffsetDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - } - - @Override - public String toString() { - return "AutoTimestampOffsetDateTime [id=" + id + ", name=" + name + ", createdOn=" + createdOn + ", modifiedOn=" - + modifiedOn + "]"; - } + @Identifier + private long id; + + private String name; + + @CreatedTimestamp + private OffsetDateTime createdOn; + + @UpdatedTimestamp + private OffsetDateTime modifiedOn; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the createdOn + */ + public OffsetDateTime getCreatedOn() { + return createdOn; + } + + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(OffsetDateTime createdOn) { + this.createdOn = createdOn; + } + + /** + * @return the modifiedOn + */ + public OffsetDateTime getModifiedOn() { + return modifiedOn; + } + + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(OffsetDateTime modifiedOn) { + this.modifiedOn = modifiedOn; + } + + @Override + public String toString() { + return "AutoTimestampOffsetDateTime [id=" + id + ", name=" + name + ", createdOn=" + createdOn + + ", modifiedOn=" + modifiedOn + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampZonedDateTime.java b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampZonedDateTime.java index a18bfb7..28b49bc 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampZonedDateTime.java +++ b/src/test/java/com/jmethods/catatumbo/entities/AutoTimestampZonedDateTime.java @@ -30,81 +30,81 @@ @Entity public class AutoTimestampZonedDateTime { - @Identifier - private long id; - - private String name; - - @CreatedTimestamp - private ZonedDateTime createdOn; - - @UpdatedTimestamp - private ZonedDateTime modifiedOn; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the createdOn - */ - public ZonedDateTime getCreatedOn() { - return createdOn; - } - - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(ZonedDateTime createdOn) { - this.createdOn = createdOn; - } - - /** - * @return the modifiedOn - */ - public ZonedDateTime getModifiedOn() { - return modifiedOn; - } - - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(ZonedDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - } - - @Override - public String toString() { - return "AutoTimestampZonedDateTime [id=" + id + ", name=" + name + ", createdOn=" + createdOn + ", modifiedOn=" - + modifiedOn + "]"; - } + @Identifier + private long id; + + private String name; + + @CreatedTimestamp + private ZonedDateTime createdOn; + + @UpdatedTimestamp + private ZonedDateTime modifiedOn; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the createdOn + */ + public ZonedDateTime getCreatedOn() { + return createdOn; + } + + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(ZonedDateTime createdOn) { + this.createdOn = createdOn; + } + + /** + * @return the modifiedOn + */ + public ZonedDateTime getModifiedOn() { + return modifiedOn; + } + + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(ZonedDateTime modifiedOn) { + this.modifiedOn = modifiedOn; + } + + @Override + public String toString() { + return "AutoTimestampZonedDateTime [id=" + id + ", name=" + name + ", createdOn=" + createdOn + + ", modifiedOn=" + modifiedOn + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity1.java b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity1.java index 9ce09c2..be51300 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity1.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity1.java @@ -26,27 +26,27 @@ @Entity public class BadBuilderEntity1 { - @Identifier - private long id; - - private String name; - - public BadBuilderEntity1(String name) { - this.name = name; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } + @Identifier + private long id; + + private String name; + + public BadBuilderEntity1(String name) { + this.name = name; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity2.java b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity2.java index c661346..ff1eb91 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity2.java @@ -26,36 +26,36 @@ @Entity public class BadBuilderEntity2 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - public BadBuilderEntity2(String name) { + public BadBuilderEntity2(String name) { - } + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - // Non-static - error - public Builder newBuilder() { - return new Builder(); - } + // Non-static - error + public Builder newBuilder() { + return new Builder(); + } - public static class Builder { + public static class Builder { - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity3.java b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity3.java index 6d800cc..b972d28 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity3.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity3.java @@ -26,54 +26,54 @@ @Entity public class BadBuilderEntity3 { - @Identifier - private long id; - - private String name; - - public BadBuilderEntity3(String name) { - - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - public static Builder newBuilder() { - return new Builder(); - } - - public static class Builder { - private long id; - - private String name; - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - } + @Identifier + private long id; + + private String name; + + public BadBuilderEntity3(String name) { + + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder { + private long id; + + private String name; + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity4.java b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity4.java index 76161d3..ec7618f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity4.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BadBuilderEntity4.java @@ -26,50 +26,50 @@ @Entity public class BadBuilderEntity4 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - public BadBuilderEntity4(String name) { + public BadBuilderEntity4(String name) { - } + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - public static Builder newBuilder() { - return new Builder(); - } + public static Builder newBuilder() { + return new Builder(); + } - public static class Builder { - private long id; + public static class Builder { + private long id; - private String name; + private String name; - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - public BadBuilderEntity4 build() { - return new BadBuilderEntity4(name); - } + public BadBuilderEntity4 build() { + return new BadBuilderEntity4(name); + } - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BigDecimalField.java b/src/test/java/com/jmethods/catatumbo/entities/BigDecimalField.java index 8036407..c6e2b59 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BigDecimalField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BigDecimalField.java @@ -28,68 +28,68 @@ @Entity public class BigDecimalField { - @Identifier - private long id; + @Identifier + private long id; - private BigDecimal value; + private BigDecimal value; - public BigDecimalField() { + public BigDecimalField() { - } + } - public BigDecimalField(BigDecimal value) { - this.value = value; - } + public BigDecimalField(BigDecimal value) { + this.value = value; + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the value - */ - public BigDecimal getValue() { - return value; - } + /** + * @return the value + */ + public BigDecimal getValue() { + return value; + } - /** - * @param value - * the value to set - */ - public void setValue(BigDecimal value) { - this.value = value; - } + /** + * @param value + * the value to set + */ + public void setValue(BigDecimal value) { + this.value = value; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !(obj instanceof BigDecimalField)) { - return false; - } - BigDecimalField that = (BigDecimalField) obj; - if (this.id != that.id) { - return false; - } - if (this.value == null && that.value == null) { - return true; - } - if (this.value == null || that.value == null) { - return false; - } - return this.value.compareTo(that.value) == 0; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !(obj instanceof BigDecimalField)) { + return false; + } + BigDecimalField that = (BigDecimalField) obj; + if (this.id != that.id) { + return false; + } + if (this.value == null && that.value == null) { + return true; + } + if (this.value == null || that.value == null) { + return false; + } + return this.value.compareTo(that.value) == 0; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BooleanField.java b/src/test/java/com/jmethods/catatumbo/entities/BooleanField.java index 9d4ecaa..acbd6c3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BooleanField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BooleanField.java @@ -26,39 +26,39 @@ @Entity public class BooleanField { - @Identifier - private long id; + @Identifier + private long id; - private boolean awesome; + private boolean awesome; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the awesome - */ - public boolean isAwesome() { - return awesome; - } + /** + * @return the awesome + */ + public boolean isAwesome() { + return awesome; + } - /** - * @param awesome - * the awesome to set - */ - public void setAwesome(boolean awesome) { - this.awesome = awesome; - } + /** + * @param awesome + * the awesome to set + */ + public void setAwesome(boolean awesome) { + this.awesome = awesome; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/BooleanObject.java b/src/test/java/com/jmethods/catatumbo/entities/BooleanObject.java index a043fad..9794875 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/BooleanObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/BooleanObject.java @@ -26,39 +26,39 @@ @Entity public class BooleanObject { - @Identifier - private long id; + @Identifier + private long id; - private Boolean awesome; + private Boolean awesome; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the awesome - */ - public Boolean getAwesome() { - return awesome; - } + /** + * @return the awesome + */ + public Boolean getAwesome() { + return awesome; + } - /** - * @param awesome - * the awesome to set - */ - public void setAwesome(Boolean awesome) { - this.awesome = awesome; - } + /** + * @param awesome + * the awesome to set + */ + public void setAwesome(Boolean awesome) { + this.awesome = awesome; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ByteArrayField.java b/src/test/java/com/jmethods/catatumbo/entities/ByteArrayField.java index 46bd5c6..0e175c8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ByteArrayField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ByteArrayField.java @@ -26,39 +26,39 @@ @Entity public class ByteArrayField { - @Identifier - private long id; + @Identifier + private long id; - private byte[] salt; + private byte[] salt; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the salt - */ - public byte[] getSalt() { - return salt; - } + /** + * @return the salt + */ + public byte[] getSalt() { + return salt; + } - /** - * @param salt - * the salt to set - */ - public void setSalt(byte[] salt) { - this.salt = salt; - } + /** + * @param salt + * the salt to set + */ + public void setSalt(byte[] salt) { + this.salt = salt; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CalculatorEntity.java b/src/test/java/com/jmethods/catatumbo/entities/CalculatorEntity.java index cfc4bc7..c301286 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CalculatorEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CalculatorEntity.java @@ -29,193 +29,193 @@ @MappedSuperClass public class CalculatorEntity { - @Identifier - private long id; - - @Key - private DatastoreKey key; - - private long operand1; - - private long operand2; - - private long sum; - - @Ignore - private long sum2; - - private long product; - - @Ignore - private long product2; - - private long difference; - - @Ignore - private long difference2; - - public CalculatorEntity() { - - } - - /** - * @param operand1 - * @param operand2 - */ - public CalculatorEntity(long operand1, long operand2) { - super(); - this.operand1 = operand1; - this.operand2 = operand2; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the operand1 - */ - public long getOperand1() { - return operand1; - } - - /** - * @param operand1 - * the operand1 to set - */ - public void setOperand1(long operand1) { - this.operand1 = operand1; - } - - /** - * @return the operand2 - */ - public long getOperand2() { - return operand2; - } - - /** - * @param operand2 - * the operand2 to set - */ - public void setOperand2(long operand2) { - this.operand2 = operand2; - } - - /** - * @return the result - */ - public long getSum() { - return sum; - } - - /** - * @param sum - * the result to set - */ - public void setSum(long sum) { - this.sum = sum; - } - - /** - * @return the result2 - */ - public long getSum2() { - return sum2; - } - - /** - * @param sum2 - * the result2 to set - */ - public void setSum2(long sum2) { - this.sum2 = sum2; - } - - /** - * @return the product - */ - public long getProduct() { - return product; - } - - /** - * @param product - * the product to set - */ - public void setProduct(long product) { - this.product = product; - } - - /** - * @return the product2 - */ - public long getProduct2() { - return product2; - } - - /** - * @param product2 - * the product2 to set - */ - public void setProduct2(long product2) { - this.product2 = product2; - } - - /** - * @return the difference - */ - public long getDifference() { - return difference; - } - - /** - * @param difference - * the difference to set - */ - public void setDifference(long difference) { - this.difference = difference; - } - - /** - * @return the difference2 - */ - public long getDifference2() { - return difference2; - } - - /** - * @param difference2 - * the difference2 to set - */ - public void setDifference2(long difference2) { - this.difference2 = difference2; - } + @Identifier + private long id; + + @Key + private DatastoreKey key; + + private long operand1; + + private long operand2; + + private long sum; + + @Ignore + private long sum2; + + private long product; + + @Ignore + private long product2; + + private long difference; + + @Ignore + private long difference2; + + public CalculatorEntity() { + + } + + /** + * @param operand1 + * @param operand2 + */ + public CalculatorEntity(long operand1, long operand2) { + super(); + this.operand1 = operand1; + this.operand2 = operand2; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the operand1 + */ + public long getOperand1() { + return operand1; + } + + /** + * @param operand1 + * the operand1 to set + */ + public void setOperand1(long operand1) { + this.operand1 = operand1; + } + + /** + * @return the operand2 + */ + public long getOperand2() { + return operand2; + } + + /** + * @param operand2 + * the operand2 to set + */ + public void setOperand2(long operand2) { + this.operand2 = operand2; + } + + /** + * @return the result + */ + public long getSum() { + return sum; + } + + /** + * @param sum + * the result to set + */ + public void setSum(long sum) { + this.sum = sum; + } + + /** + * @return the result2 + */ + public long getSum2() { + return sum2; + } + + /** + * @param sum2 + * the result2 to set + */ + public void setSum2(long sum2) { + this.sum2 = sum2; + } + + /** + * @return the product + */ + public long getProduct() { + return product; + } + + /** + * @param product + * the product to set + */ + public void setProduct(long product) { + this.product = product; + } + + /** + * @return the product2 + */ + public long getProduct2() { + return product2; + } + + /** + * @param product2 + * the product2 to set + */ + public void setProduct2(long product2) { + this.product2 = product2; + } + + /** + * @return the difference + */ + public long getDifference() { + return difference; + } + + /** + * @param difference + * the difference to set + */ + public void setDifference(long difference) { + this.difference = difference; + } + + /** + * @return the difference2 + */ + public long getDifference2() { + return difference2; + } + + /** + * @param difference2 + * the difference2 to set + */ + public void setDifference2(long difference2) { + this.difference2 = difference2; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CalendarField.java b/src/test/java/com/jmethods/catatumbo/entities/CalendarField.java index 0ddddab..aa01c81 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CalendarField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CalendarField.java @@ -27,38 +27,38 @@ */ @Entity public class CalendarField { - @Identifier - private long id; - private Calendar creationDate; + @Identifier + private long id; + private Calendar creationDate; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the creationDate - */ - public Calendar getCreationDate() { - return creationDate; - } + /** + * @return the creationDate + */ + public Calendar getCreationDate() { + return creationDate; + } - /** - * @param creationDate - * the creationDate to set - */ - public void setCreationDate(Calendar creationDate) { - this.creationDate = creationDate; - } + /** + * @param creationDate + * the creationDate to set + */ + public void setCreationDate(Calendar creationDate) { + this.creationDate = creationDate; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Cat.java b/src/test/java/com/jmethods/catatumbo/entities/Cat.java index b68539b..af514d8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Cat.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Cat.java @@ -28,12 +28,12 @@ @ExcludeDefaultListeners public class Cat extends Pet { - @PreInsert - public void insertingCat() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Cat.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingCat() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Cat.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CharArrayField.java b/src/test/java/com/jmethods/catatumbo/entities/CharArrayField.java index d8e5e2f..c62a2c8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CharArrayField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CharArrayField.java @@ -25,39 +25,39 @@ */ @Entity public class CharArrayField { - @Identifier - private long id; - - private char[] password; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the password - */ - public char[] getPassword() { - return password; - } - - /** - * @param password - * the password to set - */ - public void setPassword(char[] password) { - this.password = password; - } + @Identifier + private long id; + + private char[] password; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the password + */ + public char[] getPassword() { + return password; + } + + /** + * @param password + * the password to set + */ + public void setPassword(char[] password) { + this.password = password; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CharField.java b/src/test/java/com/jmethods/catatumbo/entities/CharField.java index 5d04b7f..0ab1e51 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CharField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CharField.java @@ -26,39 +26,39 @@ @Entity public class CharField { - @Identifier - private long id; + @Identifier + private long id; - private char sex; + private char sex; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the sex - */ - public char getSex() { - return sex; - } + /** + * @return the sex + */ + public char getSex() { + return sex; + } - /** - * @param sex - * the sex to set - */ - public void setSex(char sex) { - this.sex = sex; - } + /** + * @param sex + * the sex to set + */ + public void setSex(char sex) { + this.sex = sex; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CharObject.java b/src/test/java/com/jmethods/catatumbo/entities/CharObject.java index 8207eb6..98f7a7d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CharObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CharObject.java @@ -26,39 +26,39 @@ @Entity public class CharObject { - @Identifier - private long id; + @Identifier + private long id; - private Character sex; + private Character sex; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the sex - */ - public Character getSex() { - return sex; - } + /** + * @return the sex + */ + public Character getSex() { + return sex; + } - /** - * @param sex - * the sex to set - */ - public void setSex(Character sex) { - this.sex = sex; - } + /** + * @param sex + * the sex to set + */ + public void setSex(Character sex) { + this.sex = sex; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ChildEntity.java b/src/test/java/com/jmethods/catatumbo/entities/ChildEntity.java index 7b28203..ae4ba00 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ChildEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ChildEntity.java @@ -29,85 +29,85 @@ @Entity public class ChildEntity { - public static final ChildEntity child1 = new ChildEntity(9100, "Child 9100"); - - @Identifier - private long id; - private String field1; - @Key - private DatastoreKey key; - @ParentKey - private DatastoreKey parentKey; - - /** - * - */ - public ChildEntity() { - } - - public ChildEntity(long id, String field1) { - this.id = id; - this.field1 = field1; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the field1 - */ - public String getField1() { - return field1; - } - - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the parentKey - */ - public DatastoreKey getParentKey() { - return parentKey; - } - - /** - * @param parentKey - * the parentKey to set - */ - public void setParentKey(DatastoreKey parentKey) { - this.parentKey = parentKey; - } + public static final ChildEntity child1 = new ChildEntity(9100, "Child 9100"); + + @Identifier + private long id; + private String field1; + @Key + private DatastoreKey key; + @ParentKey + private DatastoreKey parentKey; + + /** + * + */ + public ChildEntity() { + } + + public ChildEntity(long id, String field1) { + this.id = id; + this.field1 = field1; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the field1 + */ + public String getField1() { + return field1; + } + + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the parentKey + */ + public DatastoreKey getParentKey() { + return parentKey; + } + + /** + * @param parentKey + * the parentKey to set + */ + public void setParentKey(DatastoreKey parentKey) { + this.parentKey = parentKey; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Color.java b/src/test/java/com/jmethods/catatumbo/entities/Color.java index f6cdd24..3c85159 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Color.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Color.java @@ -22,6 +22,6 @@ */ public enum Color { - WHITE, BLACK, RED, YELLOW, PURPLE, GOLD, SILVER, BLUE, PINK; + WHITE, BLACK, RED, YELLOW, PURPLE, GOLD, SILVER, BLUE, PINK; } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Contact.java b/src/test/java/com/jmethods/catatumbo/entities/Contact.java index 84bd5c0..546761d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Contact.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Contact.java @@ -35,194 +35,196 @@ */ @Entity @PropertyOverrides({ - @PropertyOverride(name = "workAddress.zipCode.fourDigits", property = @Property(name = "zipx", indexed = false)) }) + @PropertyOverride(name = "workAddress.zipCode.fourDigits", property = @Property(name = "zipx", indexed = false)) }) public class Contact { - @Identifier - private long id; - - @Key - private DatastoreKey key; - - private String firstName; - - private String lastName; - - @Embedded(name = "cellNumber", indexed = true) - @Imploded - private PhoneNumber mobileNumber; - - @Embedded - @Imploded - private Address homeAddress; - - @Embedded - @Exploded - private Address workAddress; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName - * the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the contactNumber - */ - public PhoneNumber getMobileNumber() { - return mobileNumber; - } - - /** - * @param contactNumber - * the contactNumber to set - */ - public void setMobileNumber(PhoneNumber contactNumber) { - this.mobileNumber = contactNumber; - } - - /** - * @return the homeAddress - */ - public Address getHomeAddress() { - return homeAddress; - } - - /** - * @param homeAddress - * the homeAddress to set - */ - public void setHomeAddress(Address homeAddress) { - this.homeAddress = homeAddress; - } - - /** - * @return the workAddress - */ - public Address getWorkAddress() { - return workAddress; - } - - /** - * @param workAddress - * the workAddress to set - */ - public void setWorkAddress(Address workAddress) { - this.workAddress = workAddress; - } - - public boolean equalsExceptId(Contact that) { - return Objects.equals(this.firstName, that.firstName) && Objects.equals(this.lastName, that.lastName) - && Objects.equals(this.mobileNumber, that.mobileNumber) - && Objects.equals(this.homeAddress, that.homeAddress) - && Objects.equals(this.workAddress, that.workAddress); - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Contact)) { - return false; - } - if (this == obj) { - return true; - } - Contact that = (Contact) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.key, that.key) && this.equalsExceptId(that); - } - - public static Contact createContact1() { - Contact contact = new Contact(); - contact.setFirstName("John"); - contact.setLastName("Doe"); - return contact; - } - - public static Contact createContact2() { - Contact contact = new Contact(); - contact.setFirstName("John"); - contact.setLastName("Doe"); - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("1"); - phone.setAreaCode("201"); - phone.setSubscriberNumber("3334444"); - contact.setMobileNumber(phone); - Address homeAddress = new Address(); - homeAddress.setStreet1("1 Main St."); - homeAddress.setStreet2("Apt 1"); - homeAddress.setCity("Omaha"); - homeAddress.setState("NE"); - ZipCode zip = new ZipCode(); - zip.setFiveDigits("55555"); - zip.setFourDigits("4444"); - zip.setAnotherEmbeddable(new AnotherEmbeddable("Field 1", "Field 2")); - homeAddress.setZipCode(zip); - contact.setHomeAddress(homeAddress); - - Address workAddress = new Address(); - workAddress.setStreet1("2 Secondary St."); - workAddress.setCity("Lincoln"); - workAddress.setState("NE"); - ZipCode workZipCode = new ZipCode(); - workZipCode.setFiveDigits("99999"); - workZipCode.setFourDigits("0000"); - workAddress.setZipCode(workZipCode); - - contact.setWorkAddress(workAddress); - return contact; - } + @Identifier + private long id; + + @Key + private DatastoreKey key; + + private String firstName; + + private String lastName; + + @Embedded(name = "cellNumber", indexed = true) + @Imploded + private PhoneNumber mobileNumber; + + @Embedded + @Imploded + private Address homeAddress; + + @Embedded + @Exploded + private Address workAddress; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName + * the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the contactNumber + */ + public PhoneNumber getMobileNumber() { + return mobileNumber; + } + + /** + * @param contactNumber + * the contactNumber to set + */ + public void setMobileNumber(PhoneNumber contactNumber) { + this.mobileNumber = contactNumber; + } + + /** + * @return the homeAddress + */ + public Address getHomeAddress() { + return homeAddress; + } + + /** + * @param homeAddress + * the homeAddress to set + */ + public void setHomeAddress(Address homeAddress) { + this.homeAddress = homeAddress; + } + + /** + * @return the workAddress + */ + public Address getWorkAddress() { + return workAddress; + } + + /** + * @param workAddress + * the workAddress to set + */ + public void setWorkAddress(Address workAddress) { + this.workAddress = workAddress; + } + + public boolean equalsExceptId(Contact that) { + return Objects.equals(this.firstName, that.firstName) + && Objects.equals(this.lastName, that.lastName) + && Objects.equals(this.mobileNumber, that.mobileNumber) + && Objects.equals(this.homeAddress, that.homeAddress) + && Objects.equals(this.workAddress, that.workAddress); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Contact)) { + return false; + } + if (this == obj) { + return true; + } + Contact that = (Contact) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.key, that.key) + && this.equalsExceptId(that); + } + + public static Contact createContact1() { + Contact contact = new Contact(); + contact.setFirstName("John"); + contact.setLastName("Doe"); + return contact; + } + + public static Contact createContact2() { + Contact contact = new Contact(); + contact.setFirstName("John"); + contact.setLastName("Doe"); + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("1"); + phone.setAreaCode("201"); + phone.setSubscriberNumber("3334444"); + contact.setMobileNumber(phone); + Address homeAddress = new Address(); + homeAddress.setStreet1("1 Main St."); + homeAddress.setStreet2("Apt 1"); + homeAddress.setCity("Omaha"); + homeAddress.setState("NE"); + ZipCode zip = new ZipCode(); + zip.setFiveDigits("55555"); + zip.setFourDigits("4444"); + zip.setAnotherEmbeddable(new AnotherEmbeddable("Field 1", "Field 2")); + homeAddress.setZipCode(zip); + contact.setHomeAddress(homeAddress); + + Address workAddress = new Address(); + workAddress.setStreet1("2 Secondary St."); + workAddress.setCity("Lincoln"); + workAddress.setState("NE"); + ZipCode workZipCode = new ZipCode(); + workZipCode.setFiveDigits("99999"); + workZipCode.setFourDigits("0000"); + workAddress.setZipCode(workZipCode); + + contact.setWorkAddress(workAddress); + return contact; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ContactProjection.java b/src/test/java/com/jmethods/catatumbo/entities/ContactProjection.java index 5b8a948..cce0c77 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ContactProjection.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ContactProjection.java @@ -26,49 +26,49 @@ @ProjectedEntity(kind = "Contact") public class ContactProjection { - @Identifier - private long id; + @Identifier + private long id; - private String lastName; + private String lastName; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "ContactProjection [id=" + id + ", lastName=" + lastName + "]"; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "ContactProjection [id=" + id + ", lastName=" + lastName + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Country.java b/src/test/java/com/jmethods/catatumbo/entities/Country.java index 50e26e6..30e4662 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Country.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Country.java @@ -28,57 +28,57 @@ @Entity public class Country { - @Identifier - private String id; + @Identifier + private String id; - private String name; + private String name; - @Key - private DatastoreKey key; + @Key + private DatastoreKey key; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Cow.java b/src/test/java/com/jmethods/catatumbo/entities/Cow.java index f1fe053..89df01f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Cow.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Cow.java @@ -26,12 +26,12 @@ @Entity public class Cow extends FarmAnimal { - @PreInsert - public void insertingCow() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Cow.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingCow() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Cow.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/CustomTypeEntity.java b/src/test/java/com/jmethods/catatumbo/entities/CustomTypeEntity.java index 47c59b9..7bf8e9b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/CustomTypeEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/CustomTypeEntity.java @@ -25,39 +25,39 @@ */ @Entity public class CustomTypeEntity { - @Identifier - private Long id; - - private byte byteField; - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the byteField - */ - public byte getByteField() { - return byteField; - } - - /** - * @param byteField - * the byteField to set - */ - public void setByteField(byte byteField) { - this.byteField = byteField; - } + @Identifier + private Long id; + + private byte byteField; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the byteField + */ + public byte getByteField() { + return byteField; + } + + /** + * @param byteField + * the byteField to set + */ + public void setByteField(byte byteField) { + this.byteField = byteField; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Customer.java b/src/test/java/com/jmethods/catatumbo/entities/Customer.java index 5972959..4012f8a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Customer.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Customer.java @@ -27,165 +27,165 @@ @Entity @PropertyOverrides({ - @PropertyOverride(name = "billingAddress.street1", property = @Property(name = "ba_line1", indexed = false)), - @PropertyOverride(name = "billingAddress.street2", property = @Property(name = "ba_line2", indexed = false)), - @PropertyOverride(name = "billingAddress.city", property = @Property(name = "ba_city", indexed = false)), - @PropertyOverride(name = "billingAddress.state", property = @Property(name = "ba_state", indexed = false)), - @PropertyOverride(name = "billingAddress.zipCode.fiveDigits", property = @Property(name = "ba_zip")), - @PropertyOverride(name = "billingAddress.zipCode.fourDigits", property = @Property(name = "ba_zipx")), - @PropertyOverride(name = "shippingAddress.street1", property = @Property(name = "sa_line1", indexed = false)), - @PropertyOverride(name = "shippingAddress.street2", property = @Property(name = "sa_line2", indexed = false)), - @PropertyOverride(name = "shippingAddress.city", property = @Property(name = "sa_city", indexed = false)), - @PropertyOverride(name = "shippingAddress.state", property = @Property(name = "sa_state", indexed = false)), - @PropertyOverride(name = "shippingAddress.zipCode.fiveDigits", property = @Property(name = "sa_zip")), - @PropertyOverride(name = "shippingAddress.zipCode.fourDigits", property = @Property(name = "sa_zipx")), - @PropertyOverride(name = "shippingAddress.zipCode.anotherEmbeddable.field1", property = @Property(name = "sa_f1")), - @PropertyOverride(name = "shippingAddress.zipCode.anotherEmbeddable.field2", property = @Property(name = "sa_f2")), + @PropertyOverride(name = "billingAddress.street1", property = @Property(name = "ba_line1", indexed = false)), + @PropertyOverride(name = "billingAddress.street2", property = @Property(name = "ba_line2", indexed = false)), + @PropertyOverride(name = "billingAddress.city", property = @Property(name = "ba_city", indexed = false)), + @PropertyOverride(name = "billingAddress.state", property = @Property(name = "ba_state", indexed = false)), + @PropertyOverride(name = "billingAddress.zipCode.fiveDigits", property = @Property(name = "ba_zip")), + @PropertyOverride(name = "billingAddress.zipCode.fourDigits", property = @Property(name = "ba_zipx")), + @PropertyOverride(name = "shippingAddress.street1", property = @Property(name = "sa_line1", indexed = false)), + @PropertyOverride(name = "shippingAddress.street2", property = @Property(name = "sa_line2", indexed = false)), + @PropertyOverride(name = "shippingAddress.city", property = @Property(name = "sa_city", indexed = false)), + @PropertyOverride(name = "shippingAddress.state", property = @Property(name = "sa_state", indexed = false)), + @PropertyOverride(name = "shippingAddress.zipCode.fiveDigits", property = @Property(name = "sa_zip")), + @PropertyOverride(name = "shippingAddress.zipCode.fourDigits", property = @Property(name = "sa_zipx")), + @PropertyOverride(name = "shippingAddress.zipCode.anotherEmbeddable.field1", property = @Property(name = "sa_f1")), + @PropertyOverride(name = "shippingAddress.zipCode.anotherEmbeddable.field2", property = @Property(name = "sa_f2")), }) public class Customer { - @Identifier - private long id; - - private String name; - - @Embedded - private Address billingAddress; - - @Embedded - // @Ignore - private Address shippingAddress; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the billingAddress - */ - public Address getBillingAddress() { - return billingAddress; - } - - /** - * @param billingAddress - * the billingAddress to set - */ - public void setBillingAddress(Address billingAddress) { - this.billingAddress = billingAddress; - } - - /** - * @return the shippingAddress - */ - public Address getShippingAddress() { - return shippingAddress; - } - - /** - * @param shippingAddress - * the shippingAddress to set - */ - public void setShippingAddress(Address shippingAddress) { - this.shippingAddress = shippingAddress; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Customer)) { - return false; - } - Customer that = (Customer) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) - && Objects.equals(this.billingAddress, that.billingAddress) - && Objects.equals(this.shippingAddress, that.shippingAddress); - } - - public static Customer createSampleCustomer1() { - Customer customer = new Customer(); - customer.setName("John Doe"); - Address ba = new Address(); - ba.setStreet1("1 Main St."); - ba.setStreet2("Apt 1"); - ba.setCity("Omaha"); - ba.setState("NE"); - ZipCode baZip = new ZipCode(); - baZip.setFiveDigits("68101"); - baZip.setFourDigits("0000"); - - AnotherEmbeddable ae1 = new AnotherEmbeddable(); - ae1.setField1("billing1"); - ae1.setField2("billing2"); - // baZip.setAnotherEmbeddable(ae1); - - ba.setZipCode(baZip); - - Address sa = new Address(); - sa.setStreet1("2 Second St."); - sa.setStreet2("Apt 2"); - sa.setCity("New York City"); - sa.setState("NY"); - ZipCode saZip = new ZipCode(); - saZip.setFiveDigits("11111"); - saZip.setFourDigits("9999"); - - AnotherEmbeddable ae2 = new AnotherEmbeddable(); - ae2.setField1("shipping1"); - ae2.setField2("shipping2"); - // saZip.setAnotherEmbeddable(ae2); - - sa.setZipCode(saZip); - - customer.setBillingAddress(ba); - customer.setShippingAddress(sa); - - return customer; - } - - public static Customer createSampleCustomer2() { - Customer customer = new Customer(); - customer.setName("Super Customer"); - return customer; - } - - public static Customer createSampleCustomer3() { - Customer customer = new Customer(); - customer.setName("Super Customer"); - Address ba = new Address(); - ba.setStreet1("1 Main St."); - ba.setStreet2("Apt 1"); - ba.setCity("Omaha"); - ba.setState("NE"); - customer.setBillingAddress(ba); - customer.setShippingAddress(ba); - return customer; - } + @Identifier + private long id; + + private String name; + + @Embedded + private Address billingAddress; + + @Embedded + // @Ignore + private Address shippingAddress; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the billingAddress + */ + public Address getBillingAddress() { + return billingAddress; + } + + /** + * @param billingAddress + * the billingAddress to set + */ + public void setBillingAddress(Address billingAddress) { + this.billingAddress = billingAddress; + } + + /** + * @return the shippingAddress + */ + public Address getShippingAddress() { + return shippingAddress; + } + + /** + * @param shippingAddress + * the shippingAddress to set + */ + public void setShippingAddress(Address shippingAddress) { + this.shippingAddress = shippingAddress; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Customer)) { + return false; + } + Customer that = (Customer) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) + && Objects.equals(this.billingAddress, that.billingAddress) + && Objects.equals(this.shippingAddress, that.shippingAddress); + } + + public static Customer createSampleCustomer1() { + Customer customer = new Customer(); + customer.setName("John Doe"); + Address ba = new Address(); + ba.setStreet1("1 Main St."); + ba.setStreet2("Apt 1"); + ba.setCity("Omaha"); + ba.setState("NE"); + ZipCode baZip = new ZipCode(); + baZip.setFiveDigits("68101"); + baZip.setFourDigits("0000"); + + AnotherEmbeddable ae1 = new AnotherEmbeddable(); + ae1.setField1("billing1"); + ae1.setField2("billing2"); + // baZip.setAnotherEmbeddable(ae1); + + ba.setZipCode(baZip); + + Address sa = new Address(); + sa.setStreet1("2 Second St."); + sa.setStreet2("Apt 2"); + sa.setCity("New York City"); + sa.setState("NY"); + ZipCode saZip = new ZipCode(); + saZip.setFiveDigits("11111"); + saZip.setFourDigits("9999"); + + AnotherEmbeddable ae2 = new AnotherEmbeddable(); + ae2.setField1("shipping1"); + ae2.setField2("shipping2"); + // saZip.setAnotherEmbeddable(ae2); + + sa.setZipCode(saZip); + + customer.setBillingAddress(ba); + customer.setShippingAddress(sa); + + return customer; + } + + public static Customer createSampleCustomer2() { + Customer customer = new Customer(); + customer.setName("Super Customer"); + return customer; + } + + public static Customer createSampleCustomer3() { + Customer customer = new Customer(); + customer.setName("Super Customer"); + Address ba = new Address(); + ba.setStreet1("1 Main St."); + ba.setStreet2("Apt 1"); + ba.setCity("Omaha"); + ba.setState("NE"); + customer.setBillingAddress(ba); + customer.setShippingAddress(ba); + return customer; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DateField.java b/src/test/java/com/jmethods/catatumbo/entities/DateField.java index 0523f01..90987da 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DateField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DateField.java @@ -27,38 +27,38 @@ */ @Entity public class DateField { - @Identifier - private long id; - private Date creationDate; + @Identifier + private long id; + private Date creationDate; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the creationDate - */ - public Date getCreationDate() { - return creationDate; - } + /** + * @return the creationDate + */ + public Date getCreationDate() { + return creationDate; + } - /** - * @param creationDate - * the creationDate to set - */ - public void setCreationDate(Date creationDate) { - this.creationDate = creationDate; - } + /** + * @param creationDate + * the creationDate to set + */ + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DecimalFields.java b/src/test/java/com/jmethods/catatumbo/entities/DecimalFields.java index b36c71a..1b32397 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DecimalFields.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DecimalFields.java @@ -31,148 +31,148 @@ @Entity public class DecimalFields { - @Identifier - private long id; - - @Key - private DatastoreKey key; - - @Decimal(precision = 1, scale = 0) - private BigDecimal n10; - - @Decimal(precision = 1, scale = 1) - private BigDecimal n11; - - @Decimal(precision = 5, scale = 0) - private BigDecimal n50; - - @Decimal(precision = 7, scale = 3) - private BigDecimal n73; - - @Decimal(precision = 18, scale = 0) - private BigDecimal n180; - - @Decimal(precision = 18, scale = 18) - private BigDecimal n1818; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the n10 - */ - public BigDecimal getN10() { - return n10; - } - - /** - * @param n10 - * the n10 to set - */ - public void setN10(BigDecimal n10) { - this.n10 = n10; - } - - /** - * @return the n11 - */ - public BigDecimal getN11() { - return n11; - } - - /** - * @param n11 - * the n11 to set - */ - public void setN11(BigDecimal n11) { - this.n11 = n11; - } - - /** - * @return the n50 - */ - public BigDecimal getN50() { - return n50; - } - - /** - * @param n50 - * the n50 to set - */ - public void setN50(BigDecimal n50) { - this.n50 = n50; - } - - /** - * @return the n73 - */ - public BigDecimal getN73() { - return n73; - } - - /** - * @param n73 - * the n73 to set - */ - public void setN73(BigDecimal n73) { - this.n73 = n73; - } - - /** - * @return the n180 - */ - public BigDecimal getN180() { - return n180; - } - - /** - * @param n180 - * the n180 to set - */ - public void setN180(BigDecimal n180) { - this.n180 = n180; - } - - /** - * @return the n1818 - */ - public BigDecimal getN1818() { - return n1818; - } - - /** - * @param n1818 - * the n1818 to set - */ - public void setN1818(BigDecimal n1818) { - this.n1818 = n1818; - } + @Identifier + private long id; + + @Key + private DatastoreKey key; + + @Decimal(precision = 1, scale = 0) + private BigDecimal n10; + + @Decimal(precision = 1, scale = 1) + private BigDecimal n11; + + @Decimal(precision = 5, scale = 0) + private BigDecimal n50; + + @Decimal(precision = 7, scale = 3) + private BigDecimal n73; + + @Decimal(precision = 18, scale = 0) + private BigDecimal n180; + + @Decimal(precision = 18, scale = 18) + private BigDecimal n1818; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the n10 + */ + public BigDecimal getN10() { + return n10; + } + + /** + * @param n10 + * the n10 to set + */ + public void setN10(BigDecimal n10) { + this.n10 = n10; + } + + /** + * @return the n11 + */ + public BigDecimal getN11() { + return n11; + } + + /** + * @param n11 + * the n11 to set + */ + public void setN11(BigDecimal n11) { + this.n11 = n11; + } + + /** + * @return the n50 + */ + public BigDecimal getN50() { + return n50; + } + + /** + * @param n50 + * the n50 to set + */ + public void setN50(BigDecimal n50) { + this.n50 = n50; + } + + /** + * @return the n73 + */ + public BigDecimal getN73() { + return n73; + } + + /** + * @param n73 + * the n73 to set + */ + public void setN73(BigDecimal n73) { + this.n73 = n73; + } + + /** + * @return the n180 + */ + public BigDecimal getN180() { + return n180; + } + + /** + * @param n180 + * the n180 to set + */ + public void setN180(BigDecimal n180) { + this.n180 = n180; + } + + /** + * @return the n1818 + */ + public BigDecimal getN1818() { + return n1818; + } + + /** + * @param n1818 + * the n1818 to set + */ + public void setN1818(BigDecimal n1818) { + this.n1818 = n1818; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DeleteAll.java b/src/test/java/com/jmethods/catatumbo/entities/DeleteAll.java index 474fd7b..fd855f8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DeleteAll.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DeleteAll.java @@ -27,48 +27,48 @@ @Entity public class DeleteAll { - @Identifier - private long id; + @Identifier + private long id; - private String field1; + private String field1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the field1 - */ - public String getField1() { - return field1; - } + /** + * @return the field1 + */ + public String getField1() { + return field1; + } - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof DeleteAll)) { - return false; - } - DeleteAll that = (DeleteAll) obj; - return this.id == that.id && Objects.equal(this.field1, that.field1); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof DeleteAll)) { + return false; + } + DeleteAll that = (DeleteAll) obj; + return this.id == that.id && Objects.equal(this.field1, that.field1); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Department.java b/src/test/java/com/jmethods/catatumbo/entities/Department.java index 8feb5ca..a89e6eb 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Department.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Department.java @@ -28,57 +28,57 @@ @Entity public class Department { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Key - private DatastoreKey fullKey; + @Key + private DatastoreKey fullKey; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the fullKey - */ - public DatastoreKey getFullKey() { - return fullKey; - } + /** + * @return the fullKey + */ + public DatastoreKey getFullKey() { + return fullKey; + } - /** - * @param fullKey - * the fullKey to set - */ - public void setFullKey(DatastoreKey fullKey) { - this.fullKey = fullKey; - } + /** + * @param fullKey + * the fullKey to set + */ + public void setFullKey(DatastoreKey fullKey) { + this.fullKey = fullKey; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DeviceType.java b/src/test/java/com/jmethods/catatumbo/entities/DeviceType.java index 76caba9..bbc29c1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DeviceType.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DeviceType.java @@ -22,6 +22,6 @@ */ public enum DeviceType { - DESKTOP, TABLET, SMARTPHONE; + DESKTOP, TABLET, SMARTPHONE; } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Dog.java b/src/test/java/com/jmethods/catatumbo/entities/Dog.java index ebd2e03..38deb15 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Dog.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Dog.java @@ -31,20 +31,20 @@ @ExcludeDefaultListeners public class Dog extends Pet { - @PreInsert - public void insertingDog() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Dog.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingDog() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Dog.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } - @PostInsert - public void dogInserted() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Dog.class.getSimpleName() + "." + PostInsert.class.getSimpleName(); - } + @PostInsert + public void dogInserted() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Dog.class.getSimpleName() + "." + PostInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DoubleField.java b/src/test/java/com/jmethods/catatumbo/entities/DoubleField.java index 6d942a6..6420743 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DoubleField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DoubleField.java @@ -26,39 +26,39 @@ @Entity public class DoubleField { - @Identifier - private long id; + @Identifier + private long id; - private double area; + private double area; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the area - */ - public double getArea() { - return area; - } + /** + * @return the area + */ + public double getArea() { + return area; + } - /** - * @param area - * the area to set - */ - public void setArea(double area) { - this.area = area; - } + /** + * @param area + * the area to set + */ + public void setArea(double area) { + this.area = area; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/DoubleObject.java b/src/test/java/com/jmethods/catatumbo/entities/DoubleObject.java index fbdb02c..b6076f1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/DoubleObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/DoubleObject.java @@ -26,39 +26,39 @@ @Entity public class DoubleObject { - @Identifier - private long id; + @Identifier + private long id; - private Double area; + private Double area; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the area - */ - public Double getArea() { - return area; - } + /** + * @return the area + */ + public Double getArea() { + return area; + } - /** - * @param area - * the area to set - */ - public void setArea(Double area) { - this.area = area; - } + /** + * @param area + * the area to set + */ + public void setArea(Double area) { + this.area = area; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/EmbeddedListIndex.java b/src/test/java/com/jmethods/catatumbo/entities/EmbeddedListIndex.java index aae0c4c..6ff511b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/EmbeddedListIndex.java +++ b/src/test/java/com/jmethods/catatumbo/entities/EmbeddedListIndex.java @@ -30,57 +30,57 @@ @Entity public class EmbeddedListIndex { - @Identifier - private long id; + @Identifier + private long id; - @ParentKey - private DatastoreKey parentKey; + @ParentKey + private DatastoreKey parentKey; - private List
addresses; + private List
addresses; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the parentKey - */ - public DatastoreKey getParentKey() { - return parentKey; - } + /** + * @return the parentKey + */ + public DatastoreKey getParentKey() { + return parentKey; + } - /** - * @param parentKey - * the parentKey to set - */ - public void setParentKey(DatastoreKey parentKey) { - this.parentKey = parentKey; - } + /** + * @param parentKey + * the parentKey to set + */ + public void setParentKey(DatastoreKey parentKey) { + this.parentKey = parentKey; + } - /** - * @return the addresses - */ - public List
getAddresses() { - return addresses; - } + /** + * @return the addresses + */ + public List
getAddresses() { + return addresses; + } - /** - * @param addresses - * the addresses to set - */ - public void setAddresses(List
addresses) { - this.addresses = addresses; - } + /** + * @param addresses + * the addresses to set + */ + public void setAddresses(List
addresses) { + this.addresses = addresses; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Employee.java b/src/test/java/com/jmethods/catatumbo/entities/Employee.java index 127b299..9181714 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Employee.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Employee.java @@ -28,74 +28,74 @@ @Entity public class Employee { - @Identifier - private long id; - private String name; + @Identifier + private long id; + private String name; - @Property(name = "DEPT") - private DatastoreKey department; + @Property(name = "DEPT") + private DatastoreKey department; - @Property(indexed = true) - private DatastoreKey country; + @Property(indexed = true) + private DatastoreKey country; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the department - */ - public DatastoreKey getDepartment() { - return department; - } + /** + * @return the department + */ + public DatastoreKey getDepartment() { + return department; + } - /** - * @param department - * the department to set - */ - public void setDepartment(DatastoreKey department) { - this.department = department; - } + /** + * @param department + * the department to set + */ + public void setDepartment(DatastoreKey department) { + this.department = department; + } - /** - * @return the country - */ - public DatastoreKey getCountry() { - return country; - } + /** + * @return the country + */ + public DatastoreKey getCountry() { + return country; + } - /** - * @param country - * the country to set - */ - public void setCountry(DatastoreKey country) { - this.country = country; - } + /** + * @param country + * the country to set + */ + public void setCountry(DatastoreKey country) { + this.country = country; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/EnumField.java b/src/test/java/com/jmethods/catatumbo/entities/EnumField.java index dc91e4e..5db4de2 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/EnumField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/EnumField.java @@ -26,43 +26,43 @@ @Entity public class EnumField { - @Identifier - private long id; + @Identifier + private long id; - private Size size; + private Size size; - public enum Size { - SMALL, MEDIUM, LARGE, EXTRA_LARGE; - } + public enum Size { + SMALL, MEDIUM, LARGE, EXTRA_LARGE; + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the size - */ - public Size getSize() { - return size; - } + /** + * @return the size + */ + public Size getSize() { + return size; + } - /** - * @param size - * the size to set - */ - public void setSize(Size size) { - this.size = size; - } + /** + * @param size + * the size to set + */ + public void setSize(Size size) { + this.size = size; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity.java b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity.java index a606329..3c53ec5 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity.java @@ -28,19 +28,19 @@ @EntityListeners(Adder.class) public class ExternalCalculatorEntity extends CalculatorEntity { - /** - * - */ - public ExternalCalculatorEntity() { - super(); - } + /** + * + */ + public ExternalCalculatorEntity() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public ExternalCalculatorEntity(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public ExternalCalculatorEntity(long operand1, long operand2) { + super(operand1, operand2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity2.java b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity2.java index 9a46491..2d128e4 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity2.java @@ -29,19 +29,19 @@ @EntityListeners({ Adder.class, Multiplier.class }) public class ExternalCalculatorEntity2 extends CalculatorEntity { - /** - * - */ - public ExternalCalculatorEntity2() { - super(); - } + /** + * + */ + public ExternalCalculatorEntity2() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public ExternalCalculatorEntity2(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public ExternalCalculatorEntity2(long operand1, long operand2) { + super(operand1, operand2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity3.java b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity3.java index a71e243..16b0fd0 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity3.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity3.java @@ -31,19 +31,19 @@ @ExcludeDefaultListeners public class ExternalCalculatorEntity3 extends CalculatorEntity { - /** - * - */ - public ExternalCalculatorEntity3() { - super(); - } + /** + * + */ + public ExternalCalculatorEntity3() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public ExternalCalculatorEntity3(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public ExternalCalculatorEntity3(long operand1, long operand2) { + super(operand1, operand2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity4.java b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity4.java index 40f16d7..546b00f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity4.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ExternalCalculatorEntity4.java @@ -29,19 +29,19 @@ @EntityListeners({ Adder.class, Multiplier.class }) public class ExternalCalculatorEntity4 extends CalculatorEntity { - /** - * - */ - public ExternalCalculatorEntity4() { - super(); - } + /** + * + */ + public ExternalCalculatorEntity4() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public ExternalCalculatorEntity4(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public ExternalCalculatorEntity4(long operand1, long operand2) { + super(operand1, operand2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/FarmAnimal.java b/src/test/java/com/jmethods/catatumbo/entities/FarmAnimal.java index a427878..2a9b1c9 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/FarmAnimal.java +++ b/src/test/java/com/jmethods/catatumbo/entities/FarmAnimal.java @@ -28,11 +28,11 @@ @MappedSuperClass @EntityListeners(FarmAnimalListener.class) public class FarmAnimal extends Animal { - @PreInsert - public void insertingWildAnimal() { - if (value.trim().length() > 0) { - value += "->"; - } - value += FarmAnimal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingWildAnimal() { + if (value.trim().length() > 0) { + value += "->"; + } + value += FarmAnimal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/FloatField.java b/src/test/java/com/jmethods/catatumbo/entities/FloatField.java index e0e4f2f..8076228 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/FloatField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/FloatField.java @@ -26,39 +26,39 @@ @Entity public class FloatField { - @Identifier - private long id; + @Identifier + private long id; - private float area; + private float area; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the area - */ - public float getArea() { - return area; - } + /** + * @return the area + */ + public float getArea() { + return area; + } - /** - * @param area - * the area to set - */ - public void setArea(float area) { - this.area = area; - } + /** + * @param area + * the area to set + */ + public void setArea(float area) { + this.area = area; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/FloatObject.java b/src/test/java/com/jmethods/catatumbo/entities/FloatObject.java index a5fbb84..7ac1dea 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/FloatObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/FloatObject.java @@ -26,39 +26,39 @@ @Entity public class FloatObject { - @Identifier - private long id; + @Identifier + private long id; - private Float area; + private Float area; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the area - */ - public Float getArea() { - return area; - } + /** + * @return the area + */ + public Float getArea() { + return area; + } - /** - * @param area - * the area to set - */ - public void setArea(Float area) { - this.area = area; - } + /** + * @param area + * the area to set + */ + public void setArea(Float area) { + this.area = area; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/GenericListField.java b/src/test/java/com/jmethods/catatumbo/entities/GenericListField.java index 85d9cef..ef0208f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/GenericListField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/GenericListField.java @@ -28,39 +28,39 @@ @Entity public class GenericListField { - @Identifier - private long id; + @Identifier + private long id; - private List items; + private List items; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the items - */ - public List getItems() { - return items; - } + /** + * @return the items + */ + public List getItems() { + return items; + } - /** - * @param items - * the items to set - */ - public void setItems(List items) { - this.items = items; - } + /** + * @param items + * the items to set + */ + public void setItems(List items) { + this.items = items; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/GenericLongId.java b/src/test/java/com/jmethods/catatumbo/entities/GenericLongId.java index bab53a5..533f8d1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/GenericLongId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/GenericLongId.java @@ -22,29 +22,29 @@ */ public class GenericLongId { - private long value; + private long value; - public GenericLongId(long value) { - this.value = value; - } + public GenericLongId(long value) { + this.value = value; + } - /** - * @return the value - */ - public long getValue() { - return value; - } + /** + * @return the value + */ + public long getValue() { + return value; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj != null && !(obj instanceof GenericLongId)) { - return false; - } - GenericLongId that = (GenericLongId) obj; - return this.value == that.value; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj != null && !(obj instanceof GenericLongId)) { + return false; + } + GenericLongId that = (GenericLongId) obj; + return this.value == that.value; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/GeoLocationField.java b/src/test/java/com/jmethods/catatumbo/entities/GeoLocationField.java index 620f8b1..f6ca08f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/GeoLocationField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/GeoLocationField.java @@ -27,84 +27,85 @@ @Entity(kind = "CityCoordinates") public class GeoLocationField { - public static final GeoLocationField NEW_YORK_CITY = new GeoLocationField("New York City", - new GeoLocation(40.7142700, -74.0059700)); - - public static final GeoLocationField OMAHA = new GeoLocationField("Omaha", - new GeoLocation(41.2586100, -95.9377900)); - - public static final GeoLocationField PARIS = new GeoLocationField("Paris", new GeoLocation(48.8534100, 2.3488000)); - - @Identifier - private long id; - - private String city; - - private GeoLocation coordinates; - - /** - * Creates a new instance of GeoLocationField. - */ - public GeoLocationField() { - // Do nothing - } - - /** - * Creates a new instance of GeoLocationField. - * - * @param city - * city - * @param coordinates - * coordinates - */ - public GeoLocationField(String city, GeoLocation coordinates) { - this.city = city; - this.coordinates = coordinates; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the city - */ - public String getCity() { - return city; - } - - /** - * @param city - * the city to set - */ - public void setCity(String city) { - this.city = city; - } - - /** - * @return the coordinates - */ - public GeoLocation getCoordinates() { - return coordinates; - } - - /** - * @param coordinates - * the coordinates to set - */ - public void setCoordinates(GeoLocation coordinates) { - this.coordinates = coordinates; - } + public static final GeoLocationField NEW_YORK_CITY = new GeoLocationField("New York City", + new GeoLocation(40.7142700, -74.0059700)); + + public static final GeoLocationField OMAHA = new GeoLocationField("Omaha", + new GeoLocation(41.2586100, -95.9377900)); + + public static final GeoLocationField PARIS = new GeoLocationField("Paris", + new GeoLocation(48.8534100, 2.3488000)); + + @Identifier + private long id; + + private String city; + + private GeoLocation coordinates; + + /** + * Creates a new instance of GeoLocationField. + */ + public GeoLocationField() { + // Do nothing + } + + /** + * Creates a new instance of GeoLocationField. + * + * @param city + * city + * @param coordinates + * coordinates + */ + public GeoLocationField(String city, GeoLocation coordinates) { + this.city = city; + this.coordinates = coordinates; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the city + */ + public String getCity() { + return city; + } + + /** + * @param city + * the city to set + */ + public void setCity(String city) { + this.city = city; + } + + /** + * @return the coordinates + */ + public GeoLocation getCoordinates() { + return coordinates; + } + + /** + * @param coordinates + * the coordinates to set + */ + public void setCoordinates(GeoLocation coordinates) { + this.coordinates = coordinates; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/GlobalCalculatorEntity.java b/src/test/java/com/jmethods/catatumbo/entities/GlobalCalculatorEntity.java index c2472bb..f580423 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/GlobalCalculatorEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/GlobalCalculatorEntity.java @@ -25,19 +25,19 @@ @Entity public class GlobalCalculatorEntity extends CalculatorEntity { - /** - * - */ - public GlobalCalculatorEntity() { - super(); - } + /** + * + */ + public GlobalCalculatorEntity() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public GlobalCalculatorEntity(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public GlobalCalculatorEntity(long operand1, long operand2) { + super(operand1, operand2); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/GrandchildEntity.java b/src/test/java/com/jmethods/catatumbo/entities/GrandchildEntity.java index 64bc50b..eaf99f3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/GrandchildEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/GrandchildEntity.java @@ -29,86 +29,86 @@ @Entity public class GrandchildEntity { - public static final GrandchildEntity grandchild1 = new GrandchildEntity(9200, "Grandchild 9200"); - - @Identifier - private long id; - private String field1; - @Key - private DatastoreKey key; - @ParentKey - private DatastoreKey parentKey; - - /** - * - */ - public GrandchildEntity() { - } - - public GrandchildEntity(long id, String field1) { - super(); - this.id = id; - this.field1 = field1; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the field1 - */ - public String getField1() { - return field1; - } - - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the parentKey - */ - public DatastoreKey getParentKey() { - return parentKey; - } - - /** - * @param parentKey - * the parentKey to set - */ - public void setParentKey(DatastoreKey parentKey) { - this.parentKey = parentKey; - } + public static final GrandchildEntity grandchild1 = new GrandchildEntity(9200, "Grandchild 9200"); + + @Identifier + private long id; + private String field1; + @Key + private DatastoreKey key; + @ParentKey + private DatastoreKey parentKey; + + /** + * + */ + public GrandchildEntity() { + } + + public GrandchildEntity(long id, String field1) { + super(); + this.id = id; + this.field1 = field1; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the field1 + */ + public String getField1() { + return field1; + } + + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the parentKey + */ + public DatastoreKey getParentKey() { + return parentKey; + } + + /** + * @param parentKey + * the parentKey to set + */ + public void setParentKey(DatastoreKey parentKey) { + this.parentKey = parentKey; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/IgnoreField.java b/src/test/java/com/jmethods/catatumbo/entities/IgnoreField.java index d876ccf..4fe05fb 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/IgnoreField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/IgnoreField.java @@ -27,57 +27,57 @@ @Entity public class IgnoreField { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Ignore - private String computed; + @Ignore + private String computed; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the computed - */ - public String getComputed() { - return computed; - } + /** + * @return the computed + */ + public String getComputed() { + return computed; + } - /** - * @param computed - * the computed to set - */ - public void setComputed(String computed) { - this.computed = computed; - } + /** + * @param computed + * the computed to set + */ + public void setComputed(String computed) { + this.computed = computed; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/IgnoreField2.java b/src/test/java/com/jmethods/catatumbo/entities/IgnoreField2.java index aa61637..69d33d6 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/IgnoreField2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/IgnoreField2.java @@ -26,56 +26,56 @@ @Entity(kind = "IgnoreField") public class IgnoreField2 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - private String computed; + private String computed; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the computed - */ - public String getComputed() { - return computed; - } + /** + * @return the computed + */ + public String getComputed() { + return computed; + } - /** - * @param computed - * the computed to set - */ - public void setComputed(String computed) { - this.computed = computed; - } + /** + * @param computed + * the computed to set + */ + public void setComputed(String computed) { + this.computed = computed; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutableAddress.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutableAddress.java index f4aac40..3646267 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutableAddress.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutableAddress.java @@ -28,143 +28,144 @@ @Embeddable public class ImmutableAddress { - private String line1; - private String line2; - private String city; - private String state; - @Embedded - private ImmutableZipCode zipCode; - - private ImmutableAddress(Builder builder) { - this.line1 = builder.line1; - this.line2 = builder.line2; - this.city = builder.city; - this.state = builder.state; - this.zipCode = builder.zipCode; - } - - public static Builder builder() { - return new Builder(); - } - - /** - * @return the line1 - */ - public String getLine1() { - return line1; - } - - /** - * @return the line2 - */ - public String getLine2() { - return line2; - } - - /** - * @return the city - */ - public String getCity() { - return city; - } - - /** - * @return the state - */ - public String getState() { - return state; - } - - /** - * @return the zipCode - */ - public ImmutableZipCode getZipCode() { - return zipCode; - } - - public static class Builder { - private String line1; - private String line2; - private String city; - private String state; - private ImmutableZipCode zipCode; - - private Builder() { - - } - - /** - * @param line1 - * the line1 to set - */ - public Builder setLine1(String line1) { - this.line1 = line1; - return this; - } - - /** - * @param line2 - * the line2 to set - */ - public Builder setLine2(String line2) { - this.line2 = line2; - return this; - } - - /** - * @param city - * the city to set - */ - public Builder setCity(String city) { - this.city = city; - return this; - } - - /** - * @param state - * the state to set - */ - public Builder setState(String state) { - this.state = state; - return this; - } - - public Builder setZipCode(ImmutableZipCode zipCode) { - this.zipCode = zipCode; - return this; - } - - public ImmutableAddress build() { - return new ImmutableAddress(this); - } - - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder2 = new StringBuilder(); - builder2.append("ImmutableAddress [line1=").append(line1).append(", line2=").append(line2).append(", city=") - .append(city).append(", state=").append(state).append(", zipCode=").append(zipCode).append("]"); - return builder2.toString(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - ImmutableAddress that = (ImmutableAddress) obj; - return Objects.equals(this.line1, that.line1) && Objects.equals(this.line2, that.line2) - && Objects.equals(this.city, that.city) && Objects.equals(this.state, that.state) - && Objects.equals(this.zipCode, that.zipCode); - } + private String line1; + private String line2; + private String city; + private String state; + @Embedded + private ImmutableZipCode zipCode; + + private ImmutableAddress(Builder builder) { + this.line1 = builder.line1; + this.line2 = builder.line2; + this.city = builder.city; + this.state = builder.state; + this.zipCode = builder.zipCode; + } + + public static Builder builder() { + return new Builder(); + } + + /** + * @return the line1 + */ + public String getLine1() { + return line1; + } + + /** + * @return the line2 + */ + public String getLine2() { + return line2; + } + + /** + * @return the city + */ + public String getCity() { + return city; + } + + /** + * @return the state + */ + public String getState() { + return state; + } + + /** + * @return the zipCode + */ + public ImmutableZipCode getZipCode() { + return zipCode; + } + + public static class Builder { + private String line1; + private String line2; + private String city; + private String state; + private ImmutableZipCode zipCode; + + private Builder() { + + } + + /** + * @param line1 + * the line1 to set + */ + public Builder setLine1(String line1) { + this.line1 = line1; + return this; + } + + /** + * @param line2 + * the line2 to set + */ + public Builder setLine2(String line2) { + this.line2 = line2; + return this; + } + + /** + * @param city + * the city to set + */ + public Builder setCity(String city) { + this.city = city; + return this; + } + + /** + * @param state + * the state to set + */ + public Builder setState(String state) { + this.state = state; + return this; + } + + public Builder setZipCode(ImmutableZipCode zipCode) { + this.zipCode = zipCode; + return this; + } + + public ImmutableAddress build() { + return new ImmutableAddress(this); + } + + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder2 = new StringBuilder(); + builder2.append("ImmutableAddress [line1=").append(line1).append(", line2=").append(line2) + .append(", city=").append(city).append(", state=").append(state).append(", zipCode=") + .append(zipCode).append("]"); + return builder2.toString(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + ImmutableAddress that = (ImmutableAddress) obj; + return Objects.equals(this.line1, that.line1) && Objects.equals(this.line2, that.line2) + && Objects.equals(this.city, that.city) && Objects.equals(this.state, that.state) + && Objects.equals(this.zipCode, that.zipCode); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutablePerson.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutablePerson.java index a8718c1..124fa09 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutablePerson.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutablePerson.java @@ -43,227 +43,230 @@ @EntityListeners(ImmutablePersonListener.class) public class ImmutablePerson { - @Identifier - private final long id; + @Identifier + private final long id; - private final String name; + private final String name; - @Embedded - private final ImmutableAddress address; + @Embedded + private final ImmutableAddress address; - @Key - private final DatastoreKey key; + @Key + private final DatastoreKey key; - @Embedded(optional = true) - @Imploded - private ImmutablePhone phoneNumber; + @Embedded(optional = true) + @Imploded + private ImmutablePhone phoneNumber; - @Property(optional = true) - private final List otherNumbers; + @Property(optional = true) + private final List otherNumbers; - @UpdatedTimestamp - @Property(name = "lastChanged") - private final OffsetDateTime modifiedOn; + @UpdatedTimestamp + @Property(name = "lastChanged") + private final OffsetDateTime modifiedOn; - private boolean preInsertFired; - private boolean postInsertFired; - private boolean postLoadFired; + private boolean preInsertFired; + private boolean postInsertFired; + private boolean postLoadFired; - private ImmutablePerson(Builder builder) { - this.id = builder.id; - this.name = builder.name; - this.address = builder.address; - this.phoneNumber = builder.phoneNumber; - this.key = builder.key; - this.modifiedOn = builder.modifiedOn; - this.otherNumbers = builder.otherNumbers; - } + private ImmutablePerson(Builder builder) { + this.id = builder.id; + this.name = builder.name; + this.address = builder.address; + this.phoneNumber = builder.phoneNumber; + this.key = builder.key; + this.modifiedOn = builder.modifiedOn; + this.otherNumbers = builder.otherNumbers; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public ImmutableAddress getAddress() { - return address; - } + public ImmutableAddress getAddress() { + return address; + } - public ImmutablePhone getPhoneNumber() { - return phoneNumber; - } + public ImmutablePhone getPhoneNumber() { + return phoneNumber; + } - public DatastoreKey getKey() { - return key; - } + public DatastoreKey getKey() { + return key; + } - public OffsetDateTime getModifiedOn() { - return modifiedOn; - } + public OffsetDateTime getModifiedOn() { + return modifiedOn; + } - public List getOtherNumbers() { - return otherNumbers; - } - - public boolean isPreInsertFired() { - return preInsertFired; - } - - public boolean isPostInsertFired() { - return postInsertFired; - } - - public boolean isPostLoadFired() { - return postLoadFired; - } - - @Override - public String toString() { - StringBuilder builder2 = new StringBuilder(); - builder2.append("ImmutablePerson [id=").append(id).append(", name=").append(name).append(", address=") - .append(address).append(", key=").append(key).append(", phoneNumber=").append(phoneNumber) - .append(", otherNumbers=").append(otherNumbers).append(", modifiedOn=").append(modifiedOn).append("]"); - return builder2.toString(); - } - - public static Builder newBuilder() { - return new Builder(); - } - - public static class Builder { - private long id; - - private String name; - - private ImmutableAddress address; - - private ImmutablePhone phoneNumber; - - private List otherNumbers; - - private DatastoreKey key; - - private OffsetDateTime modifiedOn; - - private Builder() { - - } - - public Builder setId(long id) { - this.id = id; - return this; - } - - public Builder withName(String name) { - this.name = name; - return this; - } - - public Builder setAddress(ImmutableAddress address) { - this.address = address; - return this; - } - - public Builder phoneNumber(ImmutablePhone phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public Builder setOtherNumbers(List otherNumbers) { - this.otherNumbers = otherNumbers; - return this; - } - - public Builder setKey(DatastoreKey key) { - this.key = key; - return this; - } - - public Builder setModifiedOn(OffsetDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - return this; - } - - public ImmutablePerson build() { - return new ImmutablePerson(this); - } - - } - - @Override - public boolean equals(Object obj) { - if (equalsExceptAutoGeneratedFields(obj)) { - ImmutablePerson that = (ImmutablePerson) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.modifiedOn, that.modifiedOn) - && Objects.equals(this.key, that.key); - } - return false; - } - - public boolean equalsExceptAutoGeneratedFields(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - ImmutablePerson that = (ImmutablePerson) obj; - return Objects.equals(this.name, that.name) && Objects.equals(this.address, that.address) - && Objects.equals(this.phoneNumber, that.phoneNumber) - && Objects.equals(this.otherNumbers, that.otherNumbers); - } - - public static ImmutablePerson getSample1() { - ImmutableZipCode.Builder zipBuilder = ImmutableZipCode.newBuilder(); - zipBuilder.setFiveDigits("55555"); - zipBuilder.setFourDgits("4444"); - ImmutableZipCode zip = zipBuilder.build(); - - ImmutablePerson person = ImmutablePerson.newBuilder().withName("John Doe") - .setAddress(ImmutableAddress.builder().setLine1("1 Main St.").setLine2("Apt 450") - .setCity("San Francisco").setState("CA").setZipCode(zip).build()) - .phoneNumber(ImmutablePhone.getSample1()).setOtherNumbers(ImmutablePhone.getSampleList()).build(); - return person; - } - - public static ImmutablePerson getSample2() { - return ImmutablePerson.newBuilder().build(); - } - - public static ImmutablePerson getSample3() { - ImmutableZipCode.Builder zipBuilder = ImmutableZipCode.newBuilder(); - zipBuilder.setFiveDigits("55555"); - ImmutableZipCode zip = zipBuilder.build(); - - ImmutablePerson person = ImmutablePerson.newBuilder().withName("John Doe") - .setAddress(ImmutableAddress.builder().setLine1("1 Main St.").setLine2("Apt 450") - .setCity("San Francisco").setState("CA").setZipCode(zip).build()) - .phoneNumber(ImmutablePhone.getSample1()).setOtherNumbers(ImmutablePhone.getSampleList()).build(); - return person; - } - - @PreInsert - public void beforeInsert() { - preInsertFired = true; - } - - @PostInsert - public void afterInsert() { - postInsertFired = true; - } - - @EntityListener - public static class ImmutablePersonListener { - public ImmutablePersonListener() { - // TODO Auto-generated constructor stub - } - - @PostLoad - public void afterLoad(ImmutablePerson person) { - person.postLoadFired = true; - } - } + public List getOtherNumbers() { + return otherNumbers; + } + + public boolean isPreInsertFired() { + return preInsertFired; + } + + public boolean isPostInsertFired() { + return postInsertFired; + } + + public boolean isPostLoadFired() { + return postLoadFired; + } + + @Override + public String toString() { + StringBuilder builder2 = new StringBuilder(); + builder2.append("ImmutablePerson [id=").append(id).append(", name=").append(name) + .append(", address=").append(address).append(", key=").append(key).append(", phoneNumber=") + .append(phoneNumber).append(", otherNumbers=").append(otherNumbers).append(", modifiedOn=") + .append(modifiedOn).append("]"); + return builder2.toString(); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder { + private long id; + + private String name; + + private ImmutableAddress address; + + private ImmutablePhone phoneNumber; + + private List otherNumbers; + + private DatastoreKey key; + + private OffsetDateTime modifiedOn; + + private Builder() { + + } + + public Builder setId(long id) { + this.id = id; + return this; + } + + public Builder withName(String name) { + this.name = name; + return this; + } + + public Builder setAddress(ImmutableAddress address) { + this.address = address; + return this; + } + + public Builder phoneNumber(ImmutablePhone phoneNumber) { + this.phoneNumber = phoneNumber; + return this; + } + + public Builder setOtherNumbers(List otherNumbers) { + this.otherNumbers = otherNumbers; + return this; + } + + public Builder setKey(DatastoreKey key) { + this.key = key; + return this; + } + + public Builder setModifiedOn(OffsetDateTime modifiedOn) { + this.modifiedOn = modifiedOn; + return this; + } + + public ImmutablePerson build() { + return new ImmutablePerson(this); + } + + } + + @Override + public boolean equals(Object obj) { + if (equalsExceptAutoGeneratedFields(obj)) { + ImmutablePerson that = (ImmutablePerson) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.modifiedOn, that.modifiedOn) + && Objects.equals(this.key, that.key); + } + return false; + } + + public boolean equalsExceptAutoGeneratedFields(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + ImmutablePerson that = (ImmutablePerson) obj; + return Objects.equals(this.name, that.name) && Objects.equals(this.address, that.address) + && Objects.equals(this.phoneNumber, that.phoneNumber) + && Objects.equals(this.otherNumbers, that.otherNumbers); + } + + public static ImmutablePerson getSample1() { + ImmutableZipCode.Builder zipBuilder = ImmutableZipCode.newBuilder(); + zipBuilder.setFiveDigits("55555"); + zipBuilder.setFourDgits("4444"); + ImmutableZipCode zip = zipBuilder.build(); + + ImmutablePerson person = ImmutablePerson.newBuilder().withName("John Doe") + .setAddress(ImmutableAddress.builder().setLine1("1 Main St.").setLine2("Apt 450") + .setCity("San Francisco").setState("CA").setZipCode(zip).build()) + .phoneNumber(ImmutablePhone.getSample1()).setOtherNumbers(ImmutablePhone.getSampleList()) + .build(); + return person; + } + + public static ImmutablePerson getSample2() { + return ImmutablePerson.newBuilder().build(); + } + + public static ImmutablePerson getSample3() { + ImmutableZipCode.Builder zipBuilder = ImmutableZipCode.newBuilder(); + zipBuilder.setFiveDigits("55555"); + ImmutableZipCode zip = zipBuilder.build(); + + ImmutablePerson person = ImmutablePerson.newBuilder().withName("John Doe") + .setAddress(ImmutableAddress.builder().setLine1("1 Main St.").setLine2("Apt 450") + .setCity("San Francisco").setState("CA").setZipCode(zip).build()) + .phoneNumber(ImmutablePhone.getSample1()).setOtherNumbers(ImmutablePhone.getSampleList()) + .build(); + return person; + } + + @PreInsert + public void beforeInsert() { + preInsertFired = true; + } + + @PostInsert + public void afterInsert() { + postInsertFired = true; + } + + @EntityListener + public static class ImmutablePersonListener { + public ImmutablePersonListener() { + // TODO Auto-generated constructor stub + } + + @PostLoad + public void afterLoad(ImmutablePerson person) { + person.postLoadFired = true; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutablePhone.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutablePhone.java index 57755db..6ba08a8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutablePhone.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutablePhone.java @@ -1,3 +1,4 @@ + package com.jmethods.catatumbo.entities; import java.util.Arrays; @@ -9,98 +10,100 @@ @Embeddable public class ImmutablePhone { - private final String countryCode; - private final String areaCode; - private final String subscriberNumber; - - public ImmutablePhone(Builder builder) { - this.countryCode = builder.countryCode; - this.areaCode = builder.areaCode; - this.subscriberNumber = builder.subscriberNumber; - } - - public String getCountryCode() { - return countryCode; - } - - public String getAreaCode() { - return areaCode; - } - - public String getSubscriberNumber() { - return subscriberNumber; - } - - @Override - public String toString() { - StringBuilder builder2 = new StringBuilder(); - builder2.append("ImmutablePhone [countryCode=").append(countryCode).append(", areaCode=").append(areaCode) - .append(", subscriberNumber=").append(subscriberNumber).append("]"); - return builder2.toString(); - } - - public static Builder newBuilder() { - return new Builder(); - } - - public static int newBuilder2() { - return 0; - } - - public static class Builder { - private String countryCode; - private String areaCode; - private String subscriberNumber; - - public Builder setCountryCode(String countryCode) { - this.countryCode = countryCode; - return this; - } - - public Builder setAreaCode(String areaCode) { - this.areaCode = areaCode; - return this; - } - - public Builder setSubscriberNumber(String subscriberNumber) { - this.subscriberNumber = subscriberNumber; - return this; - } - - public ImmutablePhone build() { - return new ImmutablePhone(this); - } - - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - ImmutablePhone that = (ImmutablePhone) obj; - return Objects.equals(this.countryCode, that.countryCode) && Objects.equals(this.areaCode, that.areaCode) - && Objects.equals(this.subscriberNumber, that.subscriberNumber); - } - - public static ImmutablePhone getSample1() { - return ImmutablePhone.newBuilder().setAreaCode("4").setAreaCode("20").setSubscriberNumber("98765432").build(); - } - - public static ImmutablePhone getSample2() { - return ImmutablePhone.newBuilder().setAreaCode("91").setAreaCode("040").setSubscriberNumber("1122334455") - .build(); - } - - public static ImmutablePhone getSample3() { - return ImmutablePhone.newBuilder().setAreaCode("91").setAreaCode("080").setSubscriberNumber("9988776655") - .build(); - } - - public static List getSampleList() { - return Arrays.asList(new ImmutablePhone[] { getSample2(), getSample3() }); - } + private final String countryCode; + private final String areaCode; + private final String subscriberNumber; + + public ImmutablePhone(Builder builder) { + this.countryCode = builder.countryCode; + this.areaCode = builder.areaCode; + this.subscriberNumber = builder.subscriberNumber; + } + + public String getCountryCode() { + return countryCode; + } + + public String getAreaCode() { + return areaCode; + } + + public String getSubscriberNumber() { + return subscriberNumber; + } + + @Override + public String toString() { + StringBuilder builder2 = new StringBuilder(); + builder2.append("ImmutablePhone [countryCode=").append(countryCode).append(", areaCode=") + .append(areaCode).append(", subscriberNumber=").append(subscriberNumber).append("]"); + return builder2.toString(); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static int newBuilder2() { + return 0; + } + + public static class Builder { + private String countryCode; + private String areaCode; + private String subscriberNumber; + + public Builder setCountryCode(String countryCode) { + this.countryCode = countryCode; + return this; + } + + public Builder setAreaCode(String areaCode) { + this.areaCode = areaCode; + return this; + } + + public Builder setSubscriberNumber(String subscriberNumber) { + this.subscriberNumber = subscriberNumber; + return this; + } + + public ImmutablePhone build() { + return new ImmutablePhone(this); + } + + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + ImmutablePhone that = (ImmutablePhone) obj; + return Objects.equals(this.countryCode, that.countryCode) + && Objects.equals(this.areaCode, that.areaCode) + && Objects.equals(this.subscriberNumber, that.subscriberNumber); + } + + public static ImmutablePhone getSample1() { + return ImmutablePhone.newBuilder().setAreaCode("4").setAreaCode("20") + .setSubscriberNumber("98765432").build(); + } + + public static ImmutablePhone getSample2() { + return ImmutablePhone.newBuilder().setAreaCode("91").setAreaCode("040") + .setSubscriberNumber("1122334455").build(); + } + + public static ImmutablePhone getSample3() { + return ImmutablePhone.newBuilder().setAreaCode("91").setAreaCode("080") + .setSubscriberNumber("9988776655").build(); + } + + public static List getSampleList() { + return Arrays.asList(new ImmutablePhone[] { getSample2(), getSample3() }); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutableSubClass.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutableSubClass.java index c3fd14a..752842e 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutableSubClass.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutableSubClass.java @@ -27,74 +27,75 @@ @Entity public class ImmutableSubClass extends ImmutableSuperClass { - private String name; - - private ImmutableSubClass(Builder builder) { - super(builder); - this.name = builder.name; - } - - public String getName() { - return name; - } - - public static Builder newBuilder() { - return new Builder(); - } - - @Override - public String toString() { - StringBuilder builder2 = new StringBuilder(); - builder2.append("ImmutableSubClass [name=").append(name).append(", getId()=").append(getId()) - .append(", getKey()=").append(getKey()).append(", getCreatedTimestamp()=").append(getCreatedTimestamp()) - .append(", getModifiedTimestamp()=").append(getModifiedTimestamp()).append(", getVersion()=") - .append(getVersion()).append("]"); - return builder2.toString(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - if (equalsExceptGeneratedValues(obj)) { - ImmutableSubClass that = (ImmutableSubClass) obj; - return Objects.equals(this.getId(), that.getId()) && Objects.equals(this.getKey(), that.getKey()) - && Objects.equals(this.getCreatedTimestamp(), that.getCreatedTimestamp()) - && Objects.equals(this.getModifiedTimestamp(), that.getModifiedTimestamp()); - - } - return false; - } - - public boolean equalsExceptGeneratedValues(Object obj) { - if (obj == this) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - ImmutableSubClass that = (ImmutableSubClass) obj; - return Objects.equals(this.name, that.name); - } - - public static class Builder extends ImmutableSuperClass.Builder { - - private String name; - - public Builder setName(String name) { - this.name = name; - return this; - } - - @Override - public ImmutableSubClass build() { - return new ImmutableSubClass(this); - } - - } + private String name; + + private ImmutableSubClass(Builder builder) { + super(builder); + this.name = builder.name; + } + + public String getName() { + return name; + } + + public static Builder newBuilder() { + return new Builder(); + } + + @Override + public String toString() { + StringBuilder builder2 = new StringBuilder(); + builder2.append("ImmutableSubClass [name=").append(name).append(", getId()=").append(getId()) + .append(", getKey()=").append(getKey()).append(", getCreatedTimestamp()=") + .append(getCreatedTimestamp()).append(", getModifiedTimestamp()=") + .append(getModifiedTimestamp()).append(", getVersion()=").append(getVersion()).append("]"); + return builder2.toString(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + if (equalsExceptGeneratedValues(obj)) { + ImmutableSubClass that = (ImmutableSubClass) obj; + return Objects.equals(this.getId(), that.getId()) + && Objects.equals(this.getKey(), that.getKey()) + && Objects.equals(this.getCreatedTimestamp(), that.getCreatedTimestamp()) + && Objects.equals(this.getModifiedTimestamp(), that.getModifiedTimestamp()); + + } + return false; + } + + public boolean equalsExceptGeneratedValues(Object obj) { + if (obj == this) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + ImmutableSubClass that = (ImmutableSubClass) obj; + return Objects.equals(this.name, that.name); + } + + public static class Builder extends ImmutableSuperClass.Builder { + + private String name; + + public Builder setName(String name) { + this.name = name; + return this; + } + + @Override + public ImmutableSubClass build() { + return new ImmutableSubClass(this); + } + + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutableSuperClass.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutableSuperClass.java index d1be839..2d99fb8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutableSuperClass.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutableSuperClass.java @@ -34,99 +34,99 @@ @MappedSuperClass public class ImmutableSuperClass { - @Identifier - private String id; + @Identifier + private String id; - @Key - private DatastoreKey key; + @Key + private DatastoreKey key; - @CreatedTimestamp - @Property(name = "createdTS") - private Date createdTimestamp; + @CreatedTimestamp + @Property(name = "createdTS") + private Date createdTimestamp; - @UpdatedTimestamp - @Property(name = "updatedTS") - private Date modifiedTimestamp; + @UpdatedTimestamp + @Property(name = "updatedTS") + private Date modifiedTimestamp; - @Version - private long version; + @Version + private long version; - private ImmutableSuperClass() { + private ImmutableSuperClass() { - } + } - public ImmutableSuperClass(Builder builder) { - this.id = builder.id; - this.key = builder.key; - this.createdTimestamp = builder.createdTimestamp; - this.modifiedTimestamp = builder.modifiedTimestamp; - this.version = builder.version; - } + public ImmutableSuperClass(Builder builder) { + this.id = builder.id; + this.key = builder.key; + this.createdTimestamp = builder.createdTimestamp; + this.modifiedTimestamp = builder.modifiedTimestamp; + this.version = builder.version; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public DatastoreKey getKey() { - return key; - } + public DatastoreKey getKey() { + return key; + } - public Date getCreatedTimestamp() { - return createdTimestamp; - } + public Date getCreatedTimestamp() { + return createdTimestamp; + } - public Date getModifiedTimestamp() { - return modifiedTimestamp; - } + public Date getModifiedTimestamp() { + return modifiedTimestamp; + } - public long getVersion() { - return version; - } + public long getVersion() { + return version; + } - public static Builder builder() { - return new Builder<>(); - } + public static Builder builder() { + return new Builder<>(); + } - public static class Builder> { - private String id; + public static class Builder> { + private String id; - private DatastoreKey key; + private DatastoreKey key; - private Date createdTimestamp; + private Date createdTimestamp; - private Date modifiedTimestamp; + private Date modifiedTimestamp; - private long version; + private long version; - public T setId(String id) { - this.id = id; - return (T) this; - } + public T setId(String id) { + this.id = id; + return (T) this; + } - public T key(DatastoreKey key) { - this.key = key; - return (T) this; - } + public T key(DatastoreKey key) { + this.key = key; + return (T) this; + } - public T setCreatedTimestamp(Date createdTimestamp) { - this.createdTimestamp = createdTimestamp; - return (T) this; - } + public T setCreatedTimestamp(Date createdTimestamp) { + this.createdTimestamp = createdTimestamp; + return (T) this; + } - public T setModifiedTimestamp(Date modifiedTimestamp) { - this.modifiedTimestamp = modifiedTimestamp; - return (T) this; - } + public T setModifiedTimestamp(Date modifiedTimestamp) { + this.modifiedTimestamp = modifiedTimestamp; + return (T) this; + } - public T withVersion(long version) { - this.version = version; - return (T) this; - } + public T withVersion(long version) { + this.version = version; + return (T) this; + } - public ImmutableSuperClass build() { - return new ImmutableSuperClass(this); - } + public ImmutableSuperClass build() { + return new ImmutableSuperClass(this); + } - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ImmutableZipCode.java b/src/test/java/com/jmethods/catatumbo/entities/ImmutableZipCode.java index 08007dc..6fa5d32 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ImmutableZipCode.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ImmutableZipCode.java @@ -28,89 +28,90 @@ @Embeddable public class ImmutableZipCode { - private String fiveDigits; - - @Property(optional = true) - private String fourDgits; - - /** - * - */ - public ImmutableZipCode(Builder builder) { - this.fiveDigits = builder.fiveDigits; - this.fourDgits = builder.fourDgits; - } - - /** - * @return the fiveDigits - */ - public String getFiveDigits() { - return fiveDigits; - } - - /** - * @return the fourDgits - */ - public String getFourDgits() { - return fourDgits; - } - - public static Builder newBuilder() { - return new Builder(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder2 = new StringBuilder(); - builder2.append("ImmutableZipCode [fiveDigits=").append(fiveDigits).append(", fourDgits=").append(fourDgits) - .append("]"); - return builder2.toString(); - } - - public static class Builder { - private String fiveDigits; - private String fourDgits; - - private Builder() { - - } - - /** - * @param fiveDigits - * the fiveDigits to set - */ - public void setFiveDigits(String fiveDigits) { - this.fiveDigits = fiveDigits; - } - - /** - * @param fourDgits - * the fourDgits to set - */ - public void setFourDgits(String fourDgits) { - this.fourDgits = fourDgits; - } - - public ImmutableZipCode build() { - return new ImmutableZipCode(this); - } - - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - ImmutableZipCode that = (ImmutableZipCode) obj; - return Objects.equals(this.fiveDigits, that.fiveDigits) && Objects.equals(this.fourDgits, that.fourDgits); - } + private String fiveDigits; + + @Property(optional = true) + private String fourDgits; + + /** + * + */ + public ImmutableZipCode(Builder builder) { + this.fiveDigits = builder.fiveDigits; + this.fourDgits = builder.fourDgits; + } + + /** + * @return the fiveDigits + */ + public String getFiveDigits() { + return fiveDigits; + } + + /** + * @return the fourDgits + */ + public String getFourDgits() { + return fourDgits; + } + + public static Builder newBuilder() { + return new Builder(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder2 = new StringBuilder(); + builder2.append("ImmutableZipCode [fiveDigits=").append(fiveDigits).append(", fourDgits=") + .append(fourDgits).append("]"); + return builder2.toString(); + } + + public static class Builder { + private String fiveDigits; + private String fourDgits; + + private Builder() { + + } + + /** + * @param fiveDigits + * the fiveDigits to set + */ + public void setFiveDigits(String fiveDigits) { + this.fiveDigits = fiveDigits; + } + + /** + * @param fourDgits + * the fourDgits to set + */ + public void setFourDgits(String fourDgits) { + this.fourDgits = fourDgits; + } + + public ImmutableZipCode build() { + return new ImmutableZipCode(this); + } + + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + ImmutableZipCode that = (ImmutableZipCode) obj; + return Objects.equals(this.fiveDigits, that.fiveDigits) + && Objects.equals(this.fourDgits, that.fourDgits); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/IntegerField.java b/src/test/java/com/jmethods/catatumbo/entities/IntegerField.java index d3f5584..700f8b3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/IntegerField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/IntegerField.java @@ -26,39 +26,39 @@ @Entity public class IntegerField { - @Identifier - private long id; + @Identifier + private long id; - private int count; + private int count; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the count - */ - public int getCount() { - return count; - } + /** + * @return the count + */ + public int getCount() { + return count; + } - /** - * @param count - * the count to set - */ - public void setCount(int count) { - this.count = count; - } + /** + * @param count + * the count to set + */ + public void setCount(int count) { + this.count = count; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/IntegerObject.java b/src/test/java/com/jmethods/catatumbo/entities/IntegerObject.java index 089f56f..b733af6 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/IntegerObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/IntegerObject.java @@ -26,39 +26,39 @@ @Entity public class IntegerObject { - @Identifier - private long id; + @Identifier + private long id; - private Integer count; + private Integer count; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the count - */ - public Integer getCount() { - return count; - } + /** + * @return the count + */ + public Integer getCount() { + return count; + } - /** - * @param count - * the count to set - */ - public void setCount(Integer count) { - this.count = count; - } + /** + * @param count + * the count to set + */ + public void setCount(Integer count) { + this.count = count; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/InternalCalculatorEntity.java b/src/test/java/com/jmethods/catatumbo/entities/InternalCalculatorEntity.java index 99b63b0..37668ef 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/InternalCalculatorEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/InternalCalculatorEntity.java @@ -29,29 +29,29 @@ @Entity public class InternalCalculatorEntity extends CalculatorEntity { - /** - * - */ - public InternalCalculatorEntity() { - super(); - } + /** + * + */ + public InternalCalculatorEntity() { + super(); + } - /** - * @param operand1 - * @param operand2 - */ - public InternalCalculatorEntity(long operand1, long operand2) { - super(operand1, operand2); - } + /** + * @param operand1 + * @param operand2 + */ + public InternalCalculatorEntity(long operand1, long operand2) { + super(operand1, operand2); + } - @PreInsert - @PreUpdate - @PreUpsert - @PreDelete - public void beforeEvent() { - setSum(getOperand1() + getOperand2()); - setProduct(getOperand1() * getOperand2()); - setDifference(getOperand1() - getOperand2()); - } + @PreInsert + @PreUpdate + @PreUpsert + @PreDelete + public void beforeEvent() { + setSum(getOperand1() + getOperand2()); + setProduct(getOperand1() * getOperand2()); + setDifference(getOperand1() - getOperand2()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Item.java b/src/test/java/com/jmethods/catatumbo/entities/Item.java index bef6f4e..c59c777 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Item.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Item.java @@ -31,87 +31,88 @@ @Entity public class Item { - @Identifier - private long id; - - private String name; - - @PropertyMapper(CurrencyMapper.class) - private BigDecimal price; - - @PropertyMapper(CurrencyMapper.class) - private BigDecimal discount; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the price - */ - public BigDecimal getPrice() { - return price; - } - - /** - * @param price - * the price to set - */ - public void setPrice(BigDecimal price) { - this.price = price; - } - - /** - * @return the discount - */ - public BigDecimal getDiscount() { - return discount; - } - - /** - * @param discount - * the discount to set - */ - public void setDiscount(BigDecimal discount) { - this.discount = discount; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Item)) { - return false; - } - if (this == obj) { - return true; - } - Item that = (Item) obj; - return this.id == that.id && Objects.equals(this.name, that.name) && Objects.equals(this.price, that.price); - } + @Identifier + private long id; + + private String name; + + @PropertyMapper(CurrencyMapper.class) + private BigDecimal price; + + @PropertyMapper(CurrencyMapper.class) + private BigDecimal discount; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the price + */ + public BigDecimal getPrice() { + return price; + } + + /** + * @param price + * the price to set + */ + public void setPrice(BigDecimal price) { + this.price = price; + } + + /** + * @return the discount + */ + public BigDecimal getDiscount() { + return discount; + } + + /** + * @param discount + * the discount to set + */ + public void setDiscount(BigDecimal discount) { + this.discount = discount; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Item)) { + return false; + } + if (this == obj) { + return true; + } + Item that = (Item) obj; + return this.id == that.id && Objects.equals(this.name, that.name) + && Objects.equals(this.price, that.price); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/KeyListField.java b/src/test/java/com/jmethods/catatumbo/entities/KeyListField.java index bed7df2..a6761e7 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/KeyListField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/KeyListField.java @@ -29,39 +29,39 @@ @Entity public class KeyListField { - @Identifier - private long id; + @Identifier + private long id; - private List tags; + private List tags; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the tags - */ - public List getTags() { - return tags; - } + /** + * @return the tags + */ + public List getTags() { + return tags; + } - /** - * @param tags - * the tags to set - */ - public void setTags(List tags) { - this.tags = tags; - } + /** + * @param tags + * the tags to set + */ + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Lion.java b/src/test/java/com/jmethods/catatumbo/entities/Lion.java index 219cf35..4d64b1c 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Lion.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Lion.java @@ -27,12 +27,12 @@ @Entity @ExcludeDefaultListeners public class Lion extends WildAnimal { - @PreInsert - public void insertingLion() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Lion.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingLion() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Lion.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ListFields.java b/src/test/java/com/jmethods/catatumbo/entities/ListFields.java index d8f4301..8e5472a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ListFields.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ListFields.java @@ -44,556 +44,570 @@ @Entity public class ListFields { - @Identifier - private long id; + @Identifier + private long id; - private List booleanList; + private List booleanList; - private List charList; + private List charList; - private List shortList; + private List shortList; - private List intList; + private List intList; - private List longList; + private List longList; - private List stringList; + private List stringList; - private List dateList; + private List dateList; - private List calendarList; + private List calendarList; - private List colorList; + private List colorList; - private List floatList; + private List floatList; - private List doubleList; + private List doubleList; - private List blobList; + private List blobList; - private List clobList; + private List clobList; - private List objectList; + private List objectList; - private List wildcardList; + private List wildcardList; - private ArrayList arrayList; + private ArrayList arrayList; - private LinkedList linkedList; + private LinkedList linkedList; - private Vector vector; + private Vector vector; - private Stack stack; + private Stack stack; - private List keyList; + private List keyList; - private List geoLocationList; + private List geoLocationList; - private List localDateList; + private List localDateList; - private List localTimeList; + private List localTimeList; - private List localDateTimeList; + private List localDateTimeList; - private List offsetDateTimeList; + private List offsetDateTimeList; - private List zonedDateTimeList; + private List zonedDateTimeList; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the booleanList - */ - public List getBooleanList() { - return booleanList; - } - - /** - * @param booleanList - * the booleanList to set - */ - public void setBooleanList(List booleanList) { - this.booleanList = booleanList; - } - - /** - * @return the charList - */ - public List getCharList() { - return charList; - } - - /** - * @param charList - * the charList to set - */ - public void setCharList(List charList) { - this.charList = charList; - } - - /** - * @return the shortList - */ - public List getShortList() { - return shortList; - } - - /** - * @param shortList - * the shortList to set - */ - public void setShortList(List shortList) { - this.shortList = shortList; - } - - /** - * @return the intList - */ - public List getIntList() { - return intList; - } - - /** - * @param intList - * the intList to set - */ - public void setIntList(List intList) { - this.intList = intList; - } - - /** - * @return the longList - */ - public List getLongList() { - return longList; - } - - /** - * @param longList - * the longList to set - */ - public void setLongList(List longList) { - this.longList = longList; - } - - /** - * @return the stringList - */ - public List getStringList() { - return stringList; - } - - /** - * @param stringList - * the stringList to set - */ - public void setStringList(List stringList) { - this.stringList = stringList; - } - - /** - * @return the dateList - */ - public List getDateList() { - return dateList; - } - - /** - * @param dateList - * the dateList to set - */ - public void setDateList(List dateList) { - this.dateList = dateList; - } - - /** - * @return the calendarList - */ - public List getCalendarList() { - return calendarList; - } - - /** - * @param calendarList - * the calendarList to set - */ - public void setCalendarList(List calendarList) { - this.calendarList = calendarList; - } - - /** - * @return the colorList - */ - public List getColorList() { - return colorList; - } - - /** - * @param colorList - * the colorList to set - */ - public void setColorList(List colorList) { - this.colorList = colorList; - } - - /** - * @return the floatList - */ - public List getFloatList() { - return floatList; - } - - /** - * @param floatList - * the floatList to set - */ - public void setFloatList(List floatList) { - this.floatList = floatList; - } - - /** - * @return the doubleList - */ - public List getDoubleList() { - return doubleList; - } - - /** - * @param doubleList - * the doubleList to set - */ - public void setDoubleList(List doubleList) { - this.doubleList = doubleList; - } - - /** - * @return the blobList - */ - public List getBlobList() { - return blobList; - } - - /** - * @param blobList - * the blobList to set - */ - public void setBlobList(List blobList) { - this.blobList = blobList; - } - - /** - * @return the clobList - */ - public List getClobList() { - return clobList; - } - - /** - * @param clobList - * the clobList to set - */ - public void setClobList(List clobList) { - this.clobList = clobList; - } - - /** - * @return the objectList - */ - public List getObjectList() { - return objectList; - } - - /** - * @param objectList - * the objectList to set - */ - public void setObjectList(List objectList) { - this.objectList = objectList; - } - - /** - * @return the wildcardList - */ - public List getWildcardList() { - return wildcardList; - } - - /** - * @param wildcardList - * the wildcardList to set - */ - public void setWildcardList(List wildcardList) { - this.wildcardList = wildcardList; - } - - /** - * @return the arrayList - */ - public ArrayList getArrayList() { - return arrayList; - } - - /** - * @param arrayList - * the arrayList to set - */ - public void setArrayList(ArrayList arrayList) { - this.arrayList = arrayList; - } - - /** - * @return the linkedList - */ - public LinkedList getLinkedList() { - return linkedList; - } - - /** - * @param linkedList - * the linkedList to set - */ - public void setLinkedList(LinkedList linkedList) { - this.linkedList = linkedList; - } - - /** - * @return the stack - */ - public Stack getStack() { - return stack; - } - - /** - * @param stack - * the stack to set - */ - public void setStack(Stack stack) { - this.stack = stack; - } - - /** - * @return the vector - */ - public Vector getVector() { - return vector; - } - - /** - * @param vector - * the vector to set - */ - public void setVector(Vector vector) { - this.vector = vector; - } - - /** - * @return the keyList - */ - public List getKeyList() { - return keyList; - } - - /** - * @param keyList - * the keyList to set - */ - public void setKeyList(List keyList) { - this.keyList = keyList; - } - - /** - * @return the geoLocationList - */ - public List getGeoLocationList() { - return geoLocationList; - } - - /** - * @param geoLocationList - * the geoLocationList to set - */ - public void setGeoLocationList(List geoLocationList) { - this.geoLocationList = geoLocationList; - } - - /** - * @return the localDateList - */ - public List getLocalDateList() { - return localDateList; - } - - /** - * @param localDateList - * the localDateList to set - */ - public void setLocalDateList(List localDateList) { - this.localDateList = localDateList; - } - - /** - * @return the localTimeList - */ - public List getLocalTimeList() { - return localTimeList; - } - - /** - * @param localTimeList - * the localTimeList to set - */ - public void setLocalTimeList(List localTimeList) { - this.localTimeList = localTimeList; - } - - /** - * @return the localDateTimeList - */ - public List getLocalDateTimeList() { - return localDateTimeList; - } - - /** - * @param localDateTimeList - * the localDateTimeList to set - */ - public void setLocalDateTimeList(List localDateTimeList) { - this.localDateTimeList = localDateTimeList; - } - - /** - * @return the offsetDateTimeList - */ - public List getOffsetDateTimeList() { - return offsetDateTimeList; - } - - /** - * @param offsetDateTimeList - * the offsetDateTimeList to set - */ - public void setOffsetDateTimeList(List offsetDateTimeList) { - this.offsetDateTimeList = offsetDateTimeList; - } - - /** - * @return the zonedDateTimeList - */ - public List getZonedDateTimeList() { - return zonedDateTimeList; - } - - /** - * @param zonedDateTimeList - * the zonedDateTimeList to set - */ - public void setZonedDateTimeList(List zonedDateTimeList) { - this.zonedDateTimeList = zonedDateTimeList; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof ListFields)) { - return false; - } - if (this == obj) { - return true; - } - ListFields that = (ListFields) obj; - - return Objects.equals(this.booleanList, that.booleanList) && Objects.equals(this.charList, that.charList) - && Objects.equals(this.shortList, that.shortList) && Objects.equals(this.intList, that.intList) - && Objects.equals(this.longList, that.longList) && Objects.equals(this.stringList, that.stringList) - && Objects.equals(this.dateList, that.dateList) && Objects.equals(this.calendarList, that.calendarList) - && Objects.equals(this.floatList, that.floatList) && Objects.equals(this.doubleList, that.doubleList) - // && Objects.deepEquals(this.blobList, that.blobList) && - // Objects.deepEquals(this.clobList, that.clobList) - && Objects.equals(this.colorList, that.colorList) && Objects.equals(this.objectList, that.objectList) - && Objects.equals(this.wildcardList, that.wildcardList) - && Objects.equals(this.arrayList, that.arrayList) && Objects.equals(this.linkedList, that.linkedList) - && Objects.equals(this.stack, that.stack) && Objects.equals(this.vector, that.vector) - && Objects.equals(this.keyList, that.keyList) - && Objects.equals(this.geoLocationList, that.geoLocationList) - && Objects.equals(this.localDateList, that.localDateList) - && Objects.equals(this.localTimeList, that.localTimeList) - && Objects.equals(this.localDateTimeList, that.localDateTimeList) - && Objects.equals(this.offsetDateTimeList, that.offsetDateTimeList) - && Objects.equals(this.zonedDateTimeList, that.zonedDateTimeList); - } - - public static ListFields getSampleEntity1() { - ListFields entity = new ListFields(); - entity.setBooleanList(Arrays.asList(true, false, false, true)); - entity.setCharList(Arrays.asList('Z', 'Y', 'X')); - entity.setShortList(Arrays.asList((short) 3, (short) 33, (short) 333)); - entity.setIntList(Arrays.asList(100, 200, 300)); - entity.setLongList(Arrays.asList(-3L, 0L, 3L, 987654321L)); - entity.setStringList(Arrays.asList("One", "Ten", "Hundred")); - long millis = System.currentTimeMillis(); - entity.setDateList(Arrays.asList(new Date(millis), new Date(millis + 60000), new Date(millis - 60000))); - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); - cal2.add(Calendar.DATE, 1); - Calendar cal3 = Calendar.getInstance(); - cal2.add(Calendar.DATE, -1); - entity.setCalendarList(Arrays.asList(cal1, cal2, cal3)); - entity.setColorList(Arrays.asList(Color.PINK, Color.BLACK, Color.YELLOW)); - entity.setFloatList(Arrays.asList(1.5f, 200f, Float.MAX_VALUE)); - entity.setDoubleList(Arrays.asList(Double.MIN_VALUE, 5000d, Double.MAX_VALUE)); - entity.setBlobList(Arrays.asList("One".getBytes(), "Two".getBytes())); - entity.setClobList(Arrays.asList("One".toCharArray(), "Two".toCharArray())); - entity.setObjectList(Arrays.asList("One", 5000L, (Object) 99.99d, Boolean.FALSE, (String) null)); - entity.setWildcardList(Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); - ArrayList arrayList = new ArrayList<>(); - arrayList.addAll(Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); - entity.setArrayList(arrayList); - LinkedList linkedList = new LinkedList<>(); - linkedList.addAll(Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); - entity.setLinkedList(linkedList); - Stack stack = new Stack<>(); - stack.addAll(Arrays.asList(3, 2, 1)); - entity.setStack(stack); - Vector vector = new Vector<>(); - vector.addAll(Arrays.asList(1.5f, 2.5f, 4.98f)); - entity.setVector(vector); - List geoLocationList = Arrays.asList(new GeoLocation(40.7142700, -74.0059700), - new GeoLocation(48.8534100, 2.3488000)); - entity.setGeoLocationList(geoLocationList); - LocalDate today = LocalDate.now(); - LocalDate tomorrow = today.plusDays(1); - entity.setLocalDateList(Arrays.asList(today, tomorrow)); - - LocalTime now = LocalTime.now(); - LocalTime anHourFromNow = now.plusHours(1); - entity.setLocalTimeList(Arrays.asList(null, now, anHourFromNow)); - - LocalDateTime ldt1 = LocalDateTime.now(); - LocalDateTime ldt2 = ldt1.plusDays(1); - entity.setLocalDateTimeList(Arrays.asList(null, ldt1, ldt2, LocalDateTime.MIN, LocalDateTime.MIN)); - - OffsetDateTime odt1 = OffsetDateTime.now(); - OffsetDateTime odt2 = odt1.plusYears(1); - OffsetDateTime odtLow = OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.of("Z")); - OffsetDateTime odtHigh = OffsetDateTime.of(9999, 12, 31, 23, 59, 59, 999999999, ZoneOffset.of("Z")); - entity.setOffsetDateTimeList(Arrays.asList(null, odt1, odt2, odtLow, odtHigh)); - - ZonedDateTime zdt1 = ZonedDateTime.now(); - ZonedDateTime zdt2 = zdt1.plusMonths(1); - entity.setZonedDateTimeList(Arrays.asList(null, zdt1, zdt2)); - return entity; - } + /** + * @return the booleanList + */ + public List getBooleanList() { + return booleanList; + } + + /** + * @param booleanList + * the booleanList to set + */ + public void setBooleanList(List booleanList) { + this.booleanList = booleanList; + } + + /** + * @return the charList + */ + public List getCharList() { + return charList; + } + + /** + * @param charList + * the charList to set + */ + public void setCharList(List charList) { + this.charList = charList; + } + + /** + * @return the shortList + */ + public List getShortList() { + return shortList; + } + + /** + * @param shortList + * the shortList to set + */ + public void setShortList(List shortList) { + this.shortList = shortList; + } + + /** + * @return the intList + */ + public List getIntList() { + return intList; + } + + /** + * @param intList + * the intList to set + */ + public void setIntList(List intList) { + this.intList = intList; + } + + /** + * @return the longList + */ + public List getLongList() { + return longList; + } + + /** + * @param longList + * the longList to set + */ + public void setLongList(List longList) { + this.longList = longList; + } + + /** + * @return the stringList + */ + public List getStringList() { + return stringList; + } + + /** + * @param stringList + * the stringList to set + */ + public void setStringList(List stringList) { + this.stringList = stringList; + } + + /** + * @return the dateList + */ + public List getDateList() { + return dateList; + } + + /** + * @param dateList + * the dateList to set + */ + public void setDateList(List dateList) { + this.dateList = dateList; + } + + /** + * @return the calendarList + */ + public List getCalendarList() { + return calendarList; + } + + /** + * @param calendarList + * the calendarList to set + */ + public void setCalendarList(List calendarList) { + this.calendarList = calendarList; + } + + /** + * @return the colorList + */ + public List getColorList() { + return colorList; + } + + /** + * @param colorList + * the colorList to set + */ + public void setColorList(List colorList) { + this.colorList = colorList; + } + + /** + * @return the floatList + */ + public List getFloatList() { + return floatList; + } + + /** + * @param floatList + * the floatList to set + */ + public void setFloatList(List floatList) { + this.floatList = floatList; + } + + /** + * @return the doubleList + */ + public List getDoubleList() { + return doubleList; + } + + /** + * @param doubleList + * the doubleList to set + */ + public void setDoubleList(List doubleList) { + this.doubleList = doubleList; + } + + /** + * @return the blobList + */ + public List getBlobList() { + return blobList; + } + + /** + * @param blobList + * the blobList to set + */ + public void setBlobList(List blobList) { + this.blobList = blobList; + } + + /** + * @return the clobList + */ + public List getClobList() { + return clobList; + } + + /** + * @param clobList + * the clobList to set + */ + public void setClobList(List clobList) { + this.clobList = clobList; + } + + /** + * @return the objectList + */ + public List getObjectList() { + return objectList; + } + + /** + * @param objectList + * the objectList to set + */ + public void setObjectList(List objectList) { + this.objectList = objectList; + } + + /** + * @return the wildcardList + */ + public List getWildcardList() { + return wildcardList; + } + + /** + * @param wildcardList + * the wildcardList to set + */ + public void setWildcardList(List wildcardList) { + this.wildcardList = wildcardList; + } + + /** + * @return the arrayList + */ + public ArrayList getArrayList() { + return arrayList; + } + + /** + * @param arrayList + * the arrayList to set + */ + public void setArrayList(ArrayList arrayList) { + this.arrayList = arrayList; + } + + /** + * @return the linkedList + */ + public LinkedList getLinkedList() { + return linkedList; + } + + /** + * @param linkedList + * the linkedList to set + */ + public void setLinkedList(LinkedList linkedList) { + this.linkedList = linkedList; + } + + /** + * @return the stack + */ + public Stack getStack() { + return stack; + } + + /** + * @param stack + * the stack to set + */ + public void setStack(Stack stack) { + this.stack = stack; + } + + /** + * @return the vector + */ + public Vector getVector() { + return vector; + } + + /** + * @param vector + * the vector to set + */ + public void setVector(Vector vector) { + this.vector = vector; + } + + /** + * @return the keyList + */ + public List getKeyList() { + return keyList; + } + + /** + * @param keyList + * the keyList to set + */ + public void setKeyList(List keyList) { + this.keyList = keyList; + } + + /** + * @return the geoLocationList + */ + public List getGeoLocationList() { + return geoLocationList; + } + + /** + * @param geoLocationList + * the geoLocationList to set + */ + public void setGeoLocationList(List geoLocationList) { + this.geoLocationList = geoLocationList; + } + + /** + * @return the localDateList + */ + public List getLocalDateList() { + return localDateList; + } + + /** + * @param localDateList + * the localDateList to set + */ + public void setLocalDateList(List localDateList) { + this.localDateList = localDateList; + } + + /** + * @return the localTimeList + */ + public List getLocalTimeList() { + return localTimeList; + } + + /** + * @param localTimeList + * the localTimeList to set + */ + public void setLocalTimeList(List localTimeList) { + this.localTimeList = localTimeList; + } + + /** + * @return the localDateTimeList + */ + public List getLocalDateTimeList() { + return localDateTimeList; + } + + /** + * @param localDateTimeList + * the localDateTimeList to set + */ + public void setLocalDateTimeList(List localDateTimeList) { + this.localDateTimeList = localDateTimeList; + } + + /** + * @return the offsetDateTimeList + */ + public List getOffsetDateTimeList() { + return offsetDateTimeList; + } + + /** + * @param offsetDateTimeList + * the offsetDateTimeList to set + */ + public void setOffsetDateTimeList(List offsetDateTimeList) { + this.offsetDateTimeList = offsetDateTimeList; + } + + /** + * @return the zonedDateTimeList + */ + public List getZonedDateTimeList() { + return zonedDateTimeList; + } + + /** + * @param zonedDateTimeList + * the zonedDateTimeList to set + */ + public void setZonedDateTimeList(List zonedDateTimeList) { + this.zonedDateTimeList = zonedDateTimeList; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof ListFields)) { + return false; + } + if (this == obj) { + return true; + } + ListFields that = (ListFields) obj; + + return Objects.equals(this.booleanList, that.booleanList) + && Objects.equals(this.charList, that.charList) + && Objects.equals(this.shortList, that.shortList) + && Objects.equals(this.intList, that.intList) + && Objects.equals(this.longList, that.longList) + && Objects.equals(this.stringList, that.stringList) + && Objects.equals(this.dateList, that.dateList) + && Objects.equals(this.calendarList, that.calendarList) + && Objects.equals(this.floatList, that.floatList) + && Objects.equals(this.doubleList, that.doubleList) + // && Objects.deepEquals(this.blobList, that.blobList) && + // Objects.deepEquals(this.clobList, that.clobList) + && Objects.equals(this.colorList, that.colorList) + && Objects.equals(this.objectList, that.objectList) + && Objects.equals(this.wildcardList, that.wildcardList) + && Objects.equals(this.arrayList, that.arrayList) + && Objects.equals(this.linkedList, that.linkedList) + && Objects.equals(this.stack, that.stack) && Objects.equals(this.vector, that.vector) + && Objects.equals(this.keyList, that.keyList) + && Objects.equals(this.geoLocationList, that.geoLocationList) + && Objects.equals(this.localDateList, that.localDateList) + && Objects.equals(this.localTimeList, that.localTimeList) + && Objects.equals(this.localDateTimeList, that.localDateTimeList) + && Objects.equals(this.offsetDateTimeList, that.offsetDateTimeList) + && Objects.equals(this.zonedDateTimeList, that.zonedDateTimeList); + } + + public static ListFields getSampleEntity1() { + ListFields entity = new ListFields(); + entity.setBooleanList(Arrays.asList(true, false, false, true)); + entity.setCharList(Arrays.asList('Z', 'Y', 'X')); + entity.setShortList(Arrays.asList((short) 3, (short) 33, (short) 333)); + entity.setIntList(Arrays.asList(100, 200, 300)); + entity.setLongList(Arrays.asList(-3L, 0L, 3L, 987654321L)); + entity.setStringList(Arrays.asList("One", "Ten", "Hundred")); + long millis = System.currentTimeMillis(); + entity.setDateList( + Arrays.asList(new Date(millis), new Date(millis + 60000), new Date(millis - 60000))); + Calendar cal1 = Calendar.getInstance(); + Calendar cal2 = Calendar.getInstance(); + cal2.add(Calendar.DATE, 1); + Calendar cal3 = Calendar.getInstance(); + cal2.add(Calendar.DATE, -1); + entity.setCalendarList(Arrays.asList(cal1, cal2, cal3)); + entity.setColorList(Arrays.asList(Color.PINK, Color.BLACK, Color.YELLOW)); + entity.setFloatList(Arrays.asList(1.5f, 200f, Float.MAX_VALUE)); + entity.setDoubleList(Arrays.asList(Double.MIN_VALUE, 5000d, Double.MAX_VALUE)); + entity.setBlobList(Arrays.asList("One".getBytes(), "Two".getBytes())); + entity.setClobList(Arrays.asList("One".toCharArray(), "Two".toCharArray())); + entity + .setObjectList(Arrays.asList("One", 5000L, (Object) 99.99d, Boolean.FALSE, (String) null)); + entity.setWildcardList( + Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); + ArrayList arrayList = new ArrayList<>(); + arrayList + .addAll(Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); + entity.setArrayList(arrayList); + LinkedList linkedList = new LinkedList<>(); + linkedList + .addAll(Arrays.asList("Hey!", 999L, (Object) 9999.9999d, Boolean.TRUE, (Integer) null)); + entity.setLinkedList(linkedList); + Stack stack = new Stack<>(); + stack.addAll(Arrays.asList(3, 2, 1)); + entity.setStack(stack); + Vector vector = new Vector<>(); + vector.addAll(Arrays.asList(1.5f, 2.5f, 4.98f)); + entity.setVector(vector); + List geoLocationList = Arrays.asList(new GeoLocation(40.7142700, -74.0059700), + new GeoLocation(48.8534100, 2.3488000)); + entity.setGeoLocationList(geoLocationList); + LocalDate today = LocalDate.now(); + LocalDate tomorrow = today.plusDays(1); + entity.setLocalDateList(Arrays.asList(today, tomorrow)); + + LocalTime now = LocalTime.now(); + LocalTime anHourFromNow = now.plusHours(1); + entity.setLocalTimeList(Arrays.asList(null, now, anHourFromNow)); + + LocalDateTime ldt1 = LocalDateTime.now(); + LocalDateTime ldt2 = ldt1.plusDays(1); + entity.setLocalDateTimeList( + Arrays.asList(null, ldt1, ldt2, LocalDateTime.MIN, LocalDateTime.MIN)); + + OffsetDateTime odt1 = OffsetDateTime.now(); + OffsetDateTime odt2 = odt1.plusYears(1); + OffsetDateTime odtLow = OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.of("Z")); + OffsetDateTime odtHigh = OffsetDateTime.of(9999, 12, 31, 23, 59, 59, 999999999, + ZoneOffset.of("Z")); + entity.setOffsetDateTimeList(Arrays.asList(null, odt1, odt2, odtLow, odtHigh)); + + ZonedDateTime zdt1 = ZonedDateTime.now(); + ZonedDateTime zdt2 = zdt1.plusMonths(1); + entity.setZonedDateTimeList(Arrays.asList(null, zdt1, zdt2)); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LocalDateField.java b/src/test/java/com/jmethods/catatumbo/entities/LocalDateField.java index 04e8788..1cd3220 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LocalDateField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LocalDateField.java @@ -27,44 +27,44 @@ */ @Entity public class LocalDateField { - @Identifier - private long id; + @Identifier + private long id; - private LocalDate birthDate; + private LocalDate birthDate; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the birthDate - */ - public LocalDate getBirthDate() { - return birthDate; - } + /** + * @return the birthDate + */ + public LocalDate getBirthDate() { + return birthDate; + } - /** - * @param birthDate - * the birthDate to set - */ - public void setBirthDate(LocalDate birthDate) { - this.birthDate = birthDate; - } + /** + * @param birthDate + * the birthDate to set + */ + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } - @Override - public String toString() { - return "LocalDateField [id=" + id + ", birthDate=" + birthDate + "]"; - } + @Override + public String toString() { + return "LocalDateField [id=" + id + ", birthDate=" + birthDate + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LocalDateTimeField.java b/src/test/java/com/jmethods/catatumbo/entities/LocalDateTimeField.java index f81264f..702363d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LocalDateTimeField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LocalDateTimeField.java @@ -28,44 +28,44 @@ @Entity public class LocalDateTimeField { - @Identifier - private long id; + @Identifier + private long id; - private LocalDateTime timestamp; + private LocalDateTime timestamp; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the timestamp - */ - public LocalDateTime getTimestamp() { - return timestamp; - } + /** + * @return the timestamp + */ + public LocalDateTime getTimestamp() { + return timestamp; + } - /** - * @param timestamp - * the timestamp to set - */ - public void setTimestamp(LocalDateTime timestamp) { - this.timestamp = timestamp; - } + /** + * @param timestamp + * the timestamp to set + */ + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } - @Override - public String toString() { - return "LocalDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; - } + @Override + public String toString() { + return "LocalDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LocalTimeField.java b/src/test/java/com/jmethods/catatumbo/entities/LocalTimeField.java index 9843e9c..504bbcd 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LocalTimeField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LocalTimeField.java @@ -28,44 +28,44 @@ @Entity public class LocalTimeField { - @Identifier - private long id; + @Identifier + private long id; - private LocalTime startTime; + private LocalTime startTime; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the startTime - */ - public LocalTime getStartTime() { - return startTime; - } + /** + * @return the startTime + */ + public LocalTime getStartTime() { + return startTime; + } - /** - * @param startTime - * the startTime to set - */ - public void setStartTime(LocalTime startTime) { - this.startTime = startTime; - } + /** + * @param startTime + * the startTime to set + */ + public void setStartTime(LocalTime startTime) { + this.startTime = startTime; + } - @Override - public String toString() { - return "LocalTimeField [id=" + id + ", startTime=" + startTime + "]"; - } + @Override + public String toString() { + return "LocalTimeField [id=" + id + ", startTime=" + startTime + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongField.java b/src/test/java/com/jmethods/catatumbo/entities/LongField.java index 397bdf4..917715a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongField.java @@ -26,38 +26,38 @@ @Entity public class LongField { - @Identifier - private long id; - private long distanceFromEarth; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the distanceFromEarth - */ - public long getDistanceFromEarth() { - return distanceFromEarth; - } - - /** - * @param distanceFromEarth - * the distanceFromEarth to set - */ - public void setDistanceFromEarth(long distanceFromEarth) { - this.distanceFromEarth = distanceFromEarth; - } + @Identifier + private long id; + private long distanceFromEarth; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the distanceFromEarth + */ + public long getDistanceFromEarth() { + return distanceFromEarth; + } + + /** + * @param distanceFromEarth + * the distanceFromEarth to set + */ + public void setDistanceFromEarth(long distanceFromEarth) { + this.distanceFromEarth = distanceFromEarth; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongId.java b/src/test/java/com/jmethods/catatumbo/entities/LongId.java index 5d87f4b..8230e45 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongId.java @@ -27,48 +27,48 @@ @Entity public class LongId { - @Identifier - private long id; + @Identifier + private long id; - private String field1; + private String field1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the field1 - */ - public String getField1() { - return field1; - } + /** + * @return the field1 + */ + public String getField1() { + return field1; + } - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof LongId)) { - return false; - } - LongId that = (LongId) obj; - return this.id == that.id && Objects.equal(this.field1, that.field1); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof LongId)) { + return false; + } + LongId that = (LongId) obj; + return this.id == that.id && Objects.equal(this.field1, that.field1); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongId2.java b/src/test/java/com/jmethods/catatumbo/entities/LongId2.java index c3e62d5..dbeab25 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongId2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongId2.java @@ -26,39 +26,39 @@ @Entity public class LongId2 { - @Identifier(autoGenerated = false) - private long id; + @Identifier(autoGenerated = false) + private long id; - private String field1; + private String field1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the field1 - */ - public String getField1() { - return field1; - } + /** + * @return the field1 + */ + public String getField1() { + return field1; + } - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongListField.java b/src/test/java/com/jmethods/catatumbo/entities/LongListField.java index 6aa9185..263435b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongListField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongListField.java @@ -28,39 +28,39 @@ @Entity public class LongListField { - @Identifier - private long id; + @Identifier + private long id; - private List numbers; + private List numbers; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the list - */ - public List getNumbers() { - return numbers; - } + /** + * @return the list + */ + public List getNumbers() { + return numbers; + } - /** - * @param numbers - * the list to set - */ - public void setNumbers(List numbers) { - this.numbers = numbers; - } + /** + * @param numbers + * the list to set + */ + public void setNumbers(List numbers) { + this.numbers = numbers; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongObject.java b/src/test/java/com/jmethods/catatumbo/entities/LongObject.java index 13bc86c..10d277f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongObject.java @@ -26,38 +26,38 @@ @Entity public class LongObject { - @Identifier - private long id; - private Long distanceFromEarth; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the distanceFromEarth - */ - public Long getDistanceFromEarth() { - return distanceFromEarth; - } - - /** - * @param distanceFromEarth - * the distanceFromEarth to set - */ - public void setDistanceFromEarth(Long distanceFromEarth) { - this.distanceFromEarth = distanceFromEarth; - } + @Identifier + private long id; + private Long distanceFromEarth; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the distanceFromEarth + */ + public Long getDistanceFromEarth() { + return distanceFromEarth; + } + + /** + * @param distanceFromEarth + * the distanceFromEarth to set + */ + public void setDistanceFromEarth(Long distanceFromEarth) { + this.distanceFromEarth = distanceFromEarth; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/LongObjectId.java b/src/test/java/com/jmethods/catatumbo/entities/LongObjectId.java index b284418..bb9043a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/LongObjectId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/LongObjectId.java @@ -28,58 +28,58 @@ @Entity public class LongObjectId { - @Identifier - private Long id; + @Identifier + private Long id; - private String comment; + private String comment; - /** - * @return the id - */ - public Long getId() { - return id; - } + /** + * @return the id + */ + public Long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(Long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(Long id) { + this.id = id; + } - /** - * @return the comment - */ - public String getComment() { - return comment; - } + /** + * @return the comment + */ + public String getComment() { + return comment; + } - /** - * @param comment - * the comment to set - */ - public void setComment(String comment) { - this.comment = comment; - } + /** + * @param comment + * the comment to set + */ + public void setComment(String comment) { + this.comment = comment; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("LongObjectId [id=").append(id).append(", comment=").append(comment).append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("LongObjectId [id=").append(id).append(", comment=").append(comment).append("]"); + return builder.toString(); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - LongObjectId that = (LongObjectId) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.comment, that.comment); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + LongObjectId that = (LongObjectId) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.comment, that.comment); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/MapFields.java b/src/test/java/com/jmethods/catatumbo/entities/MapFields.java index 7f1dbff..a3eea6e 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/MapFields.java +++ b/src/test/java/com/jmethods/catatumbo/entities/MapFields.java @@ -37,600 +37,608 @@ */ @Entity public class MapFields { - @Identifier - private long id; - - private Map booleanMap; - private Map charMap; - private Map shortMap; - private Map intMap; - private Map longMap; - private Map stringMap; - private Map enumMap; - private Map floatMap; - private Map doubleMap; - private Map dateMap; - private Map calendarMap; - private Map blobMap; - private Map clobMap; - private Map geoLocationMap; - private Map keyMap; - private Map objectMap; - private Map genericMap; - private Map wildcardValueMap; - private Map wildcardMap; - private HashMap hashMap; - private SortedMap sortedMap; - private LinkedHashMap linkedHashMap; - private TreeMap treeMap; - private Map localDateMap; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the booleanMap - */ - public Map getBooleanMap() { - return booleanMap; - } - - /** - * @param booleanMap - * the booleanMap to set - */ - public void setBooleanMap(Map booleanMap) { - this.booleanMap = booleanMap; - } - - /** - * @return the charMap - */ - public Map getCharMap() { - return charMap; - } - - /** - * @param charMap - * the charMap to set - */ - public void setCharMap(Map charMap) { - this.charMap = charMap; - } - - /** - * @return the shortMap - */ - public Map getShortMap() { - return shortMap; - } - - /** - * @param shortMap - * the shortMap to set - */ - public void setShortMap(Map shortMap) { - this.shortMap = shortMap; - } - - /** - * @return the intMap - */ - public Map getIntMap() { - return intMap; - } - - /** - * @param intMap - * the intMap to set - */ - public void setIntMap(Map intMap) { - this.intMap = intMap; - } - - /** - * @return the longMap - */ - public Map getLongMap() { - return longMap; - } - - /** - * @param longMap - * the longMap to set - */ - public void setLongMap(Map longMap) { - this.longMap = longMap; - } - - /** - * @return the stringMap - */ - public Map getStringMap() { - return stringMap; - } - - /** - * @param stringMap - * the stringMap to set - */ - public void setStringMap(Map stringMap) { - this.stringMap = stringMap; - } - - /** - * @return the enumMap - */ - public Map getEnumMap() { - return enumMap; - } - - /** - * @param enumMap - * the enumMap to set - */ - public void setEnumMap(Map enumMap) { - this.enumMap = enumMap; - } - - /** - * @return the floatMap - */ - public Map getFloatMap() { - return floatMap; - } - - /** - * @param floatMap - * the floatMap to set - */ - public void setFloatMap(Map floatMap) { - this.floatMap = floatMap; - } - - /** - * @return the doubleMap - */ - public Map getDoubleMap() { - return doubleMap; - } - - /** - * @param doubleMap - * the doubleMap to set - */ - public void setDoubleMap(Map doubleMap) { - this.doubleMap = doubleMap; - } - - /** - * @return the dateMap - */ - public Map getDateMap() { - return dateMap; - } - - /** - * @param dateMap - * the dateMap to set - */ - public void setDateMap(Map dateMap) { - this.dateMap = dateMap; - } - - /** - * @return the calendarMap - */ - public Map getCalendarMap() { - return calendarMap; - } - - /** - * @param calendarMap - * the calendarMap to set - */ - public void setCalendarMap(Map calendarMap) { - this.calendarMap = calendarMap; - } - - /** - * @return the blobMap - */ - public Map getBlobMap() { - return blobMap; - } - - /** - * @param blobMap - * the blobMap to set - */ - public void setBlobMap(Map blobMap) { - this.blobMap = blobMap; - } - - /** - * @return the clobMap - */ - public Map getClobMap() { - return clobMap; - } - - /** - * @param clobMap - * the clobMap to set - */ - public void setClobMap(Map clobMap) { - this.clobMap = clobMap; - } - - /** - * @return the geoLocationMap - */ - public Map getGeoLocationMap() { - return geoLocationMap; - } - - /** - * @param geoLocationMap - * the geoLocationMap to set - */ - public void setGeoLocationMap(Map geoLocationMap) { - this.geoLocationMap = geoLocationMap; - } - - /** - * @return the keyMap - */ - public Map getKeyMap() { - return keyMap; - } - - /** - * @param keyMap - * the keyMap to set - */ - public void setKeyMap(Map keyMap) { - this.keyMap = keyMap; - } - - /** - * @return the objectMap - */ - public Map getObjectMap() { - return objectMap; - } - - /** - * @param objectMap - * the objectMap to set - */ - public void setObjectMap(Map objectMap) { - this.objectMap = objectMap; - } - - /** - * @return the genericMap - */ - public Map getGenericMap() { - return genericMap; - } - - /** - * @param genericMap - * the genericMap to set - */ - public void setGenericMap(Map genericMap) { - this.genericMap = genericMap; - } - - /** - * @return the wildcardValueMap - */ - public Map getWildcardValueMap() { - return wildcardValueMap; - } - - /** - * @param wildcardValueMap - * the wildcardValueMap to set - */ - public void setWildcardValueMap(Map wildcardValueMap) { - this.wildcardValueMap = wildcardValueMap; - } - - /** - * @return the wildcardMap - */ - public Map getWildcardMap() { - return wildcardMap; - } - - /** - * @param wildcardMap - * the wildcardMap to set - */ - public void setWildcardMap(Map wildcardMap) { - this.wildcardMap = wildcardMap; - } - - /** - * @return the hasMap - */ - public HashMap getHashMap() { - return hashMap; - } - - /** - * @param hashMap - * the hasMap to set - */ - public void setHashMap(HashMap hashMap) { - this.hashMap = hashMap; - } - - /** - * @return the sortedMap - */ - public SortedMap getSortedMap() { - return sortedMap; - } - - /** - * @param sortedMap - * the sortedMap to set - */ - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - - /** - * @return the linkedHashMap - */ - public LinkedHashMap getLinkedHashMap() { - return linkedHashMap; - } - - /** - * @param linkedHashMap - * the linkedHashMap to set - */ - public void setLinkedHashMap(LinkedHashMap linkedHashMap) { - this.linkedHashMap = linkedHashMap; - } - - /** - * @return the treeMap - */ - public TreeMap getTreeMap() { - return treeMap; - } - - /** - * @param treeMap - * the treeMap to set - */ - public void setTreeMap(TreeMap treeMap) { - this.treeMap = treeMap; - } - - /** - * @return the localDateMap - */ - public Map getLocalDateMap() { - return localDateMap; - } - - /** - * @param localDateMap - * the localDateMap to set - */ - public void setLocalDateMap(Map localDateMap) { - this.localDateMap = localDateMap; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof MapFields)) { - return false; - } - if (this == obj) { - return true; - } - MapFields that = (MapFields) obj; - return Objects.equals(this.booleanMap, that.booleanMap) && Objects.equals(this.charMap, that.charMap) - && Objects.equals(this.shortMap, that.shortMap) && Objects.equals(this.intMap, that.intMap) - && Objects.equals(this.longMap, that.longMap) && Objects.equals(this.stringMap, that.stringMap) - && Objects.equals(this.enumMap, that.enumMap) && Objects.equals(this.floatMap, that.floatMap) - && Objects.equals(this.doubleMap, that.doubleMap) && Objects.equals(this.dateMap, that.dateMap) - && Objects.equals(this.calendarMap, that.calendarMap) - && Objects.equals(this.geoLocationMap, that.geoLocationMap) && Objects.equals(this.keyMap, that.keyMap) - && Objects.equals(this.objectMap, that.objectMap) && Objects.equals(this.genericMap, that.genericMap) - && Objects.equals(this.wildcardValueMap, that.wildcardValueMap) - && Objects.equals(this.wildcardMap, that.wildcardMap) && Objects.equals(this.hashMap, that.hashMap) - && Objects.equals(this.sortedMap, that.sortedMap) - && Objects.equals(this.linkedHashMap, that.linkedHashMap) && Objects.equals(this.treeMap, that.treeMap) - && Objects.equals(this.localDateMap, that.localDateMap); - } - - public static MapFields getSampleEntity1() { - MapFields entity = new MapFields(); - - Map booleanMap = new HashMap<>(); - booleanMap.put("isTall", Boolean.FALSE); - booleanMap.put("isTricky", Boolean.TRUE); - booleanMap.put("isHelpful", null); - entity.setBooleanMap(booleanMap); - - Map charMap = new HashMap<>(); - charMap.put("a", 'Z'); - charMap.put("b", 'Y'); - charMap.put(" ", null); - entity.setCharMap(charMap); - - Map shortMap = new HashMap<>(); - shortMap.put("binary", (short) 2); - shortMap.put("octal", (short) 8); - shortMap.put("decimal", (short) 10); - shortMap.put("hexadecimal", (short) 16); - shortMap.put("unknown", null); - entity.setShortMap(shortMap); - - Map intMap = new HashMap<>(); - intMap.put("binary", 2); - intMap.put("octal", 8); - intMap.put("decimal", 10); - intMap.put("hexadecimal", 16); - shortMap.put("unknown", null); - entity.setIntMap(intMap); - - Map longMap = new HashMap<>(); - longMap.put("revenue", 10000000000000L); - longMap.put("proft", -10000000L); - longMap.put("forecast", null); - entity.setLongMap(longMap); - - Map stringMap = new HashMap<>(); - stringMap.put("hair-color", "black"); - stringMap.put("eye-color", "brown"); - stringMap.put("licene-plate", null); - entity.setStringMap(stringMap); - - Map enumMap = new HashMap<>(); - enumMap.put("#1", Color.BLACK); - enumMap.put("#2", Color.WHITE); - enumMap.put("#3", null); - entity.setEnumMap(enumMap); - - Map floatMap = new HashMap<>(); - floatMap.put("pi", 3.14f); - floatMap.put("log(10)", 1f); - floatMap.put("log(0)", null); - entity.setFloatMap(floatMap); - - Map doubleMap = new HashMap<>(); - doubleMap.put("pi", 3.14); - doubleMap.put("log(10)", 1d); - doubleMap.put("log(0)", null); - entity.setDoubleMap(doubleMap); - - Map dateMap = new HashMap<>(); - Calendar today = Calendar.getInstance(); - Calendar tomorrow = Calendar.getInstance(); - tomorrow.add(Calendar.DATE, 1); - dateMap.put("today", today.getTime()); - dateMap.put("tomorrow", tomorrow.getTime()); - dateMap.put("end", null); - entity.setDateMap(dateMap); - - Map calendarMap = new HashMap<>(); - calendarMap.put("today", today); - calendarMap.put("tomorrow", tomorrow); - calendarMap.put("end", null); - entity.setCalendarMap(calendarMap); - - Map blobMap = new HashMap<>(); - blobMap.put("pwd", "secret".getBytes()); - blobMap.put("pin", "0000".getBytes()); - blobMap.put("ssn", null); - entity.setBlobMap(blobMap); - - Map clobMap = new HashMap<>(); - clobMap.put("pwd", "secret".toCharArray()); - clobMap.put("pin", "1111".toCharArray()); - clobMap.put("ssn", null); - entity.setClobMap(clobMap); - - Map geoLocationMap = new HashMap<>(); - geoLocationMap.put("New York City", new GeoLocation(40.7142700, -74.0059700)); - geoLocationMap.put("Paris", new GeoLocation(48.8534100, 2.3488000)); - geoLocationMap.put("Nowhere", null); - entity.setGeoLocationMap(geoLocationMap); - - Map objectMap = new HashMap<>(); - objectMap.put("String", "Hello, World!"); - objectMap.put("Long", 999999999999L); - objectMap.put("Double", 10.589); - objectMap.put("Boolean", Boolean.FALSE); - objectMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); - objectMap.put("Null", null); - entity.setObjectMap(objectMap); - - Map genericMap = new HashMap<>(); - genericMap.put("String", "Hello, World!"); - genericMap.put("Long", 999999999999L); - genericMap.put("Double", 10.589); - genericMap.put("Boolean", Boolean.FALSE); - genericMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); - genericMap.put("Null", null); - entity.setGenericMap(genericMap); - - Map wildcardValueMap = new HashMap<>(); - wildcardValueMap.put("String", "Hello, World!"); - wildcardValueMap.put("Long", 999999999999L); - wildcardValueMap.put("Double", 10.589); - wildcardValueMap.put("Boolean", Boolean.FALSE); - wildcardValueMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); - wildcardValueMap.put("Null", null); - entity.setWildcardValueMap(wildcardValueMap); - - Map wildcardMap = new HashMap<>(); - wildcardMap.put("String", "Hello, World!"); - wildcardMap.put("Long", 999999999999L); - wildcardMap.put("Double", 10.589); - wildcardMap.put("Boolean", Boolean.FALSE); - wildcardMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); - wildcardMap.put("Null", null); - entity.setWildcardMap(wildcardMap); - - HashMap hashMap = new HashMap<>(); - hashMap.put("en", "Hello"); - hashMap.put("es", "Hola"); - hashMap.put("hi", "Namste"); - hashMap.put("el", null); - entity.setHashMap(hashMap); - - SortedMap sortedMap = new TreeMap<>(); - sortedMap.put("A", 1); - sortedMap.put("C", 3); - sortedMap.put("B", 2); - sortedMap.put(" ", 0); - entity.setSortedMap(sortedMap); - - LinkedHashMap linkedHashMap = new LinkedHashMap<>(); - linkedHashMap.put("Hundred", 100L); - linkedHashMap.put("Thousand", 1000L); - linkedHashMap.put("Million", 1000000L); - entity.setLinkedHashMap(linkedHashMap); - - TreeMap treeMap = new TreeMap<>(); - treeMap.put("Hundred", 100d); - treeMap.put("Thousand", 1000d); - treeMap.put("Million", 1000000d); - entity.setTreeMap(treeMap); - - Map localDateMap = new HashMap<>(); - LocalDate todayLocalDate = LocalDate.now(); - LocalDate yesterdayLocalDate = todayLocalDate.minusDays(1); - LocalDate nextYearLocalDate = todayLocalDate.plusYears(1); - localDateMap.put("today", todayLocalDate); - localDateMap.put("yesterday", yesterdayLocalDate); - localDateMap.put("nextYear", nextYearLocalDate); - localDateMap.put("earthFormedOn", null); - entity.setLocalDateMap(localDateMap); - - return entity; - } + @Identifier + private long id; + + private Map booleanMap; + private Map charMap; + private Map shortMap; + private Map intMap; + private Map longMap; + private Map stringMap; + private Map enumMap; + private Map floatMap; + private Map doubleMap; + private Map dateMap; + private Map calendarMap; + private Map blobMap; + private Map clobMap; + private Map geoLocationMap; + private Map keyMap; + private Map objectMap; + private Map genericMap; + private Map wildcardValueMap; + private Map wildcardMap; + private HashMap hashMap; + private SortedMap sortedMap; + private LinkedHashMap linkedHashMap; + private TreeMap treeMap; + private Map localDateMap; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the booleanMap + */ + public Map getBooleanMap() { + return booleanMap; + } + + /** + * @param booleanMap + * the booleanMap to set + */ + public void setBooleanMap(Map booleanMap) { + this.booleanMap = booleanMap; + } + + /** + * @return the charMap + */ + public Map getCharMap() { + return charMap; + } + + /** + * @param charMap + * the charMap to set + */ + public void setCharMap(Map charMap) { + this.charMap = charMap; + } + + /** + * @return the shortMap + */ + public Map getShortMap() { + return shortMap; + } + + /** + * @param shortMap + * the shortMap to set + */ + public void setShortMap(Map shortMap) { + this.shortMap = shortMap; + } + + /** + * @return the intMap + */ + public Map getIntMap() { + return intMap; + } + + /** + * @param intMap + * the intMap to set + */ + public void setIntMap(Map intMap) { + this.intMap = intMap; + } + + /** + * @return the longMap + */ + public Map getLongMap() { + return longMap; + } + + /** + * @param longMap + * the longMap to set + */ + public void setLongMap(Map longMap) { + this.longMap = longMap; + } + + /** + * @return the stringMap + */ + public Map getStringMap() { + return stringMap; + } + + /** + * @param stringMap + * the stringMap to set + */ + public void setStringMap(Map stringMap) { + this.stringMap = stringMap; + } + + /** + * @return the enumMap + */ + public Map getEnumMap() { + return enumMap; + } + + /** + * @param enumMap + * the enumMap to set + */ + public void setEnumMap(Map enumMap) { + this.enumMap = enumMap; + } + + /** + * @return the floatMap + */ + public Map getFloatMap() { + return floatMap; + } + + /** + * @param floatMap + * the floatMap to set + */ + public void setFloatMap(Map floatMap) { + this.floatMap = floatMap; + } + + /** + * @return the doubleMap + */ + public Map getDoubleMap() { + return doubleMap; + } + + /** + * @param doubleMap + * the doubleMap to set + */ + public void setDoubleMap(Map doubleMap) { + this.doubleMap = doubleMap; + } + + /** + * @return the dateMap + */ + public Map getDateMap() { + return dateMap; + } + + /** + * @param dateMap + * the dateMap to set + */ + public void setDateMap(Map dateMap) { + this.dateMap = dateMap; + } + + /** + * @return the calendarMap + */ + public Map getCalendarMap() { + return calendarMap; + } + + /** + * @param calendarMap + * the calendarMap to set + */ + public void setCalendarMap(Map calendarMap) { + this.calendarMap = calendarMap; + } + + /** + * @return the blobMap + */ + public Map getBlobMap() { + return blobMap; + } + + /** + * @param blobMap + * the blobMap to set + */ + public void setBlobMap(Map blobMap) { + this.blobMap = blobMap; + } + + /** + * @return the clobMap + */ + public Map getClobMap() { + return clobMap; + } + + /** + * @param clobMap + * the clobMap to set + */ + public void setClobMap(Map clobMap) { + this.clobMap = clobMap; + } + + /** + * @return the geoLocationMap + */ + public Map getGeoLocationMap() { + return geoLocationMap; + } + + /** + * @param geoLocationMap + * the geoLocationMap to set + */ + public void setGeoLocationMap(Map geoLocationMap) { + this.geoLocationMap = geoLocationMap; + } + + /** + * @return the keyMap + */ + public Map getKeyMap() { + return keyMap; + } + + /** + * @param keyMap + * the keyMap to set + */ + public void setKeyMap(Map keyMap) { + this.keyMap = keyMap; + } + + /** + * @return the objectMap + */ + public Map getObjectMap() { + return objectMap; + } + + /** + * @param objectMap + * the objectMap to set + */ + public void setObjectMap(Map objectMap) { + this.objectMap = objectMap; + } + + /** + * @return the genericMap + */ + public Map getGenericMap() { + return genericMap; + } + + /** + * @param genericMap + * the genericMap to set + */ + public void setGenericMap(Map genericMap) { + this.genericMap = genericMap; + } + + /** + * @return the wildcardValueMap + */ + public Map getWildcardValueMap() { + return wildcardValueMap; + } + + /** + * @param wildcardValueMap + * the wildcardValueMap to set + */ + public void setWildcardValueMap(Map wildcardValueMap) { + this.wildcardValueMap = wildcardValueMap; + } + + /** + * @return the wildcardMap + */ + public Map getWildcardMap() { + return wildcardMap; + } + + /** + * @param wildcardMap + * the wildcardMap to set + */ + public void setWildcardMap(Map wildcardMap) { + this.wildcardMap = wildcardMap; + } + + /** + * @return the hasMap + */ + public HashMap getHashMap() { + return hashMap; + } + + /** + * @param hashMap + * the hasMap to set + */ + public void setHashMap(HashMap hashMap) { + this.hashMap = hashMap; + } + + /** + * @return the sortedMap + */ + public SortedMap getSortedMap() { + return sortedMap; + } + + /** + * @param sortedMap + * the sortedMap to set + */ + public void setSortedMap(SortedMap sortedMap) { + this.sortedMap = sortedMap; + } + + /** + * @return the linkedHashMap + */ + public LinkedHashMap getLinkedHashMap() { + return linkedHashMap; + } + + /** + * @param linkedHashMap + * the linkedHashMap to set + */ + public void setLinkedHashMap(LinkedHashMap linkedHashMap) { + this.linkedHashMap = linkedHashMap; + } + + /** + * @return the treeMap + */ + public TreeMap getTreeMap() { + return treeMap; + } + + /** + * @param treeMap + * the treeMap to set + */ + public void setTreeMap(TreeMap treeMap) { + this.treeMap = treeMap; + } + + /** + * @return the localDateMap + */ + public Map getLocalDateMap() { + return localDateMap; + } + + /** + * @param localDateMap + * the localDateMap to set + */ + public void setLocalDateMap(Map localDateMap) { + this.localDateMap = localDateMap; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof MapFields)) { + return false; + } + if (this == obj) { + return true; + } + MapFields that = (MapFields) obj; + return Objects.equals(this.booleanMap, that.booleanMap) + && Objects.equals(this.charMap, that.charMap) + && Objects.equals(this.shortMap, that.shortMap) && Objects.equals(this.intMap, that.intMap) + && Objects.equals(this.longMap, that.longMap) + && Objects.equals(this.stringMap, that.stringMap) + && Objects.equals(this.enumMap, that.enumMap) + && Objects.equals(this.floatMap, that.floatMap) + && Objects.equals(this.doubleMap, that.doubleMap) + && Objects.equals(this.dateMap, that.dateMap) + && Objects.equals(this.calendarMap, that.calendarMap) + && Objects.equals(this.geoLocationMap, that.geoLocationMap) + && Objects.equals(this.keyMap, that.keyMap) + && Objects.equals(this.objectMap, that.objectMap) + && Objects.equals(this.genericMap, that.genericMap) + && Objects.equals(this.wildcardValueMap, that.wildcardValueMap) + && Objects.equals(this.wildcardMap, that.wildcardMap) + && Objects.equals(this.hashMap, that.hashMap) + && Objects.equals(this.sortedMap, that.sortedMap) + && Objects.equals(this.linkedHashMap, that.linkedHashMap) + && Objects.equals(this.treeMap, that.treeMap) + && Objects.equals(this.localDateMap, that.localDateMap); + } + + public static MapFields getSampleEntity1() { + MapFields entity = new MapFields(); + + Map booleanMap = new HashMap<>(); + booleanMap.put("isTall", Boolean.FALSE); + booleanMap.put("isTricky", Boolean.TRUE); + booleanMap.put("isHelpful", null); + entity.setBooleanMap(booleanMap); + + Map charMap = new HashMap<>(); + charMap.put("a", 'Z'); + charMap.put("b", 'Y'); + charMap.put(" ", null); + entity.setCharMap(charMap); + + Map shortMap = new HashMap<>(); + shortMap.put("binary", (short) 2); + shortMap.put("octal", (short) 8); + shortMap.put("decimal", (short) 10); + shortMap.put("hexadecimal", (short) 16); + shortMap.put("unknown", null); + entity.setShortMap(shortMap); + + Map intMap = new HashMap<>(); + intMap.put("binary", 2); + intMap.put("octal", 8); + intMap.put("decimal", 10); + intMap.put("hexadecimal", 16); + shortMap.put("unknown", null); + entity.setIntMap(intMap); + + Map longMap = new HashMap<>(); + longMap.put("revenue", 10000000000000L); + longMap.put("proft", -10000000L); + longMap.put("forecast", null); + entity.setLongMap(longMap); + + Map stringMap = new HashMap<>(); + stringMap.put("hair-color", "black"); + stringMap.put("eye-color", "brown"); + stringMap.put("licene-plate", null); + entity.setStringMap(stringMap); + + Map enumMap = new HashMap<>(); + enumMap.put("#1", Color.BLACK); + enumMap.put("#2", Color.WHITE); + enumMap.put("#3", null); + entity.setEnumMap(enumMap); + + Map floatMap = new HashMap<>(); + floatMap.put("pi", 3.14f); + floatMap.put("log(10)", 1f); + floatMap.put("log(0)", null); + entity.setFloatMap(floatMap); + + Map doubleMap = new HashMap<>(); + doubleMap.put("pi", 3.14); + doubleMap.put("log(10)", 1d); + doubleMap.put("log(0)", null); + entity.setDoubleMap(doubleMap); + + Map dateMap = new HashMap<>(); + Calendar today = Calendar.getInstance(); + Calendar tomorrow = Calendar.getInstance(); + tomorrow.add(Calendar.DATE, 1); + dateMap.put("today", today.getTime()); + dateMap.put("tomorrow", tomorrow.getTime()); + dateMap.put("end", null); + entity.setDateMap(dateMap); + + Map calendarMap = new HashMap<>(); + calendarMap.put("today", today); + calendarMap.put("tomorrow", tomorrow); + calendarMap.put("end", null); + entity.setCalendarMap(calendarMap); + + Map blobMap = new HashMap<>(); + blobMap.put("pwd", "secret".getBytes()); + blobMap.put("pin", "0000".getBytes()); + blobMap.put("ssn", null); + entity.setBlobMap(blobMap); + + Map clobMap = new HashMap<>(); + clobMap.put("pwd", "secret".toCharArray()); + clobMap.put("pin", "1111".toCharArray()); + clobMap.put("ssn", null); + entity.setClobMap(clobMap); + + Map geoLocationMap = new HashMap<>(); + geoLocationMap.put("New York City", new GeoLocation(40.7142700, -74.0059700)); + geoLocationMap.put("Paris", new GeoLocation(48.8534100, 2.3488000)); + geoLocationMap.put("Nowhere", null); + entity.setGeoLocationMap(geoLocationMap); + + Map objectMap = new HashMap<>(); + objectMap.put("String", "Hello, World!"); + objectMap.put("Long", 999999999999L); + objectMap.put("Double", 10.589); + objectMap.put("Boolean", Boolean.FALSE); + objectMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); + objectMap.put("Null", null); + entity.setObjectMap(objectMap); + + Map genericMap = new HashMap<>(); + genericMap.put("String", "Hello, World!"); + genericMap.put("Long", 999999999999L); + genericMap.put("Double", 10.589); + genericMap.put("Boolean", Boolean.FALSE); + genericMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); + genericMap.put("Null", null); + entity.setGenericMap(genericMap); + + Map wildcardValueMap = new HashMap<>(); + wildcardValueMap.put("String", "Hello, World!"); + wildcardValueMap.put("Long", 999999999999L); + wildcardValueMap.put("Double", 10.589); + wildcardValueMap.put("Boolean", Boolean.FALSE); + wildcardValueMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); + wildcardValueMap.put("Null", null); + entity.setWildcardValueMap(wildcardValueMap); + + Map wildcardMap = new HashMap<>(); + wildcardMap.put("String", "Hello, World!"); + wildcardMap.put("Long", 999999999999L); + wildcardMap.put("Double", 10.589); + wildcardMap.put("Boolean", Boolean.FALSE); + wildcardMap.put("GeoLocation", new GeoLocation(48.8534100, 2.3488000)); + wildcardMap.put("Null", null); + entity.setWildcardMap(wildcardMap); + + HashMap hashMap = new HashMap<>(); + hashMap.put("en", "Hello"); + hashMap.put("es", "Hola"); + hashMap.put("hi", "Namste"); + hashMap.put("el", null); + entity.setHashMap(hashMap); + + SortedMap sortedMap = new TreeMap<>(); + sortedMap.put("A", 1); + sortedMap.put("C", 3); + sortedMap.put("B", 2); + sortedMap.put(" ", 0); + entity.setSortedMap(sortedMap); + + LinkedHashMap linkedHashMap = new LinkedHashMap<>(); + linkedHashMap.put("Hundred", 100L); + linkedHashMap.put("Thousand", 1000L); + linkedHashMap.put("Million", 1000000L); + entity.setLinkedHashMap(linkedHashMap); + + TreeMap treeMap = new TreeMap<>(); + treeMap.put("Hundred", 100d); + treeMap.put("Thousand", 1000d); + treeMap.put("Million", 1000000d); + entity.setTreeMap(treeMap); + + Map localDateMap = new HashMap<>(); + LocalDate todayLocalDate = LocalDate.now(); + LocalDate yesterdayLocalDate = todayLocalDate.minusDays(1); + LocalDate nextYearLocalDate = todayLocalDate.plusYears(1); + localDateMap.put("today", todayLocalDate); + localDateMap.put("yesterday", yesterdayLocalDate); + localDateMap.put("nextYear", nextYearLocalDate); + localDateMap.put("earthFormedOn", null); + entity.setLocalDateMap(localDateMap); + + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NestedMapEntity.java b/src/test/java/com/jmethods/catatumbo/entities/NestedMapEntity.java index bbe92d7..75e2fba 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NestedMapEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NestedMapEntity.java @@ -30,86 +30,87 @@ @Entity public class NestedMapEntity { - @Identifier - private long id; - - private Map nestedMap; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the nestedMap - */ - public Map getNestedMap() { - return nestedMap; - } - - /** - * @param nestedMap - * the nestedMap to set - */ - public void setNestedMap(Map nestedMap) { - this.nestedMap = nestedMap; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - NestedMapEntity that = (NestedMapEntity) obj; - return this.id == that.id && Objects.equals(this.nestedMap, that.nestedMap); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("NestedMapEntity [id=").append(id).append(", nestedMap=").append(nestedMap).append("]"); - return builder.toString(); - } - - public static NestedMapEntity getSample1() { - NestedMapEntity entity = new NestedMapEntity(); - Map m1 = new HashMap<>(); - m1.put("string", "Hello World!"); - m1.put("long", 1000L); - m1.put("null", null); - - Map childMap = new HashMap<>(); - childMap.put("childprop1", "child value 1"); - childMap.put("childprop2", "child value 2"); - childMap.put("childlong", -23L); - childMap.put("childbool", true); - childMap.put("childnull", null); - - Map grandchildMap = new HashMap<>(); - grandchildMap.put("grandchildprop1", "grnadchild value 1"); - grandchildMap.put("grandchildprop2", "grandchild value 2"); - grandchildMap.put("grandchildlong", 900L); - grandchildMap.put("grandchildMapdouble", 9.99); - grandchildMap.put("grandchildnull", null); - - childMap.put("grandchildMap", grandchildMap); - m1.put("childMap", childMap); - - entity.setNestedMap(m1); - return entity; - } + @Identifier + private long id; + + private Map nestedMap; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the nestedMap + */ + public Map getNestedMap() { + return nestedMap; + } + + /** + * @param nestedMap + * the nestedMap to set + */ + public void setNestedMap(Map nestedMap) { + this.nestedMap = nestedMap; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + NestedMapEntity that = (NestedMapEntity) obj; + return this.id == that.id && Objects.equals(this.nestedMap, that.nestedMap); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("NestedMapEntity [id=").append(id).append(", nestedMap=").append(nestedMap) + .append("]"); + return builder.toString(); + } + + public static NestedMapEntity getSample1() { + NestedMapEntity entity = new NestedMapEntity(); + Map m1 = new HashMap<>(); + m1.put("string", "Hello World!"); + m1.put("long", 1000L); + m1.put("null", null); + + Map childMap = new HashMap<>(); + childMap.put("childprop1", "child value 1"); + childMap.put("childprop2", "child value 2"); + childMap.put("childlong", -23L); + childMap.put("childbool", true); + childMap.put("childnull", null); + + Map grandchildMap = new HashMap<>(); + grandchildMap.put("grandchildprop1", "grnadchild value 1"); + grandchildMap.put("grandchildprop2", "grandchild value 2"); + grandchildMap.put("grandchildlong", 900L); + grandchildMap.put("grandchildMapdouble", 9.99); + grandchildMap.put("grandchildnull", null); + + childMap.put("grandchildMap", grandchildMap); + m1.put("childMap", childMap); + + entity.setNestedMap(m1); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NoDefaultConstrctorEntity.java b/src/test/java/com/jmethods/catatumbo/entities/NoDefaultConstrctorEntity.java index a423a19..c86a2c6 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NoDefaultConstrctorEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NoDefaultConstrctorEntity.java @@ -27,47 +27,47 @@ @Entity public class NoDefaultConstrctorEntity { - @Identifier - private long id; + @Identifier + private long id; - @Property - private String name; + @Property + private String name; - /** - * - */ - private NoDefaultConstrctorEntity(String name) { - this.name = name; - } + /** + * + */ + private NoDefaultConstrctorEntity(String name) { + this.name = name; + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NoGetterMethodEntity.java b/src/test/java/com/jmethods/catatumbo/entities/NoGetterMethodEntity.java index 0881e01..d322903 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NoGetterMethodEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NoGetterMethodEntity.java @@ -27,33 +27,33 @@ @Entity public class NoGetterMethodEntity { - @Identifier - private long id; - - @Property - private String name; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + @Identifier + private long id; + + @Property + private String name; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity.java b/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity.java index c9c9d20..4ce9711 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity.java @@ -27,32 +27,32 @@ @Entity public class NoSetterMethodEntity { - @Identifier - private long id; - - @Property - private String name; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } + @Identifier + private long id; + + @Property + private String name; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity2.java b/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity2.java index de6def8..4492f48 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NoSetterMethodEntity2.java @@ -28,50 +28,50 @@ @Entity public class NoSetterMethodEntity2 { - @Identifier - private long id; + @Identifier + private long id; - @Property - private String name; + @Property + private String name; - @Embedded - protected Address address; + @Embedded + protected Address address; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the address - */ - public Address getAddress() { - return address; - } + /** + * @return the address + */ + public Address getAddress() { + return address; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/NoSuitableMapperEntity.java b/src/test/java/com/jmethods/catatumbo/entities/NoSuitableMapperEntity.java index 1b76cdd..733a6d3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/NoSuitableMapperEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/NoSuitableMapperEntity.java @@ -28,39 +28,39 @@ @Entity public class NoSuitableMapperEntity { - @Identifier - private long id; + @Identifier + private long id; - private URL url; + private URL url; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the url - */ - public URL getUrl() { - return url; - } + /** + * @return the url + */ + public URL getUrl() { + return url; + } - /** - * @param url - * the url to set - */ - public void setUrl(URL url) { - this.url = url; - } + /** + * @param url + * the url to set + */ + public void setUrl(URL url) { + this.url = url; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OffsetDateTimeField.java b/src/test/java/com/jmethods/catatumbo/entities/OffsetDateTimeField.java index 49918c9..2e86bf2 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OffsetDateTimeField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OffsetDateTimeField.java @@ -28,44 +28,44 @@ @Entity public class OffsetDateTimeField { - @Identifier - private long id; + @Identifier + private long id; - private OffsetDateTime timestamp; + private OffsetDateTime timestamp; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the timestamp - */ - public OffsetDateTime getTimestamp() { - return timestamp; - } + /** + * @return the timestamp + */ + public OffsetDateTime getTimestamp() { + return timestamp; + } - /** - * @param timestamp - * the timestamp to set - */ - public void setTimestamp(OffsetDateTime timestamp) { - this.timestamp = timestamp; - } + /** + * @param timestamp + * the timestamp to set + */ + public void setTimestamp(OffsetDateTime timestamp) { + this.timestamp = timestamp; + } - @Override - public String toString() { - return "OffsetDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; - } + @Override + public String toString() { + return "OffsetDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLock1.java b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLock1.java index 7f6377d..fc7b750 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLock1.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLock1.java @@ -27,62 +27,62 @@ @Entity public class OptimisticLock1 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Version - private long version = 1; + @Version + private long version = 1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the version - */ - public long getVersion() { - return version; - } + /** + * @return the version + */ + public long getVersion() { + return version; + } - /** - * @param version - * the version to set - */ - public void setVersion(long version) { - this.version = version; - } + /** + * @param version + * the version to set + */ + public void setVersion(long version) { + this.version = version; + } - @Override - public String toString() { - return "OptimisticLock1 [id=" + id + ", name=" + name + ", version=" + version + "]"; - } + @Override + public String toString() { + return "OptimisticLock1 [id=" + id + ", name=" + name + ", version=" + version + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad1.java b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad1.java index a9ea107..536b26f 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad1.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad1.java @@ -27,57 +27,57 @@ @Entity public class OptimisticLockBad1 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Version - private String version = "1"; + @Version + private String version = "1"; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the version - */ - public String getVersion() { - return version; - } + /** + * @return the version + */ + public String getVersion() { + return version; + } - /** - * @param version - * the version to set - */ - public void setVersion(String version) { - this.version = version; - } + /** + * @param version + * the version to set + */ + public void setVersion(String version) { + this.version = version; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad2.java b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad2.java index 853c064..7f2001a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptimisticLockBad2.java @@ -27,74 +27,74 @@ @Entity public class OptimisticLockBad2 { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Version - private long version = 1; + @Version + private long version = 1; - @Version - private long anotherVersion = 1; + @Version + private long anotherVersion = 1; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the version - */ - public long getVersion() { - return version; - } + /** + * @return the version + */ + public long getVersion() { + return version; + } - /** - * @param version - * the version to set - */ - public void setVersion(long version) { - this.version = version; - } + /** + * @param version + * the version to set + */ + public void setVersion(long version) { + this.version = version; + } - /** - * @return the anotherVersion - */ - public long getAnotherVersion() { - return anotherVersion; - } + /** + * @return the anotherVersion + */ + public long getAnotherVersion() { + return anotherVersion; + } - /** - * @param anotherVersion - * the anotherVersion to set - */ - public void setAnotherVersion(long anotherVersion) { - this.anotherVersion = anotherVersion; - } + /** + * @param anotherVersion + * the anotherVersion to set + */ + public void setAnotherVersion(long anotherVersion) { + this.anotherVersion = anotherVersion; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalCreatedTimestamp.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalCreatedTimestamp.java index 9112389..0177776 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalCreatedTimestamp.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalCreatedTimestamp.java @@ -28,41 +28,41 @@ @Entity public class OptionalCreatedTimestamp { - @Identifier - private long id; + @Identifier + private long id; - @CreatedTimestamp - @Property(optional = true) - private long creationTimestamp; + @CreatedTimestamp + @Property(optional = true) + private long creationTimestamp; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the version - */ - public long getCreationTimestamp() { - return creationTimestamp; - } + /** + * @return the version + */ + public long getCreationTimestamp() { + return creationTimestamp; + } - /** - * @param creationTimestamp - * the version to set - */ - public void setCreationTimestamp(long creationTimestamp) { - this.creationTimestamp = creationTimestamp; - } + /** + * @param creationTimestamp + * the version to set + */ + public void setCreationTimestamp(long creationTimestamp) { + this.creationTimestamp = creationTimestamp; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity.java index 10348c6..6304fa3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity.java @@ -40,355 +40,357 @@ @Entity public class OptionalFieldsEntity { - @Identifier - private long id; - - private String mandatoryString; - - @Key - private DatastoreKey key; - - @Property(optional = true) - private Short optionalShort; - - @Property(optional = true) - private Integer optionalInteger; - - @Property(optional = true) - private Long optionalLong; - - @Property(optional = true) - private String optionalString; - - @Property(optional = true) - private Date optionalDate; - - @Property(optional = true) - private byte[] optionalBlob; - - @Property(optional = true) - private List optionalList; - - @Property(optional = true) - private Set optionalSet; - - @Property(optional = true) - private Map optionalMap; - - @Embedded(optional = true) - @Imploded - private PhoneNumber optionalPhone; - - @Embedded(name = "faxno", optional = false, indexed = true) - @Imploded - private PhoneNumber fax; - - @Embedded(optional = true) - // Optional should not have any effect in - // exploded mode - private Address optionalAddress; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the mandatoryString - */ - public String getMandatoryString() { - return mandatoryString; - } - - /** - * @param mandatoryString - * the mandatoryString to set - */ - public void setMandatoryString(String mandatoryString) { - this.mandatoryString = mandatoryString; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the optionalShort - */ - public Short getOptionalShort() { - return optionalShort; - } - - /** - * @param optionalShort - * the optionalShort to set - */ - public void setOptionalShort(Short optionalShort) { - this.optionalShort = optionalShort; - } - - /** - * @return the optionalInteger - */ - public Integer getOptionalInteger() { - return optionalInteger; - } - - /** - * @param optionalInteger - * the optionalInteger to set - */ - public void setOptionalInteger(Integer optionalInteger) { - this.optionalInteger = optionalInteger; - } - - /** - * @return the optionalLong - */ - public Long getOptionalLong() { - return optionalLong; - } - - /** - * @param optionalLong - * the optionalLong to set - */ - public void setOptionalLong(Long optionalLong) { - this.optionalLong = optionalLong; - } - - /** - * @return the optionalString - */ - public String getOptionalString() { - return optionalString; - } - - /** - * @param optionalString - * the optionalString to set - */ - public void setOptionalString(String optionalString) { - this.optionalString = optionalString; - } - - /** - * @return the optionalDate - */ - public Date getOptionalDate() { - return optionalDate; - } - - /** - * @param optionalDate - * the optionalDate to set - */ - public void setOptionalDate(Date optionalDate) { - this.optionalDate = optionalDate; - } - - /** - * @return the optionalBlob - */ - public byte[] getOptionalBlob() { - return optionalBlob; - } - - /** - * @param optionalBlob - * the optionalBlob to set - */ - public void setOptionalBlob(byte[] optionalBlob) { - this.optionalBlob = optionalBlob; - } - - /** - * @return the optionalList - */ - public List getOptionalList() { - return optionalList; - } - - /** - * @param optionalList - * the optionalList to set - */ - public void setOptionalList(List optionalList) { - this.optionalList = optionalList; - } - - /** - * @return the optionalSet - */ - public Set getOptionalSet() { - return optionalSet; - } - - /** - * @param optionalSet - * the optionalSet to set - */ - public void setOptionalSet(Set optionalSet) { - this.optionalSet = optionalSet; - } - - /** - * @return the optionalMap - */ - public Map getOptionalMap() { - return optionalMap; - } - - /** - * @param optionalMap - * the optionalMap to set - */ - public void setOptionalMap(Map optionalMap) { - this.optionalMap = optionalMap; - } - - /** - * @return the optionalPhone - */ - public PhoneNumber getOptionalPhone() { - return optionalPhone; - } - - /** - * @param optionalPhone - * the optionalPhone to set - */ - public void setOptionalPhone(PhoneNumber optionalPhone) { - this.optionalPhone = optionalPhone; - } - - /** - * @return the fax - */ - public PhoneNumber getFax() { - return fax; - } - - /** - * @param fax - * the fax to set - */ - public void setFax(PhoneNumber fax) { - this.fax = fax; - } - - /** - * @return the optionalAddress - */ - public Address getOptionalAddress() { - return optionalAddress; - } - - /** - * @param optionalAddress - * the optionalAddress to set - */ - public void setOptionalAddress(Address optionalAddress) { - this.optionalAddress = optionalAddress; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - OptionalFieldsEntity that = (OptionalFieldsEntity) obj; - return this.id == that.id && equalsExceptId(obj); - } - - public boolean equalsExceptId(Object obj) { - if (this == obj) { - return true; - } - if (!this.getClass().equals(obj.getClass())) { - return false; - } - OptionalFieldsEntity that = (OptionalFieldsEntity) obj; - return Objects.equals(this.mandatoryString, that.mandatoryString) - && Objects.equals(this.optionalShort, that.optionalShort) - && Objects.equals(this.optionalInteger, that.optionalInteger) - && Objects.equals(this.optionalLong, that.optionalLong) - && Objects.equals(this.optionalString, that.optionalString) - && Objects.equals(this.optionalDate, that.optionalDate) - && Objects.equals(this.optionalList, that.optionalList) - && Objects.equals(this.optionalSet, that.optionalSet) - && Objects.equals(this.optionalMap, that.optionalMap) - && Objects.equals(this.optionalPhone, that.optionalPhone) && Objects.equals(this.fax, that.fax) - && Objects.equals(this.optionalAddress, that.optionalAddress); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("OptionalFieldsEntity [id=").append(id).append(", mandatoryString=").append(mandatoryString) - .append(", key=").append(key).append(", optionalShort=").append(optionalShort) - .append(", optionalInteger=").append(optionalInteger).append(", optionalLong=").append(optionalLong) - .append(", optionalString=").append(optionalString).append(", optionalDate=").append(optionalDate) - .append(", optionalBlob=").append(Arrays.toString(optionalBlob)).append(", optionalList=") - .append(optionalList).append(", optionalSet=").append(optionalSet).append(", optionalMap=") - .append(optionalMap).append(", optionalPhone=").append(optionalPhone).append(", fax=").append(fax) - .append(", optionalAddress=").append(optionalAddress).append("]"); - return builder.toString(); - } - - public static OptionalFieldsEntity getSample1() { - OptionalFieldsEntity entity = new OptionalFieldsEntity(); - return entity; - } - - public static OptionalFieldsEntity getSample2() { - OptionalFieldsEntity entity = new OptionalFieldsEntity(); - entity.setMandatoryString("Hello"); - entity.setOptionalAddress(Address.getSample3()); - entity.setOptionalBlob("abc".getBytes()); - entity.setOptionalDate(new Date()); - entity.setOptionalInteger(50000); - entity.setOptionalList(Arrays.asList(new String[] { "One", "Two" })); - entity.setOptionalLong(1000000000000000L); - Map map = new HashMap<>(); - map.put("key1", "Value 1"); - map.put("key2", "Value 2"); - entity.setOptionalMap(map); - entity.setOptionalPhone(PhoneNumber.getSample5()); - entity.setFax(PhoneNumber.getSample5()); - entity.setOptionalSet(new HashSet<>(Arrays.asList(new Integer[] { 5, 10, 15 }))); - entity.setOptionalShort((short) 5); - entity.setOptionalString("Yo!"); - return entity; - } + @Identifier + private long id; + + private String mandatoryString; + + @Key + private DatastoreKey key; + + @Property(optional = true) + private Short optionalShort; + + @Property(optional = true) + private Integer optionalInteger; + + @Property(optional = true) + private Long optionalLong; + + @Property(optional = true) + private String optionalString; + + @Property(optional = true) + private Date optionalDate; + + @Property(optional = true) + private byte[] optionalBlob; + + @Property(optional = true) + private List optionalList; + + @Property(optional = true) + private Set optionalSet; + + @Property(optional = true) + private Map optionalMap; + + @Embedded(optional = true) + @Imploded + private PhoneNumber optionalPhone; + + @Embedded(name = "faxno", optional = false, indexed = true) + @Imploded + private PhoneNumber fax; + + @Embedded(optional = true) + // Optional should not have any effect in + // exploded mode + private Address optionalAddress; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the mandatoryString + */ + public String getMandatoryString() { + return mandatoryString; + } + + /** + * @param mandatoryString + * the mandatoryString to set + */ + public void setMandatoryString(String mandatoryString) { + this.mandatoryString = mandatoryString; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the optionalShort + */ + public Short getOptionalShort() { + return optionalShort; + } + + /** + * @param optionalShort + * the optionalShort to set + */ + public void setOptionalShort(Short optionalShort) { + this.optionalShort = optionalShort; + } + + /** + * @return the optionalInteger + */ + public Integer getOptionalInteger() { + return optionalInteger; + } + + /** + * @param optionalInteger + * the optionalInteger to set + */ + public void setOptionalInteger(Integer optionalInteger) { + this.optionalInteger = optionalInteger; + } + + /** + * @return the optionalLong + */ + public Long getOptionalLong() { + return optionalLong; + } + + /** + * @param optionalLong + * the optionalLong to set + */ + public void setOptionalLong(Long optionalLong) { + this.optionalLong = optionalLong; + } + + /** + * @return the optionalString + */ + public String getOptionalString() { + return optionalString; + } + + /** + * @param optionalString + * the optionalString to set + */ + public void setOptionalString(String optionalString) { + this.optionalString = optionalString; + } + + /** + * @return the optionalDate + */ + public Date getOptionalDate() { + return optionalDate; + } + + /** + * @param optionalDate + * the optionalDate to set + */ + public void setOptionalDate(Date optionalDate) { + this.optionalDate = optionalDate; + } + + /** + * @return the optionalBlob + */ + public byte[] getOptionalBlob() { + return optionalBlob; + } + + /** + * @param optionalBlob + * the optionalBlob to set + */ + public void setOptionalBlob(byte[] optionalBlob) { + this.optionalBlob = optionalBlob; + } + + /** + * @return the optionalList + */ + public List getOptionalList() { + return optionalList; + } + + /** + * @param optionalList + * the optionalList to set + */ + public void setOptionalList(List optionalList) { + this.optionalList = optionalList; + } + + /** + * @return the optionalSet + */ + public Set getOptionalSet() { + return optionalSet; + } + + /** + * @param optionalSet + * the optionalSet to set + */ + public void setOptionalSet(Set optionalSet) { + this.optionalSet = optionalSet; + } + + /** + * @return the optionalMap + */ + public Map getOptionalMap() { + return optionalMap; + } + + /** + * @param optionalMap + * the optionalMap to set + */ + public void setOptionalMap(Map optionalMap) { + this.optionalMap = optionalMap; + } + + /** + * @return the optionalPhone + */ + public PhoneNumber getOptionalPhone() { + return optionalPhone; + } + + /** + * @param optionalPhone + * the optionalPhone to set + */ + public void setOptionalPhone(PhoneNumber optionalPhone) { + this.optionalPhone = optionalPhone; + } + + /** + * @return the fax + */ + public PhoneNumber getFax() { + return fax; + } + + /** + * @param fax + * the fax to set + */ + public void setFax(PhoneNumber fax) { + this.fax = fax; + } + + /** + * @return the optionalAddress + */ + public Address getOptionalAddress() { + return optionalAddress; + } + + /** + * @param optionalAddress + * the optionalAddress to set + */ + public void setOptionalAddress(Address optionalAddress) { + this.optionalAddress = optionalAddress; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + OptionalFieldsEntity that = (OptionalFieldsEntity) obj; + return this.id == that.id && equalsExceptId(obj); + } + + public boolean equalsExceptId(Object obj) { + if (this == obj) { + return true; + } + if (!this.getClass().equals(obj.getClass())) { + return false; + } + OptionalFieldsEntity that = (OptionalFieldsEntity) obj; + return Objects.equals(this.mandatoryString, that.mandatoryString) + && Objects.equals(this.optionalShort, that.optionalShort) + && Objects.equals(this.optionalInteger, that.optionalInteger) + && Objects.equals(this.optionalLong, that.optionalLong) + && Objects.equals(this.optionalString, that.optionalString) + && Objects.equals(this.optionalDate, that.optionalDate) + && Objects.equals(this.optionalList, that.optionalList) + && Objects.equals(this.optionalSet, that.optionalSet) + && Objects.equals(this.optionalMap, that.optionalMap) + && Objects.equals(this.optionalPhone, that.optionalPhone) + && Objects.equals(this.fax, that.fax) + && Objects.equals(this.optionalAddress, that.optionalAddress); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("OptionalFieldsEntity [id=").append(id).append(", mandatoryString=") + .append(mandatoryString).append(", key=").append(key).append(", optionalShort=") + .append(optionalShort).append(", optionalInteger=").append(optionalInteger) + .append(", optionalLong=").append(optionalLong).append(", optionalString=") + .append(optionalString).append(", optionalDate=").append(optionalDate) + .append(", optionalBlob=").append(Arrays.toString(optionalBlob)).append(", optionalList=") + .append(optionalList).append(", optionalSet=").append(optionalSet).append(", optionalMap=") + .append(optionalMap).append(", optionalPhone=").append(optionalPhone).append(", fax=") + .append(fax).append(", optionalAddress=").append(optionalAddress).append("]"); + return builder.toString(); + } + + public static OptionalFieldsEntity getSample1() { + OptionalFieldsEntity entity = new OptionalFieldsEntity(); + return entity; + } + + public static OptionalFieldsEntity getSample2() { + OptionalFieldsEntity entity = new OptionalFieldsEntity(); + entity.setMandatoryString("Hello"); + entity.setOptionalAddress(Address.getSample3()); + entity.setOptionalBlob("abc".getBytes()); + entity.setOptionalDate(new Date()); + entity.setOptionalInteger(50000); + entity.setOptionalList(Arrays.asList(new String[] { "One", "Two" })); + entity.setOptionalLong(1000000000000000L); + Map map = new HashMap<>(); + map.put("key1", "Value 1"); + map.put("key2", "Value 2"); + entity.setOptionalMap(map); + entity.setOptionalPhone(PhoneNumber.getSample5()); + entity.setFax(PhoneNumber.getSample5()); + entity.setOptionalSet(new HashSet<>(Arrays.asList(new Integer[] { 5, 10, 15 }))); + entity.setOptionalShort((short) 5); + entity.setOptionalString("Yo!"); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity2.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity2.java index 68ace9c..c81c82b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity2.java @@ -31,75 +31,75 @@ @Entity public class OptionalFieldsEntity2 { - @Identifier - private long id; - - @Key - private DatastoreKey key; - - private List phoneNumbers; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the phoneNumbers - */ - public List getPhoneNumbers() { - return phoneNumbers; - } - - /** - * @param phoneNumbers - * the phoneNumbers to set - */ - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("OptionalFieldsEntity2 [id=").append(id).append(", phoneNumbers=").append(phoneNumbers) - .append("]"); - return builder.toString(); - } - - public static OptionalFieldsEntity2 getSample1() { - List phones = new ArrayList<>(); - phones.add(PhoneNumber.getSample1()); - phones.add(PhoneNumber.getSample2()); - phones.add(PhoneNumber.getSample5()); - OptionalFieldsEntity2 entity = new OptionalFieldsEntity2(); - entity.setPhoneNumbers(phones); - return entity; - } + @Identifier + private long id; + + @Key + private DatastoreKey key; + + private List phoneNumbers; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the phoneNumbers + */ + public List getPhoneNumbers() { + return phoneNumbers; + } + + /** + * @param phoneNumbers + * the phoneNumbers to set + */ + public void setPhoneNumbers(List phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("OptionalFieldsEntity2 [id=").append(id).append(", phoneNumbers=") + .append(phoneNumbers).append("]"); + return builder.toString(); + } + + public static OptionalFieldsEntity2 getSample1() { + List phones = new ArrayList<>(); + phones.add(PhoneNumber.getSample1()); + phones.add(PhoneNumber.getSample2()); + phones.add(PhoneNumber.getSample5()); + OptionalFieldsEntity2 entity = new OptionalFieldsEntity2(); + entity.setPhoneNumbers(phones); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity3.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity3.java index 5d6833b..f11aa07 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity3.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalFieldsEntity3.java @@ -31,63 +31,63 @@ */ @Entity @PropertyOverrides({ - @PropertyOverride(name = "phone.countryCode", property = @Property(name = "ccode", optional = false)), - @PropertyOverride(name = "phone.areaCode", property = @Property(name = "acode", optional = true)) }) + @PropertyOverride(name = "phone.countryCode", property = @Property(name = "ccode", optional = false)), + @PropertyOverride(name = "phone.areaCode", property = @Property(name = "acode", optional = true)) }) public class OptionalFieldsEntity3 { - @Identifier - private long id; + @Identifier + private long id; - @Key - private DatastoreKey key; + @Key + private DatastoreKey key; - @Embedded - private PhoneNumber phone; + @Embedded + private PhoneNumber phone; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the phoneNumbers - */ - public PhoneNumber getPhone() { - return phone; - } + /** + * @return the phoneNumbers + */ + public PhoneNumber getPhone() { + return phone; + } - /** - * @param phone - * the phoneNumbers to set - */ - public void setPhone(PhoneNumber phone) { - this.phone = phone; - } + /** + * @param phone + * the phoneNumbers to set + */ + public void setPhone(PhoneNumber phone) { + this.phone = phone; + } - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalPrimitive.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalPrimitive.java index 31a6d36..99da6df 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalPrimitive.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalPrimitive.java @@ -27,70 +27,70 @@ @Entity public class OptionalPrimitive { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Property(optional = true) - private int optionalInt; + @Property(optional = true) + private int optionalInt; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the optionalInt - */ - public int getOptionalInt() { - return optionalInt; - } + /** + * @return the optionalInt + */ + public int getOptionalInt() { + return optionalInt; + } - /** - * @param optionalInt - * the optionalInt to set - */ - public void setOptionalInt(int optionalInt) { - this.optionalInt = optionalInt; - } + /** + * @param optionalInt + * the optionalInt to set + */ + public void setOptionalInt(int optionalInt) { + this.optionalInt = optionalInt; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("PrimitveOptionalFieldsEntity [id=").append(id).append(", name=").append(name) - .append(", optionalInt=").append(optionalInt).append("]"); - return builder.toString(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("PrimitveOptionalFieldsEntity [id=").append(id).append(", name=").append(name) + .append(", optionalInt=").append(optionalInt).append("]"); + return builder.toString(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalSubClass.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalSubClass.java index e837ee1..b36e508 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalSubClass.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalSubClass.java @@ -32,57 +32,57 @@ @PropertyOverrides({ @PropertyOverride(name = "createdBy", property = @Property(optional = true)) }) public class OptionalSubClass extends SuperClass1 { - @Identifier - private String id; + @Identifier + private String id; - private String name; + private String name; - @Key - private DatastoreKey key; + @Key + private DatastoreKey key; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalUpdatedTimestamp.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalUpdatedTimestamp.java index 4818933..941f3ca 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalUpdatedTimestamp.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalUpdatedTimestamp.java @@ -30,41 +30,41 @@ @Entity public class OptionalUpdatedTimestamp { - @Identifier - private long id; + @Identifier + private long id; - @Property(optional = true) - @UpdatedTimestamp - private Date modificationTimestamp; + @Property(optional = true) + @UpdatedTimestamp + private Date modificationTimestamp; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the version - */ - public Date getModificationTimestamp() { - return modificationTimestamp; - } + /** + * @return the version + */ + public Date getModificationTimestamp() { + return modificationTimestamp; + } - /** - * @param modificationTimestamp - * the version to set - */ - public void setModificationTimestamp(Date modificationTimestamp) { - this.modificationTimestamp = modificationTimestamp; - } + /** + * @param modificationTimestamp + * the version to set + */ + public void setModificationTimestamp(Date modificationTimestamp) { + this.modificationTimestamp = modificationTimestamp; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/OptionalVersion.java b/src/test/java/com/jmethods/catatumbo/entities/OptionalVersion.java index 5333b7c..e153b9b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/OptionalVersion.java +++ b/src/test/java/com/jmethods/catatumbo/entities/OptionalVersion.java @@ -28,41 +28,41 @@ @Entity public class OptionalVersion { - @Identifier - private long id; + @Identifier + private long id; - @Version - @Property(optional = true) - private long version; + @Version + @Property(optional = true) + private long version; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the version - */ - public long getVersion() { - return version; - } + /** + * @return the version + */ + public long getVersion() { + return version; + } - /** - * @param version - * the version to set - */ - public void setVersion(long version) { - this.version = version; - } + /** + * @param version + * the version to set + */ + public void setVersion(long version) { + this.version = version; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ParentEntity.java b/src/test/java/com/jmethods/catatumbo/entities/ParentEntity.java index 66321e8..c9ab03d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ParentEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ParentEntity.java @@ -31,91 +31,92 @@ @Entity public class ParentEntity implements Serializable { - /** - * Serial version UID - */ - private static final long serialVersionUID = 8794953055891942172L; - - public static ParentEntity parent1 = new ParentEntity(9000, "Parent 9000"); - - @Identifier - private long id; - private String field1; - @Key - private DatastoreKey key; - - public ParentEntity() { - - } - - public ParentEntity(long id, String field1) { - this.id = id; - this.field1 = field1; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the field1 - */ - public String getField1() { - return field1; - } - - /** - * @param field1 - * the field1 to set - */ - public void setField1(String field1) { - this.field1 = field1; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - ParentEntity that = (ParentEntity) obj; - return this.id == that.id && Objects.equals(this.field1, that.field1) && Objects.equals(this.key, that.key); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ParentEntity [id=").append(id).append(", field1=").append(field1).append(", key=").append(key) - .append("]"); - return builder.toString(); - } + /** + * Serial version UID + */ + private static final long serialVersionUID = 8794953055891942172L; + + public static ParentEntity parent1 = new ParentEntity(9000, "Parent 9000"); + + @Identifier + private long id; + private String field1; + @Key + private DatastoreKey key; + + public ParentEntity() { + + } + + public ParentEntity(long id, String field1) { + this.id = id; + this.field1 = field1; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the field1 + */ + public String getField1() { + return field1; + } + + /** + * @param field1 + * the field1 to set + */ + public void setField1(String field1) { + this.field1 = field1; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + ParentEntity that = (ParentEntity) obj; + return this.id == that.id && Objects.equals(this.field1, that.field1) + && Objects.equals(this.key, that.key); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ParentEntity [id=").append(id).append(", field1=").append(field1) + .append(", key=").append(key).append("]"); + return builder.toString(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Pet.java b/src/test/java/com/jmethods/catatumbo/entities/Pet.java index 0ff0345..58b09ff 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Pet.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Pet.java @@ -25,11 +25,11 @@ */ @MappedSuperClass public class Pet extends Animal { - @PreInsert - public void insertingPet() { - if (value.trim().length() > 0) { - value += "->"; - } - value += Pet.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingPet() { + if (value.trim().length() > 0) { + value += "->"; + } + value += Pet.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/PhoneList.java b/src/test/java/com/jmethods/catatumbo/entities/PhoneList.java index fcb643d..3934249 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/PhoneList.java +++ b/src/test/java/com/jmethods/catatumbo/entities/PhoneList.java @@ -32,81 +32,81 @@ @Entity public class PhoneList { - @Identifier - private long id; + @Identifier + private long id; - private List mobileNumbers; - private Set landLineNumbers; + private List mobileNumbers; + private Set landLineNumbers; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the phoneNumbers - */ - public List getMobileNumbers() { - return mobileNumbers; - } + /** + * @return the phoneNumbers + */ + public List getMobileNumbers() { + return mobileNumbers; + } - /** - * @param phoneNumbers - * the phoneNumbers to set - */ - public void setMobileNumbers(List phoneNumbers) { - this.mobileNumbers = phoneNumbers; - } + /** + * @param phoneNumbers + * the phoneNumbers to set + */ + public void setMobileNumbers(List phoneNumbers) { + this.mobileNumbers = phoneNumbers; + } - /** - * @return the landLineNumbers - */ - public Set getLandLineNumbers() { - return landLineNumbers; - } + /** + * @return the landLineNumbers + */ + public Set getLandLineNumbers() { + return landLineNumbers; + } - /** - * @param landLineNumbers - * the landLineNumbers to set - */ - public void setLandLineNumbers(Set landLineNumbers) { - this.landLineNumbers = landLineNumbers; - } + /** + * @param landLineNumbers + * the landLineNumbers to set + */ + public void setLandLineNumbers(Set landLineNumbers) { + this.landLineNumbers = landLineNumbers; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof PhoneList)) { - return false; - } - if (this == obj) { - return true; - } - PhoneList that = (PhoneList) obj; - return this.id == that.id && Objects.equals(this.mobileNumbers, that.mobileNumbers) - && Objects.equals(this.landLineNumbers, that.landLineNumbers); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof PhoneList)) { + return false; + } + if (this == obj) { + return true; + } + PhoneList that = (PhoneList) obj; + return this.id == that.id && Objects.equals(this.mobileNumbers, that.mobileNumbers) + && Objects.equals(this.landLineNumbers, that.landLineNumbers); + } - public static PhoneList getSample1() { - PhoneList entity = new PhoneList(); - List phoneNumbers = new ArrayList<>(); - phoneNumbers.add(PhoneNumber.getSample1()); - phoneNumbers.add(PhoneNumber.getSample2()); - entity.setMobileNumbers(phoneNumbers); - Set landLineNumbers = new HashSet<>(); - landLineNumbers.add(PhoneNumber.getSample3()); - landLineNumbers.add(PhoneNumber.getSample4()); - entity.setLandLineNumbers(landLineNumbers); - return entity; - } + public static PhoneList getSample1() { + PhoneList entity = new PhoneList(); + List phoneNumbers = new ArrayList<>(); + phoneNumbers.add(PhoneNumber.getSample1()); + phoneNumbers.add(PhoneNumber.getSample2()); + entity.setMobileNumbers(phoneNumbers); + Set landLineNumbers = new HashSet<>(); + landLineNumbers.add(PhoneNumber.getSample3()); + landLineNumbers.add(PhoneNumber.getSample4()); + entity.setLandLineNumbers(landLineNumbers); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/PhoneNumber.java b/src/test/java/com/jmethods/catatumbo/entities/PhoneNumber.java index 6ad7f22..1074058 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/PhoneNumber.java +++ b/src/test/java/com/jmethods/catatumbo/entities/PhoneNumber.java @@ -28,129 +28,130 @@ @Embeddable public class PhoneNumber { - @Property(optional = true) - private String countryCode; - - private String areaCode; - - private String subscriberNumber; - - /** - * @return the countryCode - */ - public String getCountryCode() { - return countryCode; - } - - /** - * @param countryCode - * the countryCode to set - */ - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - /** - * @return the areaCode - */ - public String getAreaCode() { - return areaCode; - } - - /** - * @param areaCode - * the areaCode to set - */ - public void setAreaCode(String areaCode) { - this.areaCode = areaCode; - } - - /** - * @return the number - */ - public String getSubscriberNumber() { - return subscriberNumber; - } - - /** - * @param number - * the number to set - */ - public void setSubscriberNumber(String number) { - this.subscriberNumber = number; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "+" + countryCode + " (" + areaCode + ")" + subscriberNumber; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof PhoneNumber)) { - return false; - } - if (this == obj) { - return true; - } - PhoneNumber that = (PhoneNumber) obj; - return Objects.equals(this.countryCode, that.countryCode) && Objects.equals(this.areaCode, that.areaCode) - && Objects.equals(this.subscriberNumber, that.subscriberNumber); - } - - @Override - public int hashCode() { - return Objects.hash(countryCode, areaCode, subscriberNumber); - } - - public static PhoneNumber getSample1() { - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("1"); - phone.setAreaCode("212"); - phone.setSubscriberNumber("8889999"); - return phone; - } - - public static PhoneNumber getSample2() { - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("1"); - phone.setAreaCode("402"); - phone.setSubscriberNumber("5556666"); - return phone; - } - - public static PhoneNumber getSample3() { - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("91"); - phone.setAreaCode("40"); - phone.setSubscriberNumber("2722 5858"); - return phone; - } - - public static PhoneNumber getSample4() { - PhoneNumber phone = new PhoneNumber(); - phone.setCountryCode("91"); - phone.setAreaCode("80"); - phone.setSubscriberNumber("6666 0000"); - return phone; - } - - public static PhoneNumber getSample5() { - PhoneNumber phone = new PhoneNumber(); - phone.setAreaCode("80"); - phone.setSubscriberNumber("6666 0000"); - return phone; - } + @Property(optional = true) + private String countryCode; + + private String areaCode; + + private String subscriberNumber; + + /** + * @return the countryCode + */ + public String getCountryCode() { + return countryCode; + } + + /** + * @param countryCode + * the countryCode to set + */ + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + /** + * @return the areaCode + */ + public String getAreaCode() { + return areaCode; + } + + /** + * @param areaCode + * the areaCode to set + */ + public void setAreaCode(String areaCode) { + this.areaCode = areaCode; + } + + /** + * @return the number + */ + public String getSubscriberNumber() { + return subscriberNumber; + } + + /** + * @param number + * the number to set + */ + public void setSubscriberNumber(String number) { + this.subscriberNumber = number; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "+" + countryCode + " (" + areaCode + ")" + subscriberNumber; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof PhoneNumber)) { + return false; + } + if (this == obj) { + return true; + } + PhoneNumber that = (PhoneNumber) obj; + return Objects.equals(this.countryCode, that.countryCode) + && Objects.equals(this.areaCode, that.areaCode) + && Objects.equals(this.subscriberNumber, that.subscriberNumber); + } + + @Override + public int hashCode() { + return Objects.hash(countryCode, areaCode, subscriberNumber); + } + + public static PhoneNumber getSample1() { + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("1"); + phone.setAreaCode("212"); + phone.setSubscriberNumber("8889999"); + return phone; + } + + public static PhoneNumber getSample2() { + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("1"); + phone.setAreaCode("402"); + phone.setSubscriberNumber("5556666"); + return phone; + } + + public static PhoneNumber getSample3() { + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("91"); + phone.setAreaCode("40"); + phone.setSubscriberNumber("2722 5858"); + return phone; + } + + public static PhoneNumber getSample4() { + PhoneNumber phone = new PhoneNumber(); + phone.setCountryCode("91"); + phone.setAreaCode("80"); + phone.setSubscriberNumber("6666 0000"); + return phone; + } + + public static PhoneNumber getSample5() { + PhoneNumber phone = new PhoneNumber(); + phone.setAreaCode("80"); + phone.setSubscriberNumber("6666 0000"); + return phone; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SetFields.java b/src/test/java/com/jmethods/catatumbo/entities/SetFields.java index f896e85..2652ca6 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SetFields.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SetFields.java @@ -39,427 +39,437 @@ @Entity public class SetFields { - @Identifier - private long id; - - private Set booleanSet; - private Set charSet; - private Set shortSet; - private Set intSet; - private Set longSet; - private Set floatSet; - private Set doubleSet; - private Set stringSet; - private Set enumSet; - private Set dateSet; - private Set calendarSet; - private Set blobSet; - private Set clobSet; - private Set geoLocationSet; - private Set keySet; - private Set objectSet; - private HashSet hashSet; - private SortedSet sortedSet; - private LinkedHashSet linkedHashSet; - private TreeSet treeSet; - private Set wildcardSet; - private Set localDateSet; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the booleanSet - */ - public Set getBooleanSet() { - return booleanSet; - } - - /** - * @param booleanSet - * the booleanSet to set - */ - public void setBooleanSet(Set booleanSet) { - this.booleanSet = booleanSet; - } - - /** - * @return the charSet - */ - public Set getCharSet() { - return charSet; - } - - /** - * @param charSet - * the charSet to set - */ - public void setCharSet(Set charSet) { - this.charSet = charSet; - } - - /** - * @return the shortSet - */ - public Set getShortSet() { - return shortSet; - } - - /** - * @param shortSet - * the shortSet to set - */ - public void setShortSet(Set shortSet) { - this.shortSet = shortSet; - } - - /** - * @return the intSet - */ - public Set getIntSet() { - return intSet; - } - - /** - * @param intSet - * the intSet to set - */ - public void setIntSet(Set intSet) { - this.intSet = intSet; - } - - /** - * @return the longSet - */ - public Set getLongSet() { - return longSet; - } - - /** - * @param longSet - * the longSet to set - */ - public void setLongSet(Set longSet) { - this.longSet = longSet; - } - - /** - * @return the floatSet - */ - public Set getFloatSet() { - return floatSet; - } - - /** - * @param floatSet - * the floatSet to set - */ - public void setFloatSet(Set floatSet) { - this.floatSet = floatSet; - } - - /** - * @return the doubleSet - */ - public Set getDoubleSet() { - return doubleSet; - } - - /** - * @param doubleSet - * the doubleSet to set - */ - public void setDoubleSet(Set doubleSet) { - this.doubleSet = doubleSet; - } - - /** - * @return the stringSet - */ - public Set getStringSet() { - return stringSet; - } - - /** - * @param stringSet - * the stringSet to set - */ - public void setStringSet(Set stringSet) { - this.stringSet = stringSet; - } - - /** - * @return the enumSet - */ - public Set getEnumSet() { - return enumSet; - } - - /** - * @param enumSet - * the enumSet to set - */ - public void setEnumSet(Set enumSet) { - this.enumSet = enumSet; - } - - /** - * @return the dateSet - */ - public Set getDateSet() { - return dateSet; - } - - /** - * @param dateSet - * the dateSet to set - */ - public void setDateSet(Set dateSet) { - this.dateSet = dateSet; - } - - /** - * @return the calendarSet - */ - public Set getCalendarSet() { - return calendarSet; - } - - /** - * @param calendarSet - * the calendarSet to set - */ - public void setCalendarSet(Set calendarSet) { - this.calendarSet = calendarSet; - } - - /** - * @return the blobSet - */ - public Set getBlobSet() { - return blobSet; - } - - /** - * @param blobSet - * the blobSet to set - */ - public void setBlobSet(Set blobSet) { - this.blobSet = blobSet; - } - - /** - * @return the clobSet - */ - public Set getClobSet() { - return clobSet; - } - - /** - * @param clobSet - * the clobSet to set - */ - public void setClobSet(Set clobSet) { - this.clobSet = clobSet; - } - - /** - * @return the geoLocationSet - */ - public Set getGeoLocationSet() { - return geoLocationSet; - } - - /** - * @param geoLocationSet - * the geoLocationSet to set - */ - public void setGeoLocationSet(Set geoLocationSet) { - this.geoLocationSet = geoLocationSet; - } - - /** - * @return the keySet - */ - public Set getKeySet() { - return keySet; - } - - /** - * @param keySet - * the keySet to set - */ - public void setKeySet(Set keySet) { - this.keySet = keySet; - } - - /** - * @return the objectSet - */ - public Set getObjectSet() { - return objectSet; - } - - /** - * @param objectSet - * the objectSet to set - */ - public void setObjectSet(Set objectSet) { - this.objectSet = objectSet; - } - - /** - * @return the hashSet - */ - public HashSet getHashSet() { - return hashSet; - } - - /** - * @param hashSet - * the hashSet to set - */ - public void setHashSet(HashSet hashSet) { - this.hashSet = hashSet; - } - - /** - * @return the sortedSet - */ - public SortedSet getSortedSet() { - return sortedSet; - } - - /** - * @param sortedSet - * the sortedSet to set - */ - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - /** - * @return the linkedHashSet - */ - public LinkedHashSet getLinkedHashSet() { - return linkedHashSet; - } - - /** - * @param linkedHashSet - * the linkedHashSet to set - */ - public void setLinkedHashSet(LinkedHashSet linkedHashSet) { - this.linkedHashSet = linkedHashSet; - } - - /** - * @return the treeSet - */ - public TreeSet getTreeSet() { - return treeSet; - } - - /** - * @param treeSet - * the treeSet to set - */ - public void setTreeSet(TreeSet treeSet) { - this.treeSet = treeSet; - } - - /** - * @return the wildcardSet - */ - public Set getWildcardSet() { - return wildcardSet; - } - - /** - * @param wildcardSet - * the wildcardSet to set - */ - public void setWildcardSet(Set wildcardSet) { - this.wildcardSet = wildcardSet; - } - - /** - * @return the localDateSet - */ - public Set getLocalDateSet() { - return localDateSet; - } - - /** - * @param localDateSet - * the localDateSet to set - */ - public void setLocalDateSet(Set localDateSet) { - this.localDateSet = localDateSet; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof SetFields)) { - return false; - } - if (this == obj) { - return true; - } - SetFields that = (SetFields) obj; - return this.id == that.id && Objects.equals(this.booleanSet, that.booleanSet) - && Objects.equals(this.charSet, that.charSet) && Objects.equals(this.shortSet, that.shortSet) - && Objects.equals(this.intSet, that.intSet) && Objects.equals(this.longSet, that.longSet) - && Objects.equals(this.floatSet, that.floatSet) && Objects.equals(this.doubleSet, that.doubleSet) - && Objects.equals(this.stringSet, that.stringSet) && Objects.equals(this.enumSet, enumSet) - && Objects.equals(this.dateSet, that.dateSet) && Objects.equals(this.calendarSet, that.calendarSet) - && Objects.equals(this.geoLocationSet, that.geoLocationSet) && Objects.equals(this.keySet, that.keySet) - && Objects.equals(this.objectSet, that.objectSet) && Objects.equals(this.hashSet, that.hashSet) - && Objects.equals(this.sortedSet, that.sortedSet) - && Objects.equals(this.linkedHashSet, that.linkedHashSet) && Objects.equals(this.treeSet, that.treeSet) - && Objects.equals(this.wildcardSet, that.wildcardSet) - && Objects.equals(this.localDateSet, that.localDateSet); - } - - public static SetFields getSampleEntity1() { - SetFields entity = new SetFields(); - entity.setBooleanSet(new HashSet<>(Arrays.asList(true, false, null))); - entity.setCharSet(new HashSet<>(Arrays.asList('S', 'M', 'L', null))); - entity.setShortSet(new HashSet<>(Arrays.asList((short) 5, (short) 9, null))); - entity.setIntSet(new HashSet<>(Arrays.asList(88, 888, 888, null))); - entity.setLongSet(new HashSet<>(Arrays.asList(6L, 66L, 666L, null))); - entity.setFloatSet(new HashSet<>(Arrays.asList(3.14f, 97f, 999.998f, null))); - entity.setDoubleSet(new HashSet<>(Arrays.asList(5.5, null, Double.MAX_VALUE, null))); - entity.setStringSet(new HashSet<>(Arrays.asList("Hello", "World", "Awesome", null))); - entity.setEnumSet(new HashSet<>(Arrays.asList(Color.BLACK, Color.BLUE, Color.PURPLE, null))); - entity.setDateSet(new HashSet<>(Arrays.asList(new Date(), new Date(System.currentTimeMillis() + 60000), null))); - entity.setCalendarSet(new HashSet<>(Arrays.asList(Calendar.getInstance(), null, Calendar.getInstance()))); - entity.setBlobSet(new HashSet<>(Arrays.asList("ok".getBytes(), "naah".getBytes(), null))); - entity.setClobSet(new HashSet<>(Arrays.asList("Oh".toCharArray(), "My".toCharArray(), null))); - entity.setGeoLocationSet(new HashSet<>( - Arrays.asList(new GeoLocation(40.7142700, -74.0059700), new GeoLocation(48.8534100, 2.3488000)))); - entity.setObjectSet(new HashSet<>(Arrays.asList("One", 5000L, 99.99d, Boolean.FALSE, (String) null))); - entity.setHashSet(new HashSet<>(Arrays.asList("Whatever", "Let's see", null))); - entity.setSortedSet(new TreeSet<>(Arrays.asList(5, 1, 3))); - entity.setLinkedHashSet(new LinkedHashSet<>(Arrays.asList(Double.MIN_VALUE, 0.0, Double.MAX_VALUE))); - entity.setTreeSet(new TreeSet<>(Arrays.asList(false, true, false, true))); - entity.setWildcardSet(new HashSet<>(Arrays.asList("One", 1L, true, 1.0d))); - LocalDate today = LocalDate.now(); - LocalDate tomorrow = today.plusDays(1); - entity.setLocalDateSet(new HashSet<>(Arrays.asList(today, tomorrow))); - return entity; - } + @Identifier + private long id; + + private Set booleanSet; + private Set charSet; + private Set shortSet; + private Set intSet; + private Set longSet; + private Set floatSet; + private Set doubleSet; + private Set stringSet; + private Set enumSet; + private Set dateSet; + private Set calendarSet; + private Set blobSet; + private Set clobSet; + private Set geoLocationSet; + private Set keySet; + private Set objectSet; + private HashSet hashSet; + private SortedSet sortedSet; + private LinkedHashSet linkedHashSet; + private TreeSet treeSet; + private Set wildcardSet; + private Set localDateSet; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the booleanSet + */ + public Set getBooleanSet() { + return booleanSet; + } + + /** + * @param booleanSet + * the booleanSet to set + */ + public void setBooleanSet(Set booleanSet) { + this.booleanSet = booleanSet; + } + + /** + * @return the charSet + */ + public Set getCharSet() { + return charSet; + } + + /** + * @param charSet + * the charSet to set + */ + public void setCharSet(Set charSet) { + this.charSet = charSet; + } + + /** + * @return the shortSet + */ + public Set getShortSet() { + return shortSet; + } + + /** + * @param shortSet + * the shortSet to set + */ + public void setShortSet(Set shortSet) { + this.shortSet = shortSet; + } + + /** + * @return the intSet + */ + public Set getIntSet() { + return intSet; + } + + /** + * @param intSet + * the intSet to set + */ + public void setIntSet(Set intSet) { + this.intSet = intSet; + } + + /** + * @return the longSet + */ + public Set getLongSet() { + return longSet; + } + + /** + * @param longSet + * the longSet to set + */ + public void setLongSet(Set longSet) { + this.longSet = longSet; + } + + /** + * @return the floatSet + */ + public Set getFloatSet() { + return floatSet; + } + + /** + * @param floatSet + * the floatSet to set + */ + public void setFloatSet(Set floatSet) { + this.floatSet = floatSet; + } + + /** + * @return the doubleSet + */ + public Set getDoubleSet() { + return doubleSet; + } + + /** + * @param doubleSet + * the doubleSet to set + */ + public void setDoubleSet(Set doubleSet) { + this.doubleSet = doubleSet; + } + + /** + * @return the stringSet + */ + public Set getStringSet() { + return stringSet; + } + + /** + * @param stringSet + * the stringSet to set + */ + public void setStringSet(Set stringSet) { + this.stringSet = stringSet; + } + + /** + * @return the enumSet + */ + public Set getEnumSet() { + return enumSet; + } + + /** + * @param enumSet + * the enumSet to set + */ + public void setEnumSet(Set enumSet) { + this.enumSet = enumSet; + } + + /** + * @return the dateSet + */ + public Set getDateSet() { + return dateSet; + } + + /** + * @param dateSet + * the dateSet to set + */ + public void setDateSet(Set dateSet) { + this.dateSet = dateSet; + } + + /** + * @return the calendarSet + */ + public Set getCalendarSet() { + return calendarSet; + } + + /** + * @param calendarSet + * the calendarSet to set + */ + public void setCalendarSet(Set calendarSet) { + this.calendarSet = calendarSet; + } + + /** + * @return the blobSet + */ + public Set getBlobSet() { + return blobSet; + } + + /** + * @param blobSet + * the blobSet to set + */ + public void setBlobSet(Set blobSet) { + this.blobSet = blobSet; + } + + /** + * @return the clobSet + */ + public Set getClobSet() { + return clobSet; + } + + /** + * @param clobSet + * the clobSet to set + */ + public void setClobSet(Set clobSet) { + this.clobSet = clobSet; + } + + /** + * @return the geoLocationSet + */ + public Set getGeoLocationSet() { + return geoLocationSet; + } + + /** + * @param geoLocationSet + * the geoLocationSet to set + */ + public void setGeoLocationSet(Set geoLocationSet) { + this.geoLocationSet = geoLocationSet; + } + + /** + * @return the keySet + */ + public Set getKeySet() { + return keySet; + } + + /** + * @param keySet + * the keySet to set + */ + public void setKeySet(Set keySet) { + this.keySet = keySet; + } + + /** + * @return the objectSet + */ + public Set getObjectSet() { + return objectSet; + } + + /** + * @param objectSet + * the objectSet to set + */ + public void setObjectSet(Set objectSet) { + this.objectSet = objectSet; + } + + /** + * @return the hashSet + */ + public HashSet getHashSet() { + return hashSet; + } + + /** + * @param hashSet + * the hashSet to set + */ + public void setHashSet(HashSet hashSet) { + this.hashSet = hashSet; + } + + /** + * @return the sortedSet + */ + public SortedSet getSortedSet() { + return sortedSet; + } + + /** + * @param sortedSet + * the sortedSet to set + */ + public void setSortedSet(SortedSet sortedSet) { + this.sortedSet = sortedSet; + } + + /** + * @return the linkedHashSet + */ + public LinkedHashSet getLinkedHashSet() { + return linkedHashSet; + } + + /** + * @param linkedHashSet + * the linkedHashSet to set + */ + public void setLinkedHashSet(LinkedHashSet linkedHashSet) { + this.linkedHashSet = linkedHashSet; + } + + /** + * @return the treeSet + */ + public TreeSet getTreeSet() { + return treeSet; + } + + /** + * @param treeSet + * the treeSet to set + */ + public void setTreeSet(TreeSet treeSet) { + this.treeSet = treeSet; + } + + /** + * @return the wildcardSet + */ + public Set getWildcardSet() { + return wildcardSet; + } + + /** + * @param wildcardSet + * the wildcardSet to set + */ + public void setWildcardSet(Set wildcardSet) { + this.wildcardSet = wildcardSet; + } + + /** + * @return the localDateSet + */ + public Set getLocalDateSet() { + return localDateSet; + } + + /** + * @param localDateSet + * the localDateSet to set + */ + public void setLocalDateSet(Set localDateSet) { + this.localDateSet = localDateSet; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof SetFields)) { + return false; + } + if (this == obj) { + return true; + } + SetFields that = (SetFields) obj; + return this.id == that.id && Objects.equals(this.booleanSet, that.booleanSet) + && Objects.equals(this.charSet, that.charSet) + && Objects.equals(this.shortSet, that.shortSet) && Objects.equals(this.intSet, that.intSet) + && Objects.equals(this.longSet, that.longSet) + && Objects.equals(this.floatSet, that.floatSet) + && Objects.equals(this.doubleSet, that.doubleSet) + && Objects.equals(this.stringSet, that.stringSet) && Objects.equals(this.enumSet, enumSet) + && Objects.equals(this.dateSet, that.dateSet) + && Objects.equals(this.calendarSet, that.calendarSet) + && Objects.equals(this.geoLocationSet, that.geoLocationSet) + && Objects.equals(this.keySet, that.keySet) + && Objects.equals(this.objectSet, that.objectSet) + && Objects.equals(this.hashSet, that.hashSet) + && Objects.equals(this.sortedSet, that.sortedSet) + && Objects.equals(this.linkedHashSet, that.linkedHashSet) + && Objects.equals(this.treeSet, that.treeSet) + && Objects.equals(this.wildcardSet, that.wildcardSet) + && Objects.equals(this.localDateSet, that.localDateSet); + } + + public static SetFields getSampleEntity1() { + SetFields entity = new SetFields(); + entity.setBooleanSet(new HashSet<>(Arrays.asList(true, false, null))); + entity.setCharSet(new HashSet<>(Arrays.asList('S', 'M', 'L', null))); + entity.setShortSet(new HashSet<>(Arrays.asList((short) 5, (short) 9, null))); + entity.setIntSet(new HashSet<>(Arrays.asList(88, 888, 888, null))); + entity.setLongSet(new HashSet<>(Arrays.asList(6L, 66L, 666L, null))); + entity.setFloatSet(new HashSet<>(Arrays.asList(3.14f, 97f, 999.998f, null))); + entity.setDoubleSet(new HashSet<>(Arrays.asList(5.5, null, Double.MAX_VALUE, null))); + entity.setStringSet(new HashSet<>(Arrays.asList("Hello", "World", "Awesome", null))); + entity.setEnumSet(new HashSet<>(Arrays.asList(Color.BLACK, Color.BLUE, Color.PURPLE, null))); + entity.setDateSet(new HashSet<>( + Arrays.asList(new Date(), new Date(System.currentTimeMillis() + 60000), null))); + entity.setCalendarSet( + new HashSet<>(Arrays.asList(Calendar.getInstance(), null, Calendar.getInstance()))); + entity.setBlobSet(new HashSet<>(Arrays.asList("ok".getBytes(), "naah".getBytes(), null))); + entity.setClobSet(new HashSet<>(Arrays.asList("Oh".toCharArray(), "My".toCharArray(), null))); + entity.setGeoLocationSet(new HashSet<>(Arrays.asList(new GeoLocation(40.7142700, -74.0059700), + new GeoLocation(48.8534100, 2.3488000)))); + entity.setObjectSet( + new HashSet<>(Arrays.asList("One", 5000L, 99.99d, Boolean.FALSE, (String) null))); + entity.setHashSet(new HashSet<>(Arrays.asList("Whatever", "Let's see", null))); + entity.setSortedSet(new TreeSet<>(Arrays.asList(5, 1, 3))); + entity.setLinkedHashSet( + new LinkedHashSet<>(Arrays.asList(Double.MIN_VALUE, 0.0, Double.MAX_VALUE))); + entity.setTreeSet(new TreeSet<>(Arrays.asList(false, true, false, true))); + entity.setWildcardSet(new HashSet<>(Arrays.asList("One", 1L, true, 1.0d))); + LocalDate today = LocalDate.now(); + LocalDate tomorrow = today.plusDays(1); + entity.setLocalDateSet(new HashSet<>(Arrays.asList(today, tomorrow))); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ShortField.java b/src/test/java/com/jmethods/catatumbo/entities/ShortField.java index 677ea01..b95fd48 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ShortField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ShortField.java @@ -26,39 +26,39 @@ @Entity public class ShortField { - @Identifier - private long id; + @Identifier + private long id; - private short age; + private short age; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the age - */ - public short getAge() { - return age; - } + /** + * @return the age + */ + public short getAge() { + return age; + } - /** - * @param age - * the age to set - */ - public void setAge(short age) { - this.age = age; - } + /** + * @param age + * the age to set + */ + public void setAge(short age) { + this.age = age; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ShortObject.java b/src/test/java/com/jmethods/catatumbo/entities/ShortObject.java index 33ef668..233c178 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ShortObject.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ShortObject.java @@ -26,39 +26,39 @@ @Entity public class ShortObject { - @Identifier - private long id; + @Identifier + private long id; - private Short age; + private Short age; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the age - */ - public Short getAge() { - return age; - } + /** + * @return the age + */ + public Short getAge() { + return age; + } - /** - * @param age - * the age to set - */ - public void setAge(Short age) { - this.age = age; - } + /** + * @param age + * the age to set + */ + public void setAge(Short age) { + this.age = age; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringField.java b/src/test/java/com/jmethods/catatumbo/entities/StringField.java index 9de0ba5..44b5524 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringField.java @@ -26,39 +26,39 @@ @Entity public class StringField { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringId.java b/src/test/java/com/jmethods/catatumbo/entities/StringId.java index a83ce6c..f11df7a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringId.java @@ -26,52 +26,52 @@ */ @Entity public class StringId { - @Identifier - private String id; - private String greetings; + @Identifier + private String id; + private String greetings; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the greetings - */ - public String getGreetings() { - return greetings; - } + /** + * @return the greetings + */ + public String getGreetings() { + return greetings; + } - /** - * @param greetings - * the greetings to set - */ - public void setGreetings(String greetings) { - this.greetings = greetings; - } + /** + * @param greetings + * the greetings to set + */ + public void setGreetings(String greetings) { + this.greetings = greetings; + } - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof StringId)) { - return false; - } - StringId that = (StringId) obj; - return Objects.equal(this.id, that.id) && Objects.equal(this.greetings, that.greetings); - } + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof StringId)) { + return false; + } + StringId that = (StringId) obj; + return Objects.equal(this.id, that.id) && Objects.equal(this.greetings, that.greetings); + } - @Override - public String toString() { - return id + ": " + greetings; - } + @Override + public String toString() { + return id + ": " + greetings; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringId2.java b/src/test/java/com/jmethods/catatumbo/entities/StringId2.java index c201e9f..4387a11 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringId2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringId2.java @@ -25,38 +25,38 @@ */ @Entity public class StringId2 { - @Identifier(autoGenerated = false) - private String id; - private String greetings; - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the greetings - */ - public String getGreetings() { - return greetings; - } - - /** - * @param greetings - * the greetings to set - */ - public void setGreetings(String greetings) { - this.greetings = greetings; - } + @Identifier(autoGenerated = false) + private String id; + private String greetings; + + /** + * @return the id + */ + public String getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the greetings + */ + public String getGreetings() { + return greetings; + } + + /** + * @param greetings + * the greetings to set + */ + public void setGreetings(String greetings) { + this.greetings = greetings; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringIndex.java b/src/test/java/com/jmethods/catatumbo/entities/StringIndex.java index 9679ec9..e101d25 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringIndex.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringIndex.java @@ -30,98 +30,98 @@ */ @Entity public class StringIndex { - @Identifier - private long id; - - @SecondaryIndex - private String firstName; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringIndexer.class) - private String lastName; - - @SecondaryIndex(name = "emailIndex") - private String email; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName - * the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof StringIndex)) { - return false; - } - if (this == obj) { - return true; - } - StringIndex that = (StringIndex) obj; - return this.id == that.id && Objects.equals(this.firstName, that.firstName) - && Objects.equals(this.lastName, that.lastName) && Objects.equals(this.email, that.email); - } - - public static StringIndex getSample1() { - StringIndex entity = new StringIndex(); - entity.setFirstName("John"); - entity.setLastName("Doe"); - entity.setEmail("John.Doe@Example.com"); - return entity; - } + @Identifier + private long id; + + @SecondaryIndex + private String firstName; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringIndexer.class) + private String lastName; + + @SecondaryIndex(name = "emailIndex") + private String email; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName + * the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the email + */ + public String getEmail() { + return email; + } + + /** + * @param email + * the email to set + */ + public void setEmail(String email) { + this.email = email; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof StringIndex)) { + return false; + } + if (this == obj) { + return true; + } + StringIndex that = (StringIndex) obj; + return this.id == that.id && Objects.equals(this.firstName, that.firstName) + && Objects.equals(this.lastName, that.lastName) && Objects.equals(this.email, that.email); + } + + public static StringIndex getSample1() { + StringIndex entity = new StringIndex(); + entity.setFirstName("John"); + entity.setLastName("Doe"); + entity.setEmail("John.Doe@Example.com"); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringIndex2.java b/src/test/java/com/jmethods/catatumbo/entities/StringIndex2.java index e54f431..e217640 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringIndex2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringIndex2.java @@ -29,130 +29,130 @@ */ @Entity(kind = "StringIndex") public class StringIndex2 { - @Identifier - private long id; - - @SecondaryIndex - private String firstName; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringIndexer.class) - private String lastName; - - @SecondaryIndex(name = "emailIndex") - private String email = "x"; - - @Property(name = "$firstName") - private String firstNameIndex = "y"; - - @Property(name = "$lastName") - private String lastNameIndex; - - private String emailIndex = "z"; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName - * the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the firstNameIndex - */ - public String getFirstNameIndex() { - return firstNameIndex; - } - - /** - * @param firstNameIndex - * the firstNameIndex to set - */ - public void setFirstNameIndex(String firstNameIndex) { - this.firstNameIndex = firstNameIndex; - } - - /** - * @return the lastNameIndex - */ - public String getLastNameIndex() { - return lastNameIndex; - } - - /** - * @param lastNameIndex - * the lastNameIndex to set - */ - public void setLastNameIndex(String lastNameIndex) { - this.lastNameIndex = lastNameIndex; - } - - /** - * @return the emailIndex - */ - public String getEmailIndex() { - return emailIndex; - } - - /** - * @param emailIndex - * the emailIndex to set - */ - public void setEmailIndex(String emailIndex) { - this.emailIndex = emailIndex; - } + @Identifier + private long id; + + @SecondaryIndex + private String firstName; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringIndexer.class) + private String lastName; + + @SecondaryIndex(name = "emailIndex") + private String email = "x"; + + @Property(name = "$firstName") + private String firstNameIndex = "y"; + + @Property(name = "$lastName") + private String lastNameIndex; + + private String emailIndex = "z"; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName + * the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the email + */ + public String getEmail() { + return email; + } + + /** + * @param email + * the email to set + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return the firstNameIndex + */ + public String getFirstNameIndex() { + return firstNameIndex; + } + + /** + * @param firstNameIndex + * the firstNameIndex to set + */ + public void setFirstNameIndex(String firstNameIndex) { + this.firstNameIndex = firstNameIndex; + } + + /** + * @return the lastNameIndex + */ + public String getLastNameIndex() { + return lastNameIndex; + } + + /** + * @param lastNameIndex + * the lastNameIndex to set + */ + public void setLastNameIndex(String lastNameIndex) { + this.lastNameIndex = lastNameIndex; + } + + /** + * @return the emailIndex + */ + public String getEmailIndex() { + return emailIndex; + } + + /** + * @param emailIndex + * the emailIndex to set + */ + public void setEmailIndex(String emailIndex) { + this.emailIndex = emailIndex; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringListField.java b/src/test/java/com/jmethods/catatumbo/entities/StringListField.java index ceca62c..de1f339 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringListField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringListField.java @@ -28,39 +28,39 @@ @Entity public class StringListField { - @Identifier - private long id; + @Identifier + private long id; - private List hobbies; + private List hobbies; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the list - */ - public List getHobbies() { - return hobbies; - } + /** + * @return the list + */ + public List getHobbies() { + return hobbies; + } - /** - * @param hobbies - * the list to set - */ - public void setHobbies(List hobbies) { - this.hobbies = hobbies; - } + /** + * @param hobbies + * the list to set + */ + public void setHobbies(List hobbies) { + this.hobbies = hobbies; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringListIndex.java b/src/test/java/com/jmethods/catatumbo/entities/StringListIndex.java index 4e73ea9..338ab33 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringListIndex.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringListIndex.java @@ -34,79 +34,81 @@ @Entity public class StringListIndex { - @Identifier - private long id; - - @SecondaryIndex - private List colors; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringListIndexer.class) - private LinkedList sizes; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the colors - */ - public List getColors() { - return colors; - } - - /** - * @param colors - * the colors to set - */ - public void setColors(List colors) { - this.colors = colors; - } - - /** - * @return the sizes - */ - public LinkedList getSizes() { - return sizes; - } - - /** - * @param sizes - * the sizes to set - */ - public void setSizes(LinkedList sizes) { - this.sizes = sizes; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof StringListIndex)) { - return false; - } - if (this == obj) { - return true; - } - StringListIndex that = (StringListIndex) obj; - return this.id == that.id && Objects.equals(this.colors, that.colors) && Objects.equals(this.sizes, that.sizes); - - } - - public static StringListIndex getSample1() { - StringListIndex entity = new StringListIndex(); - entity.setColors(Arrays.asList(new String[] { "Black", "White", "Red" })); - entity.setSizes(new LinkedList<>(Arrays.asList(new String[] { "Small", "Medium", "Large", null }))); - return entity; - } + @Identifier + private long id; + + @SecondaryIndex + private List colors; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringListIndexer.class) + private LinkedList sizes; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the colors + */ + public List getColors() { + return colors; + } + + /** + * @param colors + * the colors to set + */ + public void setColors(List colors) { + this.colors = colors; + } + + /** + * @return the sizes + */ + public LinkedList getSizes() { + return sizes; + } + + /** + * @param sizes + * the sizes to set + */ + public void setSizes(LinkedList sizes) { + this.sizes = sizes; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof StringListIndex)) { + return false; + } + if (this == obj) { + return true; + } + StringListIndex that = (StringListIndex) obj; + return this.id == that.id && Objects.equals(this.colors, that.colors) + && Objects.equals(this.sizes, that.sizes); + + } + + public static StringListIndex getSample1() { + StringListIndex entity = new StringListIndex(); + entity.setColors(Arrays.asList(new String[] { "Black", "White", "Red" })); + entity.setSizes( + new LinkedList<>(Arrays.asList(new String[] { "Small", "Medium", "Large", null }))); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringListIndex2.java b/src/test/java/com/jmethods/catatumbo/entities/StringListIndex2.java index 34372fd..4a76f5a 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringListIndex2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringListIndex2.java @@ -33,95 +33,95 @@ @Entity(kind = "StringListIndex") public class StringListIndex2 { - @Identifier - private long id; - - @SecondaryIndex - private List colors; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringListIndexer.class) - private LinkedList sizes; - - @Property(name = "$colors") - private List colorsIndex; - - @Property(name = "$sizes") - private LinkedList sizesIndex; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the colors - */ - public List getColors() { - return colors; - } - - /** - * @param colors - * the colors to set - */ - public void setColors(List colors) { - this.colors = colors; - } - - /** - * @return the sizes - */ - public LinkedList getSizes() { - return sizes; - } - - /** - * @param sizes - * the sizes to set - */ - public void setSizes(LinkedList sizes) { - this.sizes = sizes; - } - - /** - * @return the colorsIndex - */ - public List getColorsIndex() { - return colorsIndex; - } - - /** - * @param colorsIndex - * the colorsIndex to set - */ - public void setColorsIndex(List colorsIndex) { - this.colorsIndex = colorsIndex; - } - - /** - * @return the sizesIndex - */ - public LinkedList getSizesIndex() { - return sizesIndex; - } - - /** - * @param sizesIndex - * the sizesIndex to set - */ - public void setSizesIndex(LinkedList sizesIndex) { - this.sizesIndex = sizesIndex; - } + @Identifier + private long id; + + @SecondaryIndex + private List colors; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringListIndexer.class) + private LinkedList sizes; + + @Property(name = "$colors") + private List colorsIndex; + + @Property(name = "$sizes") + private LinkedList sizesIndex; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the colors + */ + public List getColors() { + return colors; + } + + /** + * @param colors + * the colors to set + */ + public void setColors(List colors) { + this.colors = colors; + } + + /** + * @return the sizes + */ + public LinkedList getSizes() { + return sizes; + } + + /** + * @param sizes + * the sizes to set + */ + public void setSizes(LinkedList sizes) { + this.sizes = sizes; + } + + /** + * @return the colorsIndex + */ + public List getColorsIndex() { + return colorsIndex; + } + + /** + * @param colorsIndex + * the colorsIndex to set + */ + public void setColorsIndex(List colorsIndex) { + this.colorsIndex = colorsIndex; + } + + /** + * @return the sizesIndex + */ + public LinkedList getSizesIndex() { + return sizesIndex; + } + + /** + * @param sizesIndex + * the sizesIndex to set + */ + public void setSizesIndex(LinkedList sizesIndex) { + this.sizesIndex = sizesIndex; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex.java b/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex.java index 83f260f..0907aab 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex.java @@ -33,79 +33,81 @@ @Entity public class StringSetIndex { - @Identifier - private long id; - - @SecondaryIndex - private LinkedHashSet colors; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringListIndexer.class) - private LinkedHashSet sizes; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the colors - */ - public LinkedHashSet getColors() { - return colors; - } - - /** - * @param colors - * the colors to set - */ - public void setColors(LinkedHashSet colors) { - this.colors = colors; - } - - /** - * @return the sizes - */ - public LinkedHashSet getSizes() { - return sizes; - } - - /** - * @param sizes - * the sizes to set - */ - public void setSizes(LinkedHashSet sizes) { - this.sizes = sizes; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof StringSetIndex)) { - return false; - } - if (this == obj) { - return true; - } - StringSetIndex that = (StringSetIndex) obj; - return this.id == that.id && Objects.equals(this.colors, that.colors) && Objects.equals(this.sizes, that.sizes); - - } - - public static StringSetIndex getSample1() { - StringSetIndex entity = new StringSetIndex(); - entity.setColors(new LinkedHashSet<>(Arrays.asList(new String[] { "Black", "White", "Red" }))); - entity.setSizes(new LinkedHashSet<>(Arrays.asList(new String[] { "Small", "Medium", "Large", null }))); - return entity; - } + @Identifier + private long id; + + @SecondaryIndex + private LinkedHashSet colors; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringListIndexer.class) + private LinkedHashSet sizes; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the colors + */ + public LinkedHashSet getColors() { + return colors; + } + + /** + * @param colors + * the colors to set + */ + public void setColors(LinkedHashSet colors) { + this.colors = colors; + } + + /** + * @return the sizes + */ + public LinkedHashSet getSizes() { + return sizes; + } + + /** + * @param sizes + * the sizes to set + */ + public void setSizes(LinkedHashSet sizes) { + this.sizes = sizes; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof StringSetIndex)) { + return false; + } + if (this == obj) { + return true; + } + StringSetIndex that = (StringSetIndex) obj; + return this.id == that.id && Objects.equals(this.colors, that.colors) + && Objects.equals(this.sizes, that.sizes); + + } + + public static StringSetIndex getSample1() { + StringSetIndex entity = new StringSetIndex(); + entity.setColors(new LinkedHashSet<>(Arrays.asList(new String[] { "Black", "White", "Red" }))); + entity.setSizes( + new LinkedHashSet<>(Arrays.asList(new String[] { "Small", "Medium", "Large", null }))); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex2.java b/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex2.java index c20dd55..e82a1e5 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/StringSetIndex2.java @@ -32,95 +32,95 @@ @Entity(kind = "StringSetIndex") public class StringSetIndex2 { - @Identifier - private long id; - - @SecondaryIndex - private LinkedHashSet colors; - - @SecondaryIndex - @PropertyIndexer(UpperCaseStringListIndexer.class) - private LinkedHashSet sizes; - - @Property(name = "$colors") - private LinkedHashSet colorsIndex; - - @Property(name = "$sizes") - private LinkedHashSet sizesIndex; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the colors - */ - public LinkedHashSet getColors() { - return colors; - } - - /** - * @param colors - * the colors to set - */ - public void setColors(LinkedHashSet colors) { - this.colors = colors; - } - - /** - * @return the sizes - */ - public LinkedHashSet getSizes() { - return sizes; - } - - /** - * @param sizes - * the sizes to set - */ - public void setSizes(LinkedHashSet sizes) { - this.sizes = sizes; - } - - /** - * @return the colorsIndex - */ - public LinkedHashSet getColorsIndex() { - return colorsIndex; - } - - /** - * @param colorsIndex - * the colorsIndex to set - */ - public void setColorsIndex(LinkedHashSet colorsIndex) { - this.colorsIndex = colorsIndex; - } - - /** - * @return the sizesIndex - */ - public LinkedHashSet getSizesIndex() { - return sizesIndex; - } - - /** - * @param sizesIndex - * the sizesIndex to set - */ - public void setSizesIndex(LinkedHashSet sizesIndex) { - this.sizesIndex = sizesIndex; - } + @Identifier + private long id; + + @SecondaryIndex + private LinkedHashSet colors; + + @SecondaryIndex + @PropertyIndexer(UpperCaseStringListIndexer.class) + private LinkedHashSet sizes; + + @Property(name = "$colors") + private LinkedHashSet colorsIndex; + + @Property(name = "$sizes") + private LinkedHashSet sizesIndex; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the colors + */ + public LinkedHashSet getColors() { + return colors; + } + + /** + * @param colors + * the colors to set + */ + public void setColors(LinkedHashSet colors) { + this.colors = colors; + } + + /** + * @return the sizes + */ + public LinkedHashSet getSizes() { + return sizes; + } + + /** + * @param sizes + * the sizes to set + */ + public void setSizes(LinkedHashSet sizes) { + this.sizes = sizes; + } + + /** + * @return the colorsIndex + */ + public LinkedHashSet getColorsIndex() { + return colorsIndex; + } + + /** + * @param colorsIndex + * the colorsIndex to set + */ + public void setColorsIndex(LinkedHashSet colorsIndex) { + this.colorsIndex = colorsIndex; + } + + /** + * @return the sizesIndex + */ + public LinkedHashSet getSizesIndex() { + return sizesIndex; + } + + /** + * @param sizesIndex + * the sizesIndex to set + */ + public void setSizesIndex(LinkedHashSet sizesIndex) { + this.sizesIndex = sizesIndex; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SubClass1.java b/src/test/java/com/jmethods/catatumbo/entities/SubClass1.java index a1be326..f9bf9a2 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SubClass1.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SubClass1.java @@ -28,54 +28,54 @@ @Entity public class SubClass1 extends SuperClass1 { - @Identifier - private long id; - private String name; + @Identifier + private long id; + private String name; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - SubClass1 that = (SubClass1) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) - && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) - && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) - && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) - && Objects.equals(this.getModifiedOn(), that.getModifiedOn()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + SubClass1 that = (SubClass1) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) + && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) + && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) + && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) + && Objects.equals(this.getModifiedOn(), that.getModifiedOn()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SubClass2.java b/src/test/java/com/jmethods/catatumbo/entities/SubClass2.java index 8920bb7..a8e501b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SubClass2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SubClass2.java @@ -27,37 +27,37 @@ @Entity public class SubClass2 extends SuperClass2 { - private String name; - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - SubClass2 that = (SubClass2) obj; - return Objects.equals(this.getId(), that.getId()) && Objects.equals(this.name, that.name) - && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) - && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) - && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) - && Objects.equals(this.getModifiedOn(), that.getModifiedOn()); - } + private String name; + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + SubClass2 that = (SubClass2) obj; + return Objects.equals(this.getId(), that.getId()) && Objects.equals(this.name, that.name) + && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) + && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) + && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) + && Objects.equals(this.getModifiedOn(), that.getModifiedOn()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SubClass3.java b/src/test/java/com/jmethods/catatumbo/entities/SubClass3.java index 4c26d81..9d49320 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SubClass3.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SubClass3.java @@ -29,61 +29,62 @@ * */ @Entity -@PropertyOverrides({ @PropertyOverride(name = "fieldx", property = @Property(name = "myfieldx", indexed = true)), - @PropertyOverride(name = "address.city", property = @Property(name = "mycity", indexed = true)), - @PropertyOverride(name = "address.zipCode.fourDigits", property = @Property(name = "zip_four_digits", indexed = true)), }) +@PropertyOverrides({ + @PropertyOverride(name = "fieldx", property = @Property(name = "myfieldx", indexed = true)), + @PropertyOverride(name = "address.city", property = @Property(name = "mycity", indexed = true)), + @PropertyOverride(name = "address.zipCode.fourDigits", property = @Property(name = "zip_four_digits", indexed = true)), }) public class SubClass3 extends SuperClass3 { - @Identifier - private long id; - private String name; + @Identifier + private long id; + private String name; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - SubClass3 that = (SubClass3) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) - && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) - && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) - && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) - && Objects.equals(this.getModifiedOn(), that.getModifiedOn()) - && Objects.equals(this.getFieldx(), that.getFieldx()) - && Objects.equals(this.getAddress(), that.getAddress()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + SubClass3 that = (SubClass3) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) + && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) + && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) + && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) + && Objects.equals(this.getModifiedOn(), that.getModifiedOn()) + && Objects.equals(this.getFieldx(), that.getFieldx()) + && Objects.equals(this.getAddress(), that.getAddress()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SubClass4.java b/src/test/java/com/jmethods/catatumbo/entities/SubClass4.java index 2f61036..13fb406 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SubClass4.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SubClass4.java @@ -28,56 +28,56 @@ @Entity public class SubClass4 extends SuperClass4 { - @Identifier - private long id; - private String name; + @Identifier + private long id; + private String name; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - SubClass4 that = (SubClass4) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) - && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) - && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) - && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) - && Objects.equals(this.getModifiedOn(), that.getModifiedOn()) - && Objects.equals(this.getFieldx(), that.getFieldx()) - && Objects.equals(this.getAddress(), that.getAddress()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + SubClass4 that = (SubClass4) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) + && Objects.equals(this.getCreatedBy(), that.getCreatedBy()) + && Objects.equals(this.getCreatedOn(), that.getCreatedOn()) + && Objects.equals(this.getModifiedBy(), that.getModifiedBy()) + && Objects.equals(this.getModifiedOn(), that.getModifiedOn()) + && Objects.equals(this.getFieldx(), that.getFieldx()) + && Objects.equals(this.getAddress(), that.getAddress()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SuperClass1.java b/src/test/java/com/jmethods/catatumbo/entities/SuperClass1.java index 3c503ee..e9283fa 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SuperClass1.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SuperClass1.java @@ -28,87 +28,87 @@ @MappedSuperClass public class SuperClass1 { - private String createdBy; - private Date createdOn; - private String modifiedBy; - private Date modifiedOn; - - @Ignore - private String ignoredField; - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy - * the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the createdOn - */ - public Date getCreatedOn() { - return createdOn; - } - - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy - * the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the modifiedOn - */ - public Date getModifiedOn() { - return modifiedOn; - } - - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(Date modifiedOn) { - this.modifiedOn = modifiedOn; - } - - /** - * @return the ignoredField - */ - public String getIgnoredField() { - return ignoredField; - } - - /** - * @param ignoredField - * the ignoredField to set - */ - public void setIgnoredField(String ignoredField) { - this.ignoredField = ignoredField; - } + private String createdBy; + private Date createdOn; + private String modifiedBy; + private Date modifiedOn; + + @Ignore + private String ignoredField; + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the createdOn + */ + public Date getCreatedOn() { + return createdOn; + } + + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy + * the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the modifiedOn + */ + public Date getModifiedOn() { + return modifiedOn; + } + + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } + + /** + * @return the ignoredField + */ + public String getIgnoredField() { + return ignoredField; + } + + /** + * @param ignoredField + * the ignoredField to set + */ + public void setIgnoredField(String ignoredField) { + this.ignoredField = ignoredField; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SuperClass2.java b/src/test/java/com/jmethods/catatumbo/entities/SuperClass2.java index e9a3c75..3a494a3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SuperClass2.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SuperClass2.java @@ -28,86 +28,86 @@ @MappedSuperClass public class SuperClass2 { - @Identifier - private long id; - private String createdBy; - private Date createdOn; - private String modifiedBy; - private Date modifiedOn; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy - * the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the createdOn - */ - public Date getCreatedOn() { - return createdOn; - } - - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy - * the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the modifiedOn - */ - public Date getModifiedOn() { - return modifiedOn; - } - - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(Date modifiedOn) { - this.modifiedOn = modifiedOn; - } + @Identifier + private long id; + private String createdBy; + private Date createdOn; + private String modifiedBy; + private Date modifiedOn; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the createdOn + */ + public Date getCreatedOn() { + return createdOn; + } + + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy + * the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the modifiedOn + */ + public Date getModifiedOn() { + return modifiedOn; + } + + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SuperClass3.java b/src/test/java/com/jmethods/catatumbo/entities/SuperClass3.java index ce6beb5..5e33baf 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SuperClass3.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SuperClass3.java @@ -27,69 +27,69 @@ @MappedSuperClass public class SuperClass3 extends SuperSuperClass { - private String createdBy; - private Date createdOn; - private String modifiedBy; - private Date modifiedOn; + private String createdBy; + private Date createdOn; + private String modifiedBy; + private Date modifiedOn; - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } - /** - * @param createdBy - * the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - /** - * @return the createdOn - */ - public Date getCreatedOn() { - return createdOn; - } + /** + * @return the createdOn + */ + public Date getCreatedOn() { + return createdOn; + } - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } - /** - * @param modifiedBy - * the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + /** + * @param modifiedBy + * the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - /** - * @return the modifiedOn - */ - public Date getModifiedOn() { - return modifiedOn; - } + /** + * @return the modifiedOn + */ + public Date getModifiedOn() { + return modifiedOn; + } - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(Date modifiedOn) { - this.modifiedOn = modifiedOn; - } + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SuperClass4.java b/src/test/java/com/jmethods/catatumbo/entities/SuperClass4.java index 22342bd..772bc6e 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SuperClass4.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SuperClass4.java @@ -24,69 +24,69 @@ */ public class SuperClass4 extends SuperSuperClass { - private String createdBy; - private Date createdOn; - private String modifiedBy; - private Date modifiedOn; + private String createdBy; + private Date createdOn; + private String modifiedBy; + private Date modifiedOn; - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } - /** - * @param createdBy - * the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - /** - * @return the createdOn - */ - public Date getCreatedOn() { - return createdOn; - } + /** + * @return the createdOn + */ + public Date getCreatedOn() { + return createdOn; + } - /** - * @param createdOn - * the createdOn to set - */ - public void setCreatedOn(Date createdOn) { - this.createdOn = createdOn; - } + /** + * @param createdOn + * the createdOn to set + */ + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } - /** - * @param modifiedBy - * the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + /** + * @param modifiedBy + * the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - /** - * @return the modifiedOn - */ - public Date getModifiedOn() { - return modifiedOn; - } + /** + * @return the modifiedOn + */ + public Date getModifiedOn() { + return modifiedOn; + } - /** - * @param modifiedOn - * the modifiedOn to set - */ - public void setModifiedOn(Date modifiedOn) { - this.modifiedOn = modifiedOn; - } + /** + * @param modifiedOn + * the modifiedOn to set + */ + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/SuperSuperClass.java b/src/test/java/com/jmethods/catatumbo/entities/SuperSuperClass.java index ca67ee3..b8ea881 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/SuperSuperClass.java +++ b/src/test/java/com/jmethods/catatumbo/entities/SuperSuperClass.java @@ -29,58 +29,58 @@ @MappedSuperClass public class SuperSuperClass { - @Property(name = "super.super", indexed = false) - private String fieldx; + @Property(name = "super.super", indexed = false) + private String fieldx; - @Key - private DatastoreKey myKey; + @Key + private DatastoreKey myKey; - @Embedded - private Address address; + @Embedded + private Address address; - /** - * @return the fieldx - */ - public String getFieldx() { - return fieldx; - } + /** + * @return the fieldx + */ + public String getFieldx() { + return fieldx; + } - /** - * @param fieldx - * the fieldx to set - */ - public void setFieldx(String fieldx) { - this.fieldx = fieldx; - } + /** + * @param fieldx + * the fieldx to set + */ + public void setFieldx(String fieldx) { + this.fieldx = fieldx; + } - /** - * @return the myKey - */ - public DatastoreKey getMyKey() { - return myKey; - } + /** + * @return the myKey + */ + public DatastoreKey getMyKey() { + return myKey; + } - /** - * @param myKey - * the myKey to set - */ - public void setMyKey(DatastoreKey myKey) { - this.myKey = myKey; - } + /** + * @param myKey + * the myKey to set + */ + public void setMyKey(DatastoreKey myKey) { + this.myKey = myKey; + } - /** - * @return the address - */ - public Address getAddress() { - return address; - } + /** + * @return the address + */ + public Address getAddress() { + return address; + } - /** - * @param address - * the address to set - */ - public void setAddress(Address address) { - this.address = address; - } + /** + * @param address + * the address to set + */ + public void setAddress(Address address) { + this.address = address; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Tag.java b/src/test/java/com/jmethods/catatumbo/entities/Tag.java index f5b2ff5..c35cf1d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Tag.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Tag.java @@ -28,57 +28,57 @@ @Entity public class Tag { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - @Key - private DatastoreKey key; + @Key + private DatastoreKey key; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Task.java b/src/test/java/com/jmethods/catatumbo/entities/Task.java index 2d1887e..d9838c3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Task.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Task.java @@ -28,101 +28,101 @@ @Entity public class Task { - @Identifier - private long id; - - private String name; - - private int priority; - - private Date completionDate; - - private boolean complete; - - public Task() { - - } - - public Task(long id, String name, int priority, boolean complete) { - this.id = id; - this.name = name; - this.priority = priority; - this.complete = complete; - } - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the priority - */ - public int getPriority() { - return priority; - } - - /** - * @param priority - * the priority to set - */ - public void setPriority(int priority) { - this.priority = priority; - } - - /** - * @return the completionDate - */ - public Date getCompletionDate() { - return completionDate; - } - - /** - * @param completionDate - * the completionDate to set - */ - public void setCompletionDate(Date completionDate) { - this.completionDate = completionDate; - } - - /** - * @return the complete - */ - public boolean isComplete() { - return complete; - } - - /** - * @param complete - * the complete to set - */ - public void setComplete(boolean complete) { - this.complete = complete; - } + @Identifier + private long id; + + private String name; + + private int priority; + + private Date completionDate; + + private boolean complete; + + public Task() { + + } + + public Task(long id, String name, int priority, boolean complete) { + this.id = id; + this.name = name; + this.priority = priority; + this.complete = complete; + } + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the priority + */ + public int getPriority() { + return priority; + } + + /** + * @param priority + * the priority to set + */ + public void setPriority(int priority) { + this.priority = priority; + } + + /** + * @return the completionDate + */ + public Date getCompletionDate() { + return completionDate; + } + + /** + * @param completionDate + * the completionDate to set + */ + public void setCompletionDate(Date completionDate) { + this.completionDate = completionDate; + } + + /** + * @return the complete + */ + public boolean isComplete() { + return complete; + } + + /** + * @param complete + * the complete to set + */ + public void setComplete(boolean complete) { + this.complete = complete; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/TaskName.java b/src/test/java/com/jmethods/catatumbo/entities/TaskName.java index ef09da9..1f171a5 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/TaskName.java +++ b/src/test/java/com/jmethods/catatumbo/entities/TaskName.java @@ -26,46 +26,46 @@ @Entity(kind = "Task") public class TaskName { - @Identifier - private long id; + @Identifier + private long id; - private String name; + private String name; - /** - * Creates a new instance of TaskName. - */ - public TaskName() { - // @ToDo Auto-generated constructor stub - } + /** + * Creates a new instance of TaskName. + */ + public TaskName() { + // @ToDo Auto-generated constructor stub + } - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/UnindexedByteArrayField.java b/src/test/java/com/jmethods/catatumbo/entities/UnindexedByteArrayField.java index 5a6d05d..f2dc199 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/UnindexedByteArrayField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/UnindexedByteArrayField.java @@ -27,40 +27,40 @@ @Entity public class UnindexedByteArrayField { - @Identifier - private long id; + @Identifier + private long id; - @Property(indexed = false) - private byte[] junk; + @Property(indexed = false) + private byte[] junk; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the salt - */ - public byte[] getJunk() { - return junk; - } + /** + * @return the salt + */ + public byte[] getJunk() { + return junk; + } - /** - * @param salt - * the salt to set - */ - public void setJunk(byte[] salt) { - this.junk = salt; - } + /** + * @param salt + * the salt to set + */ + public void setJunk(byte[] salt) { + this.junk = salt; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/UnindexedStringField.java b/src/test/java/com/jmethods/catatumbo/entities/UnindexedStringField.java index fe8bc4a..b664f51 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/UnindexedStringField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/UnindexedStringField.java @@ -26,40 +26,40 @@ */ @Entity public class UnindexedStringField { - @Identifier - private long id; + @Identifier + private long id; - @Property(indexed = false) - private String hugeString; + @Property(indexed = false) + private String hugeString; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the hugeString - */ - public String getHugeString() { - return hugeString; - } + /** + * @return the hugeString + */ + public String getHugeString() { + return hugeString; + } - /** - * @param hugeString - * the hugeString to set - */ - public void setHugeString(String hugeString) { - this.hugeString = hugeString; - } + /** + * @param hugeString + * the hugeString to set + */ + public void setHugeString(String hugeString) { + this.hugeString = hugeString; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/User.java b/src/test/java/com/jmethods/catatumbo/entities/User.java index d9b14b5..64c0e0d 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/User.java +++ b/src/test/java/com/jmethods/catatumbo/entities/User.java @@ -31,83 +31,83 @@ @Entity public class User { - @Identifier - private UserId id; - - @Key - private DatastoreKey key; - - private String name; - - /** - * @return the id - */ - public UserId getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(UserId id) { - this.id = id; - } - - /** - * @return the key - */ - public DatastoreKey getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(DatastoreKey key) { - this.key = key; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - User that = (User) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.key, that.key) - && Objects.equals(this.name, that.name); - } - - public static User getSample1() { - User entity = new User(); - entity.setName("John Doe"); - return entity; - } - - public static User getSample2() { - User entity = new User(); - entity.setId(new UserId(0)); - entity.setName("John Doe"); - return entity; - } + @Identifier + private UserId id; + + @Key + private DatastoreKey key; + + private String name; + + /** + * @return the id + */ + public UserId getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(UserId id) { + this.id = id; + } + + /** + * @return the key + */ + public DatastoreKey getKey() { + return key; + } + + /** + * @param key + * the key to set + */ + public void setKey(DatastoreKey key) { + this.key = key; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + User that = (User) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.key, that.key) + && Objects.equals(this.name, that.name); + } + + public static User getSample1() { + User entity = new User(); + entity.setName("John Doe"); + return entity; + } + + public static User getSample2() { + User entity = new User(); + entity.setId(new UserId(0)); + entity.setName("John Doe"); + return entity; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/UserContact.java b/src/test/java/com/jmethods/catatumbo/entities/UserContact.java index d4e20a5..e7cc9a3 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/UserContact.java +++ b/src/test/java/com/jmethods/catatumbo/entities/UserContact.java @@ -31,96 +31,98 @@ @Entity public class UserContact { - @Identifier - private long id; - - @ParentKey - private DatastoreKey userKey; - - @Key - private DatastoreKey contactKey; - - private String contactName; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the userKey - */ - public DatastoreKey getUserKey() { - return userKey; - } - - /** - * @param userKey - * the userKey to set - */ - public void setUserKey(DatastoreKey userKey) { - this.userKey = userKey; - } - - /** - * @return the contactKey - */ - public DatastoreKey getContactKey() { - return contactKey; - } - - /** - * @param contactKey - * the contactKey to set - */ - public void setContactKey(DatastoreKey contactKey) { - this.contactKey = contactKey; - } - - /** - * @return the contactName - */ - public String getContactName() { - return contactName; - } - - /** - * @param contactName - * the contactName to set - */ - public void setContactName(String contactName) { - this.contactName = contactName; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - UserContact that = (UserContact) obj; - return Objects.equal(this.id, that.id) && Objects.equal(this.userKey, that.userKey) - && Objects.equal(this.contactKey, that.contactKey) && Objects.equal(this.contactName, that.contactName); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("UserContact [id=").append(id).append(", userKey=").append(userKey).append(", contactKey=") - .append(contactKey).append(", contactName=").append(contactName).append("]"); - return builder.toString(); - } + @Identifier + private long id; + + @ParentKey + private DatastoreKey userKey; + + @Key + private DatastoreKey contactKey; + + private String contactName; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the userKey + */ + public DatastoreKey getUserKey() { + return userKey; + } + + /** + * @param userKey + * the userKey to set + */ + public void setUserKey(DatastoreKey userKey) { + this.userKey = userKey; + } + + /** + * @return the contactKey + */ + public DatastoreKey getContactKey() { + return contactKey; + } + + /** + * @param contactKey + * the contactKey to set + */ + public void setContactKey(DatastoreKey contactKey) { + this.contactKey = contactKey; + } + + /** + * @return the contactName + */ + public String getContactName() { + return contactName; + } + + /** + * @param contactName + * the contactName to set + */ + public void setContactName(String contactName) { + this.contactName = contactName; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + UserContact that = (UserContact) obj; + return Objects.equal(this.id, that.id) && Objects.equal(this.userKey, that.userKey) + && Objects.equal(this.contactKey, that.contactKey) + && Objects.equal(this.contactName, that.contactName); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("UserContact [id=").append(id).append(", userKey=").append(userKey) + .append(", contactKey=").append(contactKey).append(", contactName=").append(contactName) + .append("]"); + return builder.toString(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/UserId.java b/src/test/java/com/jmethods/catatumbo/entities/UserId.java index 6a97a8f..e3b81f5 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/UserId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/UserId.java @@ -22,11 +22,11 @@ */ public class UserId extends GenericLongId { - /** - * @param value - */ - public UserId(long value) { - super(value); - } + /** + * @param value + */ + public UserId(long value) { + super(value); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/Visitor.java b/src/test/java/com/jmethods/catatumbo/entities/Visitor.java index 6230ea7..8204600 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/Visitor.java +++ b/src/test/java/com/jmethods/catatumbo/entities/Visitor.java @@ -29,78 +29,78 @@ @Entity public class Visitor { - public Visitor() { - timestamp = new Date(); - } - - public Visitor(DeviceType deviceType) { - timestamp = new Date(); - this.deviceType = deviceType; - } - - @Identifier - private long id; - - private Date timestamp; - - private DeviceType deviceType; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the timestamp - */ - public Date getTimestamp() { - return timestamp; - } - - /** - * @param timestamp - * the timestamp to set - */ - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - /** - * @return the deviceType - */ - public DeviceType getDeviceType() { - return deviceType; - } - - /** - * @param deviceType - * the deviceType to set - */ - public void setDeviceType(DeviceType deviceType) { - this.deviceType = deviceType; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || !obj.getClass().equals(this.getClass())) { - return false; - } - Visitor that = (Visitor) obj; - return this.id == that.id && Objects.equals(this.timestamp, that.timestamp) - && Objects.equals(this.deviceType, that.deviceType); - } + public Visitor() { + timestamp = new Date(); + } + + public Visitor(DeviceType deviceType) { + timestamp = new Date(); + this.deviceType = deviceType; + } + + @Identifier + private long id; + + private Date timestamp; + + private DeviceType deviceType; + + /** + * @return the id + */ + public long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } + + /** + * @return the timestamp + */ + public Date getTimestamp() { + return timestamp; + } + + /** + * @param timestamp + * the timestamp to set + */ + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the deviceType + */ + public DeviceType getDeviceType() { + return deviceType; + } + + /** + * @param deviceType + * the deviceType to set + */ + public void setDeviceType(DeviceType deviceType) { + this.deviceType = deviceType; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj == null || !obj.getClass().equals(this.getClass())) { + return false; + } + Visitor that = (Visitor) obj; + return this.id == that.id && Objects.equals(this.timestamp, that.timestamp) + && Objects.equals(this.deviceType, that.deviceType); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WildAnimal.java b/src/test/java/com/jmethods/catatumbo/entities/WildAnimal.java index 6eec042..a39e9d1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WildAnimal.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WildAnimal.java @@ -27,11 +27,11 @@ @MappedSuperClass @ExcludeSuperclassListeners public class WildAnimal extends Animal { - @PreInsert - public void insertingWildAnimal() { - if (value.trim().length() > 0) { - value += "->"; - } - value += WildAnimal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - } + @PreInsert + public void insertingWildAnimal() { + if (value.trim().length() > 0) { + value += "->"; + } + value += WildAnimal.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerId.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerId.java index c342bbe..2f3b5e9 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerId.java @@ -22,14 +22,14 @@ */ public class WrappedIntegerId { - private int value; + private int value; - public WrappedIntegerId(int value) { - this.value = value; - } + public WrappedIntegerId(int value) { + this.value = value; + } - public int getValue() { - return value; - } + public int getValue() { + return value; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerIdEntity.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerIdEntity.java index 6c1cd46..7324b44 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerIdEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedIntegerIdEntity.java @@ -26,39 +26,39 @@ @Entity public class WrappedIntegerIdEntity { - @Identifier - private WrappedIntegerId id; + @Identifier + private WrappedIntegerId id; - private String name; + private String name; - /** - * @return the id - */ - public WrappedIntegerId getId() { - return id; - } + /** + * @return the id + */ + public WrappedIntegerId getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(WrappedIntegerId id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(WrappedIntegerId id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongId.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongId.java index 35ce82d..62a93d0 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongId.java @@ -22,33 +22,33 @@ */ public class WrappedLongId { - private long value; - - public WrappedLongId(long value) { - this.value = value; - } - - public long getValue() { - return value; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("WrappedLongId [value=").append(value).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedLongId that = (WrappedLongId) obj; - return this.value == that.value; - } + private long value; + + public WrappedLongId(long value) { + this.value = value; + } + + public long getValue() { + return value; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("WrappedLongId [value=").append(value).append("]"); + return builder.toString(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedLongId that = (WrappedLongId) obj; + return this.value == that.value; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongIdEntity.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongIdEntity.java index 6f07d50..eeec78e 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongIdEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongIdEntity.java @@ -28,78 +28,78 @@ @Entity public class WrappedLongIdEntity { - @Identifier - private WrappedLongId id; - - private String name; - - /** - * @return the id - */ - public WrappedLongId getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(WrappedLongId id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - - public static WrappedLongIdEntity getSample1() { - WrappedLongIdEntity user = new WrappedLongIdEntity(); - user.setName("johndoe"); - return user; - } - - public static WrappedLongIdEntity getSample2() { - WrappedLongIdEntity user = new WrappedLongIdEntity(); - user.setId(new WrappedLongId(0L)); - user.setName("johndoe"); - return user; - } - - public static WrappedLongIdEntity getSample3() { - WrappedLongIdEntity user = new WrappedLongIdEntity(); - user.setId(new WrappedLongId(50000L)); - user.setName("johndoe"); - return user; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedLongIdEntity that = (WrappedLongIdEntity) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); - } + @Identifier + private WrappedLongId id; + + private String name; + + /** + * @return the id + */ + public WrappedLongId getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(WrappedLongId id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + public static WrappedLongIdEntity getSample1() { + WrappedLongIdEntity user = new WrappedLongIdEntity(); + user.setName("johndoe"); + return user; + } + + public static WrappedLongIdEntity getSample2() { + WrappedLongIdEntity user = new WrappedLongIdEntity(); + user.setId(new WrappedLongId(0L)); + user.setName("johndoe"); + return user; + } + + public static WrappedLongIdEntity getSample3() { + WrappedLongIdEntity user = new WrappedLongIdEntity(); + user.setId(new WrappedLongId(50000L)); + user.setName("johndoe"); + return user; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedLongIdEntity that = (WrappedLongIdEntity) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectId.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectId.java index 3851c34..25c2fa9 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectId.java @@ -24,33 +24,33 @@ */ public class WrappedLongObjectId { - private Long value; - - public WrappedLongObjectId(Long value) { - this.value = value; - } - - public Long getValue() { - return value; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("WrappedLongObjectId [value=").append(value).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedLongObjectId that = (WrappedLongObjectId) obj; - return Objects.equals(this.value, that.value); - } + private Long value; + + public WrappedLongObjectId(Long value) { + this.value = value; + } + + public Long getValue() { + return value; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("WrappedLongObjectId [value=").append(value).append("]"); + return builder.toString(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedLongObjectId that = (WrappedLongObjectId) obj; + return Objects.equals(this.value, that.value); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectIdEntity.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectIdEntity.java index 24fb0dd..609b4d7 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectIdEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedLongObjectIdEntity.java @@ -28,85 +28,86 @@ @Entity public class WrappedLongObjectIdEntity { - @Identifier - private WrappedLongObjectId id; - - private String name; - - /** - * @return the id - */ - public WrappedLongObjectId getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(WrappedLongObjectId id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("WrappedLongObjectIdEntity").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - - public static WrappedLongObjectIdEntity getSample1() { - WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); - entity.setName("johndoe"); - return entity; - } - - public static WrappedLongObjectIdEntity getSample2() { - WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); - entity.setId(new WrappedLongObjectId(null)); - entity.setName("johndoe"); - return entity; - } - - public static WrappedLongObjectIdEntity getSample3() { - WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); - entity.setId(new WrappedLongObjectId(0L)); - entity.setName("johndoe"); - return entity; - } - - public static WrappedLongObjectIdEntity getSample4() { - WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); - entity.setId(new WrappedLongObjectId(60000L)); - entity.setName("johndoe"); - return entity; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedLongObjectIdEntity that = (WrappedLongObjectIdEntity) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); - } + @Identifier + private WrappedLongObjectId id; + + private String name; + + /** + * @return the id + */ + public WrappedLongObjectId getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(WrappedLongObjectId id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("WrappedLongObjectIdEntity").append(id).append(", name=").append(name) + .append("]"); + return builder.toString(); + } + + public static WrappedLongObjectIdEntity getSample1() { + WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); + entity.setName("johndoe"); + return entity; + } + + public static WrappedLongObjectIdEntity getSample2() { + WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); + entity.setId(new WrappedLongObjectId(null)); + entity.setName("johndoe"); + return entity; + } + + public static WrappedLongObjectIdEntity getSample3() { + WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); + entity.setId(new WrappedLongObjectId(0L)); + entity.setName("johndoe"); + return entity; + } + + public static WrappedLongObjectIdEntity getSample4() { + WrappedLongObjectIdEntity entity = new WrappedLongObjectIdEntity(); + entity.setId(new WrappedLongObjectId(60000L)); + entity.setName("johndoe"); + return entity; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedLongObjectIdEntity that = (WrappedLongObjectIdEntity) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedStringId.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedStringId.java index 1ec57bb..44c88a8 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedStringId.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedStringId.java @@ -22,33 +22,33 @@ */ public class WrappedStringId { - private String value; - - public WrappedStringId(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("WrappedStringId [value=").append(value).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedStringId that = (WrappedStringId) obj; - return this.value == that.value; - } + private String value; + + public WrappedStringId(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("WrappedStringId [value=").append(value).append("]"); + return builder.toString(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedStringId that = (WrappedStringId) obj; + return this.value == that.value; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/WrappedStringIdEntity.java b/src/test/java/com/jmethods/catatumbo/entities/WrappedStringIdEntity.java index 6535ce1..72a8e6b 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/WrappedStringIdEntity.java +++ b/src/test/java/com/jmethods/catatumbo/entities/WrappedStringIdEntity.java @@ -28,85 +28,86 @@ @Entity public class WrappedStringIdEntity { - @Identifier - private WrappedStringId id; - - private String name; - - /** - * @return the id - */ - public WrappedStringId getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(WrappedStringId id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("WrappedStringIdEntity [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - - public static WrappedStringIdEntity getSample1() { - WrappedStringIdEntity entity = new WrappedStringIdEntity(); - entity.setName("johndoe"); - return entity; - } - - public static WrappedStringIdEntity getSample2() { - WrappedStringIdEntity entity = new WrappedStringIdEntity(); - entity.setId(new WrappedStringId(null)); - entity.setName("johndoe"); - return entity; - } - - public static WrappedStringIdEntity getSample3() { - WrappedStringIdEntity entity = new WrappedStringIdEntity(); - entity.setId(new WrappedStringId("")); - entity.setName("johndoe"); - return entity; - } - - public static WrappedStringIdEntity getSample4() { - WrappedStringIdEntity entity = new WrappedStringIdEntity(); - entity.setId(new WrappedStringId("mykey")); - entity.setName("johndoe"); - return entity; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || !this.getClass().equals(obj.getClass())) { - return false; - } - WrappedStringIdEntity that = (WrappedStringIdEntity) obj; - return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); - } + @Identifier + private WrappedStringId id; + + private String name; + + /** + * @return the id + */ + public WrappedStringId getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(WrappedStringId id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("WrappedStringIdEntity [id=").append(id).append(", name=").append(name) + .append("]"); + return builder.toString(); + } + + public static WrappedStringIdEntity getSample1() { + WrappedStringIdEntity entity = new WrappedStringIdEntity(); + entity.setName("johndoe"); + return entity; + } + + public static WrappedStringIdEntity getSample2() { + WrappedStringIdEntity entity = new WrappedStringIdEntity(); + entity.setId(new WrappedStringId(null)); + entity.setName("johndoe"); + return entity; + } + + public static WrappedStringIdEntity getSample3() { + WrappedStringIdEntity entity = new WrappedStringIdEntity(); + entity.setId(new WrappedStringId("")); + entity.setName("johndoe"); + return entity; + } + + public static WrappedStringIdEntity getSample4() { + WrappedStringIdEntity entity = new WrappedStringIdEntity(); + entity.setId(new WrappedStringId("mykey")); + entity.setName("johndoe"); + return entity; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !this.getClass().equals(obj.getClass())) { + return false; + } + WrappedStringIdEntity that = (WrappedStringIdEntity) obj; + return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name); + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ZipCode.java b/src/test/java/com/jmethods/catatumbo/entities/ZipCode.java index 79e43d3..a95bd49 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ZipCode.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ZipCode.java @@ -29,85 +29,86 @@ @Embeddable public class ZipCode { - @Property(name = "zip") - private String fiveDigits; - - @Property(name = "zipx", indexed = false, optional = true) - private String fourDigits; - - @Embedded(name = "useless", indexed = true) - private AnotherEmbeddable anotherEmbeddable = new AnotherEmbeddable(); - - /** - * - */ - public ZipCode() { - // TODO Auto-generated constructor stub - } - - /** - * @return the fiveDigits - */ - public String getFiveDigits() { - return fiveDigits; - } - - /** - * @param fiveDigits - * the fiveDigits to set - */ - public void setFiveDigits(String fiveDigits) { - this.fiveDigits = fiveDigits; - } - - /** - * @return the fourDigits - */ - public String getFourDigits() { - return fourDigits; - } - - /** - * @param fourDigits - * the fourDigits to set - */ - public void setFourDigits(String fourDigits) { - this.fourDigits = fourDigits; - } - - @Override - public String toString() { - return fiveDigits + "-" + fourDigits; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof ZipCode)) { - return false; - } - ZipCode that = (ZipCode) obj; - return Objects.equals(this.fiveDigits, that.fiveDigits) && Objects.equals(this.fourDigits, that.fourDigits) - && Objects.equals(this.anotherEmbeddable, that.anotherEmbeddable); - } - - @Override - public int hashCode() { - return Objects.hash(fiveDigits, fourDigits, anotherEmbeddable); - } - - /** - * @return the anotherEmbeddable - */ - public AnotherEmbeddable getAnotherEmbeddable() { - return anotherEmbeddable; - } - - /** - * @param anotherEmbeddable - * the anotherEmbeddable to set - */ - public void setAnotherEmbeddable(AnotherEmbeddable anotherEmbeddable) { - this.anotherEmbeddable = anotherEmbeddable; - } + @Property(name = "zip") + private String fiveDigits; + + @Property(name = "zipx", indexed = false, optional = true) + private String fourDigits; + + @Embedded(name = "useless", indexed = true) + private AnotherEmbeddable anotherEmbeddable = new AnotherEmbeddable(); + + /** + * + */ + public ZipCode() { + // TODO Auto-generated constructor stub + } + + /** + * @return the fiveDigits + */ + public String getFiveDigits() { + return fiveDigits; + } + + /** + * @param fiveDigits + * the fiveDigits to set + */ + public void setFiveDigits(String fiveDigits) { + this.fiveDigits = fiveDigits; + } + + /** + * @return the fourDigits + */ + public String getFourDigits() { + return fourDigits; + } + + /** + * @param fourDigits + * the fourDigits to set + */ + public void setFourDigits(String fourDigits) { + this.fourDigits = fourDigits; + } + + @Override + public String toString() { + return fiveDigits + "-" + fourDigits; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof ZipCode)) { + return false; + } + ZipCode that = (ZipCode) obj; + return Objects.equals(this.fiveDigits, that.fiveDigits) + && Objects.equals(this.fourDigits, that.fourDigits) + && Objects.equals(this.anotherEmbeddable, that.anotherEmbeddable); + } + + @Override + public int hashCode() { + return Objects.hash(fiveDigits, fourDigits, anotherEmbeddable); + } + + /** + * @return the anotherEmbeddable + */ + public AnotherEmbeddable getAnotherEmbeddable() { + return anotherEmbeddable; + } + + /** + * @param anotherEmbeddable + * the anotherEmbeddable to set + */ + public void setAnotherEmbeddable(AnotherEmbeddable anotherEmbeddable) { + this.anotherEmbeddable = anotherEmbeddable; + } } diff --git a/src/test/java/com/jmethods/catatumbo/entities/ZonedDateTimeField.java b/src/test/java/com/jmethods/catatumbo/entities/ZonedDateTimeField.java index 21da63d..b96aee1 100644 --- a/src/test/java/com/jmethods/catatumbo/entities/ZonedDateTimeField.java +++ b/src/test/java/com/jmethods/catatumbo/entities/ZonedDateTimeField.java @@ -28,44 +28,44 @@ @Entity public class ZonedDateTimeField { - @Identifier - private long id; + @Identifier + private long id; - private ZonedDateTime timestamp; + private ZonedDateTime timestamp; - /** - * @return the id - */ - public long getId() { - return id; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @param id - * the id to set - */ - public void setId(long id) { - this.id = id; - } + /** + * @param id + * the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @return the timestamp - */ - public ZonedDateTime getTimestamp() { - return timestamp; - } + /** + * @return the timestamp + */ + public ZonedDateTime getTimestamp() { + return timestamp; + } - /** - * @param timestamp - * the timestamp to set - */ - public void setTimestamp(ZonedDateTime timestamp) { - this.timestamp = timestamp; - } + /** + * @param timestamp + * the timestamp to set + */ + public void setTimestamp(ZonedDateTime timestamp) { + this.timestamp = timestamp; + } - @Override - public String toString() { - return "ZonedDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; - } + @Override + public String toString() { + return "ZonedDateTimeField [id=" + id + ", timestamp=" + timestamp + "]"; + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/AllTests.java b/src/test/java/com/jmethods/catatumbo/impl/AllTests.java index 8909bfe..4db2b17 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/AllTests.java +++ b/src/test/java/com/jmethods/catatumbo/impl/AllTests.java @@ -26,8 +26,8 @@ */ @RunWith(Suite.class) @SuiteClasses({ EntityIntrospectorTest.class, ExternalListenerIntrospectorTest.class, - InternalListenerIntrospectorTest.class, IntrospectionUtilsTest.class, LRUCacheTest.class, MarshallerTest.class, - UnmarshallerTest.class }) + InternalListenerIntrospectorTest.class, IntrospectionUtilsTest.class, LRUCacheTest.class, + MarshallerTest.class, UnmarshallerTest.class }) public class AllTests { } diff --git a/src/test/java/com/jmethods/catatumbo/impl/EntityIntrospectorTest.java b/src/test/java/com/jmethods/catatumbo/impl/EntityIntrospectorTest.java index 4b6075c..0fa0988 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/EntityIntrospectorTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/EntityIntrospectorTest.java @@ -66,249 +66,252 @@ */ public class EntityIntrospectorTest { - @Test - public void testIntrospect_Embedded() { - EntityMetadata metadata = EntityIntrospector.introspect(Customer.class); - System.out.println(metadata); - System.out.println("************"); - metadata = EntityIntrospector.introspect(Customer.class); - System.out.println(metadata); - - } - - @Test - public void testIntrospect_OptimisticLock1() { - EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLock1.class); - assertTrue(Objects.equals(metadata.getVersionMetadata(), metadata.getPropertyMetadata("version"))); - } - - @Test(expected = EntityManagerException.class) - public void testIntrospect_OptimisticLock_StringField() { - EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLockBad1.class); - } - - @Test(expected = EntityManagerException.class) - public void testIntrospect_OptimisticLock_TwoVersionFields() { - EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLockBad2.class); - } - - @Test - public void testIntrospect_Listeners1() { - EntityMetadata metadata = EntityIntrospector.introspect(StringField.class); - assertNull(metadata.getEntityListenersMetadata().getCallbacks()); - } - - @Test - public void testIntrospect_Listeners2() { - EntityMetadata metadata = EntityIntrospector.introspect(Cat.class); - EntityListenersMetadata elm = metadata.getEntityListenersMetadata(); - assertEquals(1, elm.getCallbacks().size()); - assertEquals(3, elm.getCallbacks(CallbackType.PRE_INSERT).size()); - } - - @Test - public void testIntrospect_MultiThreaded() { - class MyRunnable implements Runnable { - private Class clazz; - - public MyRunnable(Class clazz) { - this.clazz = clazz; - } - - @Override - public void run() { - EntityMetadata metadata = EntityIntrospector.introspect(clazz); - System.out.println(metadata); - } - } - ; - Thread[] threads = new Thread[4]; - Class[] entityClasses = { StringId.class, StringField.class, StringId.class, StringField.class }; - for (int i = 0; i < threads.length; i++) { - threads[i] = new Thread(new MyRunnable(entityClasses[i])); - threads[i].start(); - } - for (int i = 0; i < threads.length; i++) { - try { - threads[i].join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Test - public void testIntrospect_Embedded_Imploded() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(Contact.class); - Map embeddedMetadataMap = entityMetadata.getEmbeddedMetadataMap(); - assertEquals(3, embeddedMetadataMap.size()); - } - - @Test - public void testIntrospect_Task() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(Task.class); - assertEquals("Task", entityMetadata.getKind()); - assertEquals(4, entityMetadata.getPropertyMetadataCollection().size()); - } - - @Test - public void testIntrospect_TaskName() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(TaskName.class); - assertEquals("Task", entityMetadata.getKind()); - assertEquals(1, entityMetadata.getPropertyMetadataCollection().size()); - } - - @Test(expected = EntityManagerException.class) - public void testIntrospect_Button() { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(Button.class); - } catch (EntityManagerException exp) { - System.err.println(exp.getMessage()); - throw exp; - } - } - - @Test(expected = NoSuitableMapperException.class) - public void testNoSuitableMapper() { - try { - EntityIntrospector.introspect(NoSuitableMapperEntity.class); - } catch (NoSuitableMapperException exp) { - System.err.println(exp); - throw exp; - } - } - - @Test(expected = NoAccessorMethodException.class) - public void testNoGetterMethod() { - try { - EntityIntrospector.introspect(NoGetterMethodEntity.class); - } catch (NoAccessorMethodException exp) { - System.err.println(exp); - throw exp; - } - } - - @Test(expected = NoMutatorMethodException.class) - public void testNoSetterMethod() { - try { - EntityIntrospector.introspect(NoSetterMethodEntity.class); - } catch (NoMutatorMethodException exp) { - System.err.println(exp); - throw exp; - } - } - - @Test(expected = NoMutatorMethodException.class) - public void testNoSetterMethod_2() { - try { - EntityIntrospector.introspect(NoSetterMethodEntity2.class); - } catch (NoMutatorMethodException exp) { - System.err.println(exp); - throw exp; - } - } - - @Test(expected = EntityManagerException.class) - public void testInvalidConstructionStrategy() { - try { - EntityIntrospector.introspect(NoDefaultConstrctorEntity.class); - } catch (EntityManagerException exp) { - System.err.println(exp); - throw exp; - } - } - - @Test - public void testIntrospectWrappedLongId() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(WrappedLongIdEntity.class); - IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); - IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); - assertEquals(DataType.LONG, identifierMetadata.getDataType()); - assertNotNull(idClassMetadata); - assertNotNull(idClassMetadata.getReadMethod()); - assertNotNull(idClassMetadata.getConstructor()); - } - - @Test(expected = EntityManagerException.class) - public void testIntrospectWrappedIntegerId() { - try { - EntityMetadata entityMetadata = EntityIntrospector.introspect(WrappedIntegerIdEntity.class); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testIntrospectOptionalPrimitive() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalPrimitive.class); - PropertyMetadata propertyMetadata = entityMetadata.getPropertyMetadata("optionalInt"); - assertFalse(propertyMetadata.isOptional()); - } - - @Test - public void testIntrospectOptionalVersion() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalVersion.class); - PropertyMetadata propertyMetadata = entityMetadata.getVersionMetadata(); - assertFalse(propertyMetadata.isOptional()); - } - - @Test - public void testIntrospectOptionalCreatedTimestamp() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalCreatedTimestamp.class); - PropertyMetadata propertyMetadata = entityMetadata.getCreatedTimestampMetadata(); - assertFalse(propertyMetadata.isOptional()); - } - - @Test - public void testIntrospectOptionalUpdatedTimestamp() { - EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalUpdatedTimestamp.class); - PropertyMetadata propertyMetadata = entityMetadata.getUpdatedTimestampMetadata(); - assertFalse(propertyMetadata.isOptional()); - } - - @Test(expected = UnsupportedConstructionStrategyException.class) - public void testBadBuilderEntity1() { - try { - EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity1.class); - } catch (UnsupportedConstructionStrategyException exp) { - System.err.println(exp); - throw exp; - } - - } - - @Test(expected = UnsupportedConstructionStrategyException.class) - public void testBadBuilderEntity2() { - try { - EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity2.class); - } catch (UnsupportedConstructionStrategyException exp) { - System.err.println(exp); - throw exp; - } - - } - - @Test(expected = EntityManagerException.class) - public void testBadBuilderEntity3() { - try { - EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity3.class); - } catch (EntityManagerException exp) { - System.err.println(exp); - throw exp; - } - - } - - @Test(expected = NoMutatorMethodException.class) - public void testBadBuilderEntity4() { - try { - EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity4.class); - } catch (NoMutatorMethodException exp) { - System.err.println(exp); - throw exp; - } - - } + @Test + public void testIntrospect_Embedded() { + EntityMetadata metadata = EntityIntrospector.introspect(Customer.class); + System.out.println(metadata); + System.out.println("************"); + metadata = EntityIntrospector.introspect(Customer.class); + System.out.println(metadata); + + } + + @Test + public void testIntrospect_OptimisticLock1() { + EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLock1.class); + assertTrue( + Objects.equals(metadata.getVersionMetadata(), metadata.getPropertyMetadata("version"))); + } + + @Test(expected = EntityManagerException.class) + public void testIntrospect_OptimisticLock_StringField() { + EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLockBad1.class); + } + + @Test(expected = EntityManagerException.class) + public void testIntrospect_OptimisticLock_TwoVersionFields() { + EntityMetadata metadata = EntityIntrospector.introspect(OptimisticLockBad2.class); + } + + @Test + public void testIntrospect_Listeners1() { + EntityMetadata metadata = EntityIntrospector.introspect(StringField.class); + assertNull(metadata.getEntityListenersMetadata().getCallbacks()); + } + + @Test + public void testIntrospect_Listeners2() { + EntityMetadata metadata = EntityIntrospector.introspect(Cat.class); + EntityListenersMetadata elm = metadata.getEntityListenersMetadata(); + assertEquals(1, elm.getCallbacks().size()); + assertEquals(3, elm.getCallbacks(CallbackType.PRE_INSERT).size()); + } + + @Test + public void testIntrospect_MultiThreaded() { + class MyRunnable implements Runnable { + private Class clazz; + + public MyRunnable(Class clazz) { + this.clazz = clazz; + } + + @Override + public void run() { + EntityMetadata metadata = EntityIntrospector.introspect(clazz); + System.out.println(metadata); + } + } + ; + Thread[] threads = new Thread[4]; + Class[] entityClasses = { StringId.class, StringField.class, StringId.class, + StringField.class }; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread(new MyRunnable(entityClasses[i])); + threads[i].start(); + } + for (int i = 0; i < threads.length; i++) { + try { + threads[i].join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + @Test + public void testIntrospect_Embedded_Imploded() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(Contact.class); + Map embeddedMetadataMap = entityMetadata + .getEmbeddedMetadataMap(); + assertEquals(3, embeddedMetadataMap.size()); + } + + @Test + public void testIntrospect_Task() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(Task.class); + assertEquals("Task", entityMetadata.getKind()); + assertEquals(4, entityMetadata.getPropertyMetadataCollection().size()); + } + + @Test + public void testIntrospect_TaskName() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(TaskName.class); + assertEquals("Task", entityMetadata.getKind()); + assertEquals(1, entityMetadata.getPropertyMetadataCollection().size()); + } + + @Test(expected = EntityManagerException.class) + public void testIntrospect_Button() { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(Button.class); + } catch (EntityManagerException exp) { + System.err.println(exp.getMessage()); + throw exp; + } + } + + @Test(expected = NoSuitableMapperException.class) + public void testNoSuitableMapper() { + try { + EntityIntrospector.introspect(NoSuitableMapperEntity.class); + } catch (NoSuitableMapperException exp) { + System.err.println(exp); + throw exp; + } + } + + @Test(expected = NoAccessorMethodException.class) + public void testNoGetterMethod() { + try { + EntityIntrospector.introspect(NoGetterMethodEntity.class); + } catch (NoAccessorMethodException exp) { + System.err.println(exp); + throw exp; + } + } + + @Test(expected = NoMutatorMethodException.class) + public void testNoSetterMethod() { + try { + EntityIntrospector.introspect(NoSetterMethodEntity.class); + } catch (NoMutatorMethodException exp) { + System.err.println(exp); + throw exp; + } + } + + @Test(expected = NoMutatorMethodException.class) + public void testNoSetterMethod_2() { + try { + EntityIntrospector.introspect(NoSetterMethodEntity2.class); + } catch (NoMutatorMethodException exp) { + System.err.println(exp); + throw exp; + } + } + + @Test(expected = EntityManagerException.class) + public void testInvalidConstructionStrategy() { + try { + EntityIntrospector.introspect(NoDefaultConstrctorEntity.class); + } catch (EntityManagerException exp) { + System.err.println(exp); + throw exp; + } + } + + @Test + public void testIntrospectWrappedLongId() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(WrappedLongIdEntity.class); + IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata(); + IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata(); + assertEquals(DataType.LONG, identifierMetadata.getDataType()); + assertNotNull(idClassMetadata); + assertNotNull(idClassMetadata.getReadMethod()); + assertNotNull(idClassMetadata.getConstructor()); + } + + @Test(expected = EntityManagerException.class) + public void testIntrospectWrappedIntegerId() { + try { + EntityMetadata entityMetadata = EntityIntrospector.introspect(WrappedIntegerIdEntity.class); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testIntrospectOptionalPrimitive() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalPrimitive.class); + PropertyMetadata propertyMetadata = entityMetadata.getPropertyMetadata("optionalInt"); + assertFalse(propertyMetadata.isOptional()); + } + + @Test + public void testIntrospectOptionalVersion() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalVersion.class); + PropertyMetadata propertyMetadata = entityMetadata.getVersionMetadata(); + assertFalse(propertyMetadata.isOptional()); + } + + @Test + public void testIntrospectOptionalCreatedTimestamp() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalCreatedTimestamp.class); + PropertyMetadata propertyMetadata = entityMetadata.getCreatedTimestampMetadata(); + assertFalse(propertyMetadata.isOptional()); + } + + @Test + public void testIntrospectOptionalUpdatedTimestamp() { + EntityMetadata entityMetadata = EntityIntrospector.introspect(OptionalUpdatedTimestamp.class); + PropertyMetadata propertyMetadata = entityMetadata.getUpdatedTimestampMetadata(); + assertFalse(propertyMetadata.isOptional()); + } + + @Test(expected = UnsupportedConstructionStrategyException.class) + public void testBadBuilderEntity1() { + try { + EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity1.class); + } catch (UnsupportedConstructionStrategyException exp) { + System.err.println(exp); + throw exp; + } + + } + + @Test(expected = UnsupportedConstructionStrategyException.class) + public void testBadBuilderEntity2() { + try { + EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity2.class); + } catch (UnsupportedConstructionStrategyException exp) { + System.err.println(exp); + throw exp; + } + + } + + @Test(expected = EntityManagerException.class) + public void testBadBuilderEntity3() { + try { + EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity3.class); + } catch (EntityManagerException exp) { + System.err.println(exp); + throw exp; + } + + } + + @Test(expected = NoMutatorMethodException.class) + public void testBadBuilderEntity4() { + try { + EntityMetadata metadata = EntityIntrospector.introspect(BadBuilderEntity4.class); + } catch (NoMutatorMethodException exp) { + System.err.println(exp); + throw exp; + } + + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospectorTest.java b/src/test/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospectorTest.java index 55ca751..c367cb5 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospectorTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/ExternalListenerIntrospectorTest.java @@ -16,7 +16,7 @@ package com.jmethods.catatumbo.impl; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Map; @@ -35,44 +35,45 @@ */ public class ExternalListenerIntrospectorTest { - @Test(expected = EntityManagerException.class) - public void testIntrospect_NotEntityListener() { - try { - ExternalListenerIntrospector.introspect(BadExternalListener1.class); - } catch (EntityManagerException exp) { - System.out.println(exp.getMessage()); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect_NotEntityListener() { + try { + ExternalListenerIntrospector.introspect(BadExternalListener1.class); + } catch (EntityManagerException exp) { + System.out.println(exp.getMessage()); + throw exp; + } + } - @Test(expected = EntityManagerException.class) - public void testIntrospect_MultipleCallbacks() { - try { - ExternalListenerIntrospector.introspect(BadExternalListener2.class); - } catch (EntityManagerException exp) { - System.out.println(exp.getMessage()); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect_MultipleCallbacks() { + try { + ExternalListenerIntrospector.introspect(BadExternalListener2.class); + } catch (EntityManagerException exp) { + System.out.println(exp.getMessage()); + throw exp; + } + } - @Test(expected = EntityManagerException.class) - public void testIntrospect_InvalidMethod() { - try { - ExternalListenerIntrospector.introspect(BadExternalListener3.class); - } catch (EntityManagerException exp) { - System.out.println(exp.getMessage()); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect_InvalidMethod() { + try { + ExternalListenerIntrospector.introspect(BadExternalListener3.class); + } catch (EntityManagerException exp) { + System.out.println(exp.getMessage()); + throw exp; + } + } - @Test - public void testIntroSpect1() { - ExternalListenerMetadata metadata = ExternalListenerIntrospector.introspect(GoodExternalListener1.class); - Map callbacks = metadata.getCallbacks(); - assertTrue(metadata.getCallbacks().size() == 3); - assertTrue(callbacks.containsKey(CallbackType.PRE_INSERT)); - assertTrue(callbacks.containsKey(CallbackType.PRE_UPDATE)); - assertTrue(callbacks.containsKey(CallbackType.POST_LOAD)); - } + @Test + public void testIntroSpect1() { + ExternalListenerMetadata metadata = ExternalListenerIntrospector + .introspect(GoodExternalListener1.class); + Map callbacks = metadata.getCallbacks(); + assertTrue(metadata.getCallbacks().size() == 3); + assertTrue(callbacks.containsKey(CallbackType.PRE_INSERT)); + assertTrue(callbacks.containsKey(CallbackType.PRE_UPDATE)); + assertTrue(callbacks.containsKey(CallbackType.POST_LOAD)); + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/InternalListenerIntrospectorTest.java b/src/test/java/com/jmethods/catatumbo/impl/InternalListenerIntrospectorTest.java index c487cdb..a4e63c6 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/InternalListenerIntrospectorTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/InternalListenerIntrospectorTest.java @@ -16,7 +16,9 @@ package com.jmethods.catatumbo.impl; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.junit.Test; @@ -36,70 +38,74 @@ */ public class InternalListenerIntrospectorTest { - @Test - public void testIntrospect1() { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(StringField.class); - assertNull(metadata.getCallbacks()); - } + @Test + public void testIntrospect1() { + InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(StringField.class); + assertNull(metadata.getCallbacks()); + } - @Test - public void testIntrospect2() { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Animal.class); - assertEquals(1, metadata.getCallbacks().size()); - assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); - } + @Test + public void testIntrospect2() { + InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Animal.class); + assertEquals(1, metadata.getCallbacks().size()); + assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); + } - @Test - public void testIntrospect3() { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Pet.class); - assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); - } + @Test + public void testIntrospect3() { + InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Pet.class); + assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); + } - @Test - public void testIntrospect4() { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Dog.class); - assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); - assertNotNull(metadata.getCallbacks().get(CallbackType.POST_INSERT)); - } + @Test + public void testIntrospect4() { + InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(Dog.class); + assertNotNull(metadata.getCallbacks().get(CallbackType.PRE_INSERT)); + assertNotNull(metadata.getCallbacks().get(CallbackType.POST_INSERT)); + } - @Test(expected = EntityManagerException.class) - public void testIntrospect5() { - try { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(BadInternalListener1.class); - } catch (EntityManagerException exp) { - System.out.println(exp); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect5() { + try { + InternalListenerMetadata metadata = InternalListenerIntrospector + .introspect(BadInternalListener1.class); + } catch (EntityManagerException exp) { + System.out.println(exp); + throw exp; + } + } - @Test(expected = EntityManagerException.class) - public void testIntrospect6() { - try { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(BadInternalListener2.class); - } catch (EntityManagerException exp) { - System.out.println(exp); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect6() { + try { + InternalListenerMetadata metadata = InternalListenerIntrospector + .introspect(BadInternalListener2.class); + } catch (EntityManagerException exp) { + System.out.println(exp); + throw exp; + } + } - @Test(expected = EntityManagerException.class) - public void testIntrospect7() { - try { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(BadInternalListener3.class); - } catch (EntityManagerException exp) { - System.out.println(exp); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect7() { + try { + InternalListenerMetadata metadata = InternalListenerIntrospector + .introspect(BadInternalListener3.class); + } catch (EntityManagerException exp) { + System.out.println(exp); + throw exp; + } + } - @Test(expected = EntityManagerException.class) - public void testIntrospect8() { - try { - InternalListenerMetadata metadata = InternalListenerIntrospector.introspect(BadInternalListener4.class); - } catch (EntityManagerException exp) { - System.out.println(exp); - throw exp; - } - } + @Test(expected = EntityManagerException.class) + public void testIntrospect8() { + try { + InternalListenerMetadata metadata = InternalListenerIntrospector + .introspect(BadInternalListener4.class); + } catch (EntityManagerException exp) { + System.out.println(exp); + throw exp; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/IntrospectionUtilsTest.java b/src/test/java/com/jmethods/catatumbo/impl/IntrospectionUtilsTest.java index 621918d..8c8afb1 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/IntrospectionUtilsTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/IntrospectionUtilsTest.java @@ -32,185 +32,187 @@ */ public class IntrospectionUtilsTest { - private static Logger LOGGER = Logger.getLogger(IntrospectionUtilsTest.class.getName()); - - @Test - public void testGetCapitalizedName1() { - String input = "name"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("Name", output); - } - - @Test - public void testGetCapitalizedName2() { - String input = "x"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("X", output); - } - - @Test - public void testGetCapitalizedName3() { - String input = "firstName"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("FirstName", output); - } - - @Test - public void testGetCapitalizedName4() { - String input = "X"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("X", output); - } - - @Test - public void testGetCapitalizedName5() { - String input = "xY"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("xY", output); - } - - @Test - public void testGetCapitalizedName6() { - String input = "xYz"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("xYz", output); - } - - @Test - public void testGetCapitalizedName7() { - String input = "URL"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("URL", output); - } - - @Test - public void testGetCapitalizedName8() { - String input = "uRL"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("uRL", output); - } - - @Test - public void testGetCapitalizedName9() { - String input = "aURL"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("aURL", output); - } - - @Test - public void testGetCapitalizedName10() { - String input = "salesRepCommission"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("SalesRepCommission", output); - } - - @Test - public void testGetCapitalizedName11() { - String input = "xSameAsY"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("xSameAsY", output); - } - - @Test - public void testGetCapitalizedName12() { - String input = "xindex"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("Xindex", output); - } - - @Test - public void testGetCapitalizedName13() { - String input = "xIndex"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("xIndex", output); - } - - @Test - public void testGetCapitalizedName14() { - String input = "_name"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("_name", output); - } - - @Test - public void testGetCapitalizedName15() { - String input = "$abc"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("$abc", output); - } - - @Test - public void testGetCapitalizedName16() { - String input = "$Ab"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("$Ab", output); - } - - @Test - public void testGetCapitalizedName17() { - String input = "a1"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("A1", output); - } - - @Test - public void testGetCapitalizedName18() { - String input = "aB1"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("aB1", output); - } - - @Test - public void testGetCapitalizedName19() { - String input = "ab1"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("Ab1", output); - } - - @Test - public void testGetCapitalizedName20() { - String input = "iPhoneName"; - String output = IntrospectionUtils.getCapitalizedName(input); - LOGGER.info(input + "-->" + output); - assertEquals("iPhoneName", output); - } - - @Test - public void testFindStaticMethod() { - MethodHandle mh = IntrospectionUtils.findStaticMethod(ImmutablePhone.class, "newBuilder", Object.class); - assertNotNull(mh); - } - - @Test - public void testFindInstanceStaticMethod() { - MethodHandle mh = IntrospectionUtils.findInstanceMethod(ImmutablePhone.class, "getCountryCode", String.class); - assertNotNull(mh); - } - - @Test - public void testFindInstanceStaticMethod2() { - MethodHandle mh = IntrospectionUtils.findInstanceMethod(ImmutablePhone.Builder.class, "setCountryCode", null, - String.class); - assertNotNull(mh); - } + private static Logger LOGGER = Logger.getLogger(IntrospectionUtilsTest.class.getName()); + + @Test + public void testGetCapitalizedName1() { + String input = "name"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("Name", output); + } + + @Test + public void testGetCapitalizedName2() { + String input = "x"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("X", output); + } + + @Test + public void testGetCapitalizedName3() { + String input = "firstName"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("FirstName", output); + } + + @Test + public void testGetCapitalizedName4() { + String input = "X"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("X", output); + } + + @Test + public void testGetCapitalizedName5() { + String input = "xY"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("xY", output); + } + + @Test + public void testGetCapitalizedName6() { + String input = "xYz"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("xYz", output); + } + + @Test + public void testGetCapitalizedName7() { + String input = "URL"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("URL", output); + } + + @Test + public void testGetCapitalizedName8() { + String input = "uRL"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("uRL", output); + } + + @Test + public void testGetCapitalizedName9() { + String input = "aURL"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("aURL", output); + } + + @Test + public void testGetCapitalizedName10() { + String input = "salesRepCommission"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("SalesRepCommission", output); + } + + @Test + public void testGetCapitalizedName11() { + String input = "xSameAsY"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("xSameAsY", output); + } + + @Test + public void testGetCapitalizedName12() { + String input = "xindex"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("Xindex", output); + } + + @Test + public void testGetCapitalizedName13() { + String input = "xIndex"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("xIndex", output); + } + + @Test + public void testGetCapitalizedName14() { + String input = "_name"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("_name", output); + } + + @Test + public void testGetCapitalizedName15() { + String input = "$abc"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("$abc", output); + } + + @Test + public void testGetCapitalizedName16() { + String input = "$Ab"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("$Ab", output); + } + + @Test + public void testGetCapitalizedName17() { + String input = "a1"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("A1", output); + } + + @Test + public void testGetCapitalizedName18() { + String input = "aB1"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("aB1", output); + } + + @Test + public void testGetCapitalizedName19() { + String input = "ab1"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("Ab1", output); + } + + @Test + public void testGetCapitalizedName20() { + String input = "iPhoneName"; + String output = IntrospectionUtils.getCapitalizedName(input); + LOGGER.info(input + "-->" + output); + assertEquals("iPhoneName", output); + } + + @Test + public void testFindStaticMethod() { + MethodHandle mh = IntrospectionUtils.findStaticMethod(ImmutablePhone.class, "newBuilder", + Object.class); + assertNotNull(mh); + } + + @Test + public void testFindInstanceStaticMethod() { + MethodHandle mh = IntrospectionUtils.findInstanceMethod(ImmutablePhone.class, "getCountryCode", + String.class); + assertNotNull(mh); + } + + @Test + public void testFindInstanceStaticMethod2() { + MethodHandle mh = IntrospectionUtils.findInstanceMethod(ImmutablePhone.Builder.class, + "setCountryCode", null, String.class); + assertNotNull(mh); + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/LRUCacheTest.java b/src/test/java/com/jmethods/catatumbo/impl/LRUCacheTest.java index b8be850..5082dea 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/LRUCacheTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/LRUCacheTest.java @@ -16,7 +16,8 @@ package com.jmethods.catatumbo.impl; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -26,128 +27,119 @@ */ public class LRUCacheTest { - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#getMaxCapacity()}. - */ - @Test - public void testGetMaxCapacity() { - LRUCache cache = new LRUCache<>(5, 10); - assertTrue(cache.getMaxCapacity() == 10); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#getMaxCapacity()}. + */ + @Test + public void testGetMaxCapacity() { + LRUCache cache = new LRUCache<>(5, 10); + assertTrue(cache.getMaxCapacity() == 10); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#setMaxCapacity(int)}. - */ - @Test - public void testSetMaxCapacity_Good() { - LRUCache cache = new LRUCache<>(2, 5); - cache.setMaxCapacity(20); - assertTrue(cache.getMaxCapacity() == 20); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#setMaxCapacity(int)}. + */ + @Test + public void testSetMaxCapacity_Good() { + LRUCache cache = new LRUCache<>(2, 5); + cache.setMaxCapacity(20); + assertTrue(cache.getMaxCapacity() == 20); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#setMaxCapacity(int)}. - */ - @Test(expected = IllegalArgumentException.class) - public void testSetMaxCapacity_Bad() { - LRUCache cache = new LRUCache<>(2, 5); - cache.setMaxCapacity(0); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#setMaxCapacity(int)}. + */ + @Test(expected = IllegalArgumentException.class) + public void testSetMaxCapacity_Bad() { + LRUCache cache = new LRUCache<>(2, 5); + cache.setMaxCapacity(0); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. - */ - @Test - public void testGet() { - LRUCache squaresCache = new LRUCache<>(5, 10); - for (int i = 1; i <= 5; i++) { - squaresCache.put(i, i * i); - } - assertTrue(squaresCache.get(4) == 16); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. + */ + @Test + public void testGet() { + LRUCache squaresCache = new LRUCache<>(5, 10); + for (int i = 1; i <= 5; i++) { + squaresCache.put(i, i * i); + } + assertTrue(squaresCache.get(4) == 16); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. - */ - @Test - public void testGet_2() { - LRUCache squaresCache = new LRUCache<>(5, 10); - for (int i = 1; i <= 11; i++) { - squaresCache.put(i, i * i); - } - assertTrue(squaresCache.size() == 10 && squaresCache.get(1) == null && squaresCache.get(11) != null); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. + */ + @Test + public void testGet_2() { + LRUCache squaresCache = new LRUCache<>(5, 10); + for (int i = 1; i <= 11; i++) { + squaresCache.put(i, i * i); + } + assertTrue( + squaresCache.size() == 10 && squaresCache.get(1) == null && squaresCache.get(11) != null); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. - */ - @Test - public void testGet_3() { - LRUCache squaresCache = new LRUCache<>(5, 10); - for (int i = 1; i <= 10; i++) { - squaresCache.put(i, i * i); - } - squaresCache.get(1); - squaresCache.put(11, 11 * 11); - assertTrue(squaresCache.size() == 10 && squaresCache.get(1) != null && squaresCache.get(11) != null); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. + */ + @Test + public void testGet_3() { + LRUCache squaresCache = new LRUCache<>(5, 10); + for (int i = 1; i <= 10; i++) { + squaresCache.put(i, i * i); + } + squaresCache.get(1); + squaresCache.put(11, 11 * 11); + assertTrue( + squaresCache.size() == 10 && squaresCache.get(1) != null && squaresCache.get(11) != null); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. - */ - @Test - public void testGet_4() { - LRUCache squaresCache = new LRUCache<>(5, 10); - for (int i = 1; i <= 10; i++) { - squaresCache.put(i, i * i); - } - squaresCache.setMaxCapacity(20); - squaresCache.get(1); - squaresCache.put(11, 11 * 11); - assertTrue(squaresCache.size() == 11 && squaresCache.get(1) == 1 && squaresCache.get(11) == 121); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#get(java.lang.Object)}. + */ + @Test + public void testGet_4() { + LRUCache squaresCache = new LRUCache<>(5, 10); + for (int i = 1; i <= 10; i++) { + squaresCache.put(i, i * i); + } + squaresCache.setMaxCapacity(20); + squaresCache.get(1); + squaresCache.put(11, 11 * 11); + assertTrue( + squaresCache.size() == 11 && squaresCache.get(1) == 1 && squaresCache.get(11) == 121); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#put(java.lang.Object, java.lang.Object)} - * . - */ - @Test - public void testPut() { - LRUCache squaresCache = new LRUCache<>(5, 10); - squaresCache.put(6, 6 * 6); - assertTrue(squaresCache.get(6) == 36); - } + /** + * Test method for + * {@link com.jmethods.catatumbo.impl.LRUCache#put(java.lang.Object, java.lang.Object)} . + */ + @Test + public void testPut() { + LRUCache squaresCache = new LRUCache<>(5, 10); + squaresCache.put(6, 6 * 6); + assertTrue(squaresCache.get(6) == 36); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#containsKey(java.lang.Object)} - * . - */ - @Test - public void testContainsKey() { - LRUCache squaresCache = new LRUCache<>(5, 10); - squaresCache.put(6, 6 * 6); - assertTrue(squaresCache.containsKey(6)); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#containsKey(java.lang.Object)} . + */ + @Test + public void testContainsKey() { + LRUCache squaresCache = new LRUCache<>(5, 10); + squaresCache.put(6, 6 * 6); + assertTrue(squaresCache.containsKey(6)); + } - /** - * Test method for - * {@link com.jmethods.catatumbo.impl.LRUCache#containsKey(java.lang.Object)} - * . - */ - @Test - public void testContainsKey_2() { - LRUCache squaresCache = new LRUCache<>(5, 10); - squaresCache.put(6, 6 * 6); - assertFalse(squaresCache.containsKey(5)); - } + /** + * Test method for {@link com.jmethods.catatumbo.impl.LRUCache#containsKey(java.lang.Object)} . + */ + @Test + public void testContainsKey_2() { + LRUCache squaresCache = new LRUCache<>(5, 10); + squaresCache.put(6, 6 * 6); + assertFalse(squaresCache.containsKey(5)); + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/MarshallerTest.java b/src/test/java/com/jmethods/catatumbo/impl/MarshallerTest.java index 4c2939c..3de4983 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/MarshallerTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/MarshallerTest.java @@ -42,132 +42,133 @@ */ public class MarshallerTest { - private static DefaultEntityManager em; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = (DefaultEntityManager) TestUtils.getEntityManager(); - } - - @Test - public void testMarshal_Embedded() { - Customer customer = Customer.createSampleCustomer2(); - FullEntity entity = (FullEntity) Marshaller.marshal(em, customer, Intent.INSERT); - assertNull(entity.getString("ba_line1")); - assertNull(entity.getString("ba_line2")); - assertNull(entity.getString("ba_zip")); - assertNull(entity.getString("ba_zipx")); - assertNull(entity.getString("ba_zip")); - } - - @Test - public void testMarshal_Embedded_Imploded() { - Contact contact = Contact.createContact1(); - FullEntity entity = (FullEntity) Marshaller.marshal(em, contact, Intent.INSERT); - assertNull(entity.getValue("cellNumber").get()); - assertNull(entity.getValue("homeAddress").get()); - } - - @Test - public void testMarshal_Embedded_Imploded2() { - Contact contact = Contact.createContact2(); - FullEntity entity = (FullEntity) Marshaller.marshal(em, contact, Intent.INSERT); - assertEquals("55555", entity.getEntity("homeAddress").getEntity("postal_code").getString("zip")); - } - - @Test - public void testMarshal_WrappedLongId1() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample1(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - IncompleteKey incompleteKey = nativeEntity.getKey(); - assertNotNull(incompleteKey); - } - - @Test - public void testMarshal_WrappedLongId2() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample2(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - IncompleteKey incompleteKey = nativeEntity.getKey(); - assertNotNull(incompleteKey); - } - - @Test - public void testMarshal_WrappedLongId3() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = (Key) nativeEntity.getKey(); - assertNotNull(key); - assertEquals(50000L, (long) key.getId()); - } - - @Test - public void testMarshal_WrappedLongObjectId1() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample1(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - IncompleteKey incompleteKey = nativeEntity.getKey(); - assertNotNull(incompleteKey); - } - - @Test - public void testMarshal_WrappedLongObjectId2() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample2(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - IncompleteKey incompleteKey = nativeEntity.getKey(); - assertNotNull(incompleteKey); - } - - @Test - public void testMarshal_WrappedLongObjectId3() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample3(); - FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); - IncompleteKey incompleteKey = nativeEntity.getKey(); - assertNotNull(incompleteKey); - } - - @Test - public void testMarshal_WrappedLongObjectId4() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample4(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = nativeEntity.getKey(); - assertNotNull(key); - assertEquals(entity.getId().getValue(), key.getId()); - } - - @Test - public void testMarshal_WrappedStringId1() { - WrappedStringIdEntity entity = WrappedStringIdEntity.getSample1(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = nativeEntity.getKey(); - assertNotNull(key); - assertTrue(key.hasName()); - } - - @Test - public void testMarshal_WrappedStringId2() { - WrappedStringIdEntity entity = WrappedStringIdEntity.getSample2(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = nativeEntity.getKey(); - assertNotNull(key); - assertTrue(key.hasName()); - } - - @Test - public void testMarshal_WrappedStringId3() { - WrappedStringIdEntity entity = WrappedStringIdEntity.getSample3(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = nativeEntity.getKey(); - assertNotNull(key); - assertTrue(key.hasName()); - } - - @Test - public void testMarshal_WrappedStringId4() { - WrappedStringIdEntity entity = WrappedStringIdEntity.getSample4(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - Key key = nativeEntity.getKey(); - assertNotNull(key); - assertTrue(key.hasName()); - assertEquals(entity.getId().getValue(), key.getName()); - } + private static DefaultEntityManager em; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = (DefaultEntityManager) TestUtils.getEntityManager(); + } + + @Test + public void testMarshal_Embedded() { + Customer customer = Customer.createSampleCustomer2(); + FullEntity entity = (FullEntity) Marshaller.marshal(em, customer, Intent.INSERT); + assertNull(entity.getString("ba_line1")); + assertNull(entity.getString("ba_line2")); + assertNull(entity.getString("ba_zip")); + assertNull(entity.getString("ba_zipx")); + assertNull(entity.getString("ba_zip")); + } + + @Test + public void testMarshal_Embedded_Imploded() { + Contact contact = Contact.createContact1(); + FullEntity entity = (FullEntity) Marshaller.marshal(em, contact, Intent.INSERT); + assertNull(entity.getValue("cellNumber").get()); + assertNull(entity.getValue("homeAddress").get()); + } + + @Test + public void testMarshal_Embedded_Imploded2() { + Contact contact = Contact.createContact2(); + FullEntity entity = (FullEntity) Marshaller.marshal(em, contact, Intent.INSERT); + assertEquals("55555", + entity.getEntity("homeAddress").getEntity("postal_code").getString("zip")); + } + + @Test + public void testMarshal_WrappedLongId1() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample1(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + IncompleteKey incompleteKey = nativeEntity.getKey(); + assertNotNull(incompleteKey); + } + + @Test + public void testMarshal_WrappedLongId2() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample2(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + IncompleteKey incompleteKey = nativeEntity.getKey(); + assertNotNull(incompleteKey); + } + + @Test + public void testMarshal_WrappedLongId3() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = (Key) nativeEntity.getKey(); + assertNotNull(key); + assertEquals(50000L, (long) key.getId()); + } + + @Test + public void testMarshal_WrappedLongObjectId1() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample1(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + IncompleteKey incompleteKey = nativeEntity.getKey(); + assertNotNull(incompleteKey); + } + + @Test + public void testMarshal_WrappedLongObjectId2() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample2(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + IncompleteKey incompleteKey = nativeEntity.getKey(); + assertNotNull(incompleteKey); + } + + @Test + public void testMarshal_WrappedLongObjectId3() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample3(); + FullEntity nativeEntity = (FullEntity) Marshaller.marshal(em, entity, Intent.INSERT); + IncompleteKey incompleteKey = nativeEntity.getKey(); + assertNotNull(incompleteKey); + } + + @Test + public void testMarshal_WrappedLongObjectId4() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample4(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = nativeEntity.getKey(); + assertNotNull(key); + assertEquals(entity.getId().getValue(), key.getId()); + } + + @Test + public void testMarshal_WrappedStringId1() { + WrappedStringIdEntity entity = WrappedStringIdEntity.getSample1(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = nativeEntity.getKey(); + assertNotNull(key); + assertTrue(key.hasName()); + } + + @Test + public void testMarshal_WrappedStringId2() { + WrappedStringIdEntity entity = WrappedStringIdEntity.getSample2(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = nativeEntity.getKey(); + assertNotNull(key); + assertTrue(key.hasName()); + } + + @Test + public void testMarshal_WrappedStringId3() { + WrappedStringIdEntity entity = WrappedStringIdEntity.getSample3(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = nativeEntity.getKey(); + assertNotNull(key); + assertTrue(key.hasName()); + } + + @Test + public void testMarshal_WrappedStringId4() { + WrappedStringIdEntity entity = WrappedStringIdEntity.getSample4(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + Key key = nativeEntity.getKey(); + assertNotNull(key); + assertTrue(key.hasName()); + assertEquals(entity.getId().getValue(), key.getName()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/impl/UnmarshallerTest.java b/src/test/java/com/jmethods/catatumbo/impl/UnmarshallerTest.java index 90c7fda..0827bf3 100644 --- a/src/test/java/com/jmethods/catatumbo/impl/UnmarshallerTest.java +++ b/src/test/java/com/jmethods/catatumbo/impl/UnmarshallerTest.java @@ -36,65 +36,67 @@ * */ public class UnmarshallerTest { - private static DefaultEntityManager em; + private static DefaultEntityManager em; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - em = (DefaultEntityManager) TestUtils.getEntityManager(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + em = (DefaultEntityManager) TestUtils.getEntityManager(); + } - @Test - public void testUnmarshal_StringId() { - StringId entity = new StringId(); - entity.setGreetings("Hello"); - entity.setId("myid"); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - StringId entity2 = Unmarshaller.unmarshal(nativeEntity, StringId.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_StringId() { + StringId entity = new StringId(); + entity.setGreetings("Hello"); + entity.setId("myid"); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + StringId entity2 = Unmarshaller.unmarshal(nativeEntity, StringId.class); + assertTrue(entity.equals(entity2)); + } - @Test - public void testUnmarshal_LongObjectId() { - LongObjectId entity = new LongObjectId(); - entity.setComment("Hello"); - entity.setId(900001L); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - LongObjectId entity2 = Unmarshaller.unmarshal(nativeEntity, LongObjectId.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_LongObjectId() { + LongObjectId entity = new LongObjectId(); + entity.setComment("Hello"); + entity.setId(900001L); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + LongObjectId entity2 = Unmarshaller.unmarshal(nativeEntity, LongObjectId.class); + assertTrue(entity.equals(entity2)); + } - @Test - public void testUnmarshal_LongId() { - LongId entity = new LongId(); - entity.setField1("Hello"); - entity.setId(90000L); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - LongId entity2 = Unmarshaller.unmarshal(nativeEntity, LongId.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_LongId() { + LongId entity = new LongId(); + entity.setField1("Hello"); + entity.setId(90000L); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + LongId entity2 = Unmarshaller.unmarshal(nativeEntity, LongId.class); + assertTrue(entity.equals(entity2)); + } - @Test - public void testUnmarshal_WrappedLongId() { - WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); - WrappedLongIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, WrappedLongIdEntity.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_WrappedLongId() { + WrappedLongIdEntity entity = WrappedLongIdEntity.getSample3(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.INSERT); + WrappedLongIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, WrappedLongIdEntity.class); + assertTrue(entity.equals(entity2)); + } - @Test - public void testUnmarshal_WrappedLongObjectId() { - WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample4(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.UPDATE); - WrappedLongObjectIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, WrappedLongObjectIdEntity.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_WrappedLongObjectId() { + WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample4(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.UPDATE); + WrappedLongObjectIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, + WrappedLongObjectIdEntity.class); + assertTrue(entity.equals(entity2)); + } - @Test - public void testUnmarshal_WrappedStringId() { - WrappedStringIdEntity entity = WrappedStringIdEntity.getSample4(); - Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.UPDATE); - WrappedStringIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, WrappedStringIdEntity.class); - assertTrue(entity.equals(entity2)); - } + @Test + public void testUnmarshal_WrappedStringId() { + WrappedStringIdEntity entity = WrappedStringIdEntity.getSample4(); + Entity nativeEntity = (Entity) Marshaller.marshal(em, entity, Intent.UPDATE); + WrappedStringIdEntity entity2 = Unmarshaller.unmarshal(nativeEntity, + WrappedStringIdEntity.class); + assertTrue(entity.equals(entity2)); + } } diff --git a/src/test/java/com/jmethods/catatumbo/indexers/AllTests.java b/src/test/java/com/jmethods/catatumbo/indexers/AllTests.java index 02a2eb0..c3ae0c3 100644 --- a/src/test/java/com/jmethods/catatumbo/indexers/AllTests.java +++ b/src/test/java/com/jmethods/catatumbo/indexers/AllTests.java @@ -26,7 +26,7 @@ */ @RunWith(Suite.class) @SuiteClasses({ LowerCaseStringIndexerTest.class, LowerCaseStringListIndexerTest.class, - UpperCaseStringIndexerTest.class, UpperCaseStringListIndexerTest.class }) + UpperCaseStringIndexerTest.class, UpperCaseStringListIndexerTest.class }) public class AllTests { } diff --git a/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexerTest.java b/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexerTest.java index 05981dd..9b3f267 100644 --- a/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexerTest.java +++ b/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringIndexerTest.java @@ -39,39 +39,39 @@ */ public class LowerCaseStringIndexerTest { - private static final Logger LOGGER = Logger.getLogger(LowerCaseStringIndexerTest.class.getName()); + private static final Logger LOGGER = Logger.getLogger(LowerCaseStringIndexerTest.class.getName()); - private static LowerCaseStringIndexer indexer; + private static LowerCaseStringIndexer indexer; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - indexer = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + indexer = IndexerFactory.getInstance().getIndexer(LowerCaseStringIndexer.class); + } - @Test - public void testIndex_1() { - Value input = NullValue.of(); - Value output = indexer.index(input); - assertEquals(input, output); - } + @Test + public void testIndex_1() { + Value input = NullValue.of(); + Value output = indexer.index(input); + assertEquals(input, output); + } - @Test - public void testIndex_2() { - StringValue input = StringValue.of("Hello World"); - StringValue output = (StringValue) indexer.index(input); - assertEquals(input.get().toLowerCase(Locale.ENGLISH), output.get()); - assertNotEquals(input.get(), output.get()); - } + @Test + public void testIndex_2() { + StringValue input = StringValue.of("Hello World"); + StringValue output = (StringValue) indexer.index(input); + assertEquals(input.get().toLowerCase(Locale.ENGLISH), output.get()); + assertNotEquals(input.get(), output.get()); + } - @Test(expected = IndexingException.class) - public void testIndex_3() { - LongValue input = LongValue.of(5L); - try { - Value output = indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_3() { + LongValue input = LongValue.of(5L); + try { + Value output = indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexerTest.java b/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexerTest.java index 226f3b9..5dc13b3 100644 --- a/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexerTest.java +++ b/src/test/java/com/jmethods/catatumbo/indexers/LowerCaseStringListIndexerTest.java @@ -41,65 +41,68 @@ */ public class LowerCaseStringListIndexerTest { - private static final Logger LOGGER = Logger.getLogger(LowerCaseStringListIndexerTest.class.getName()); - private static LowerCaseStringListIndexer indexer; + private static final Logger LOGGER = Logger + .getLogger(LowerCaseStringListIndexerTest.class.getName()); + private static LowerCaseStringListIndexer indexer; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - indexer = IndexerFactory.getInstance().getIndexer(LowerCaseStringListIndexer.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + indexer = IndexerFactory.getInstance().getIndexer(LowerCaseStringListIndexer.class); + } - @Test - public void testIndex_1() { - Value input = NullValue.of(); - Value output = indexer.index(input); - assertEquals(input, output); - } + @Test + public void testIndex_1() { + Value input = NullValue.of(); + Value output = indexer.index(input); + assertEquals(input, output); + } - @Test - public void testIndex_2() { - Value[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"), StringValue.of("thRee") }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - ListValue output = (ListValue) indexer.index(input); - List inputList = (List) input.get(); - List outputList = (List) output.get(); - assertEquals(inputList.get(0).get().toLowerCase(Locale.ENGLISH), outputList.get(0).get()); - assertEquals(inputList.get(1).get().toLowerCase(Locale.ENGLISH), outputList.get(1).get()); - assertEquals(inputList.get(2).get().toLowerCase(Locale.ENGLISH), outputList.get(2).get()); - } + @Test + public void testIndex_2() { + Value[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"), + StringValue.of("thRee") }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + ListValue output = (ListValue) indexer.index(input); + List inputList = (List) input.get(); + List outputList = (List) output.get(); + assertEquals(inputList.get(0).get().toLowerCase(Locale.ENGLISH), outputList.get(0).get()); + assertEquals(inputList.get(1).get().toLowerCase(Locale.ENGLISH), outputList.get(1).get()); + assertEquals(inputList.get(2).get().toLowerCase(Locale.ENGLISH), outputList.get(2).get()); + } - @Test - public void testIndex_3() { - Value[] inputArray = { StringValue.of("Hello"), NullValue.of() }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - ListValue output = (ListValue) indexer.index(input); - List inputList = input.get(); - List outputList = output.get(); - assertEquals(((StringValue) inputList.get(0)).get().toLowerCase(Locale.ENGLISH), outputList.get(0).get()); - assertEquals(inputList.get(1).get(), outputList.get(1).get()); - } + @Test + public void testIndex_3() { + Value[] inputArray = { StringValue.of("Hello"), NullValue.of() }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + ListValue output = (ListValue) indexer.index(input); + List inputList = input.get(); + List outputList = output.get(); + assertEquals(((StringValue) inputList.get(0)).get().toLowerCase(Locale.ENGLISH), + outputList.get(0).get()); + assertEquals(inputList.get(1).get(), outputList.get(1).get()); + } - @Test(expected = IndexingException.class) - public void testIndex_4() { - StringValue input = StringValue.of("Hello World"); - try { - Value output = indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_4() { + StringValue input = StringValue.of("Hello World"); + try { + Value output = indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } - @Test(expected = IndexingException.class) - public void testIndex_5() { - Value[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - try { - ListValue output = (ListValue) indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_5() { + Value[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + try { + ListValue output = (ListValue) indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexerTest.java b/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexerTest.java index e98568b..01f4641 100644 --- a/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexerTest.java +++ b/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringIndexerTest.java @@ -39,38 +39,38 @@ */ public class UpperCaseStringIndexerTest { - private static final Logger LOGGER = Logger.getLogger(UpperCaseStringIndexerTest.class.getName()); - private static UpperCaseStringIndexer indexer; + private static final Logger LOGGER = Logger.getLogger(UpperCaseStringIndexerTest.class.getName()); + private static UpperCaseStringIndexer indexer; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - indexer = IndexerFactory.getInstance().getIndexer(UpperCaseStringIndexer.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + indexer = IndexerFactory.getInstance().getIndexer(UpperCaseStringIndexer.class); + } - @Test - public void testIndex_1() { - Value input = NullValue.of(); - Value output = indexer.index(input); - assertEquals(input, output); - } + @Test + public void testIndex_1() { + Value input = NullValue.of(); + Value output = indexer.index(input); + assertEquals(input, output); + } - @Test - public void testIndex_2() { - StringValue input = StringValue.of("Hello World!"); - StringValue output = (StringValue) indexer.index(input); - assertEquals(input.get().toUpperCase(Locale.ENGLISH), output.get()); - assertNotEquals(input.get(), output.get()); - } + @Test + public void testIndex_2() { + StringValue input = StringValue.of("Hello World!"); + StringValue output = (StringValue) indexer.index(input); + assertEquals(input.get().toUpperCase(Locale.ENGLISH), output.get()); + assertNotEquals(input.get(), output.get()); + } - @Test(expected = IndexingException.class) - public void testIndex_3() { - LongValue input = LongValue.of(5L); - try { - Value output = indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_3() { + LongValue input = LongValue.of(5L); + try { + Value output = indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexerTest.java b/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexerTest.java index 4dca662..a93a959 100644 --- a/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexerTest.java +++ b/src/test/java/com/jmethods/catatumbo/indexers/UpperCaseStringListIndexerTest.java @@ -41,65 +41,68 @@ */ public class UpperCaseStringListIndexerTest { - private static final Logger LOGGER = Logger.getLogger(UpperCaseStringListIndexerTest.class.getName()); - private static UpperCaseStringListIndexer indexer; + private static final Logger LOGGER = Logger + .getLogger(UpperCaseStringListIndexerTest.class.getName()); + private static UpperCaseStringListIndexer indexer; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - indexer = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + indexer = IndexerFactory.getInstance().getIndexer(UpperCaseStringListIndexer.class); + } - @Test - public void testIndex_1() { - Value input = NullValue.of(); - Value output = indexer.index(input); - assertEquals(input, output); - } + @Test + public void testIndex_1() { + Value input = NullValue.of(); + Value output = indexer.index(input); + assertEquals(input, output); + } - @Test - public void testIndex_2() { - Value[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"), StringValue.of("thRee") }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - ListValue output = (ListValue) indexer.index(input); - List inputList = (List) input.get(); - List outputList = (List) output.get(); - assertEquals(inputList.get(0).get().toUpperCase(Locale.ENGLISH), outputList.get(0).get()); - assertEquals(inputList.get(1).get().toUpperCase(Locale.ENGLISH), outputList.get(1).get()); - assertEquals(inputList.get(2).get().toUpperCase(Locale.ENGLISH), outputList.get(2).get()); - } + @Test + public void testIndex_2() { + Value[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"), + StringValue.of("thRee") }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + ListValue output = (ListValue) indexer.index(input); + List inputList = (List) input.get(); + List outputList = (List) output.get(); + assertEquals(inputList.get(0).get().toUpperCase(Locale.ENGLISH), outputList.get(0).get()); + assertEquals(inputList.get(1).get().toUpperCase(Locale.ENGLISH), outputList.get(1).get()); + assertEquals(inputList.get(2).get().toUpperCase(Locale.ENGLISH), outputList.get(2).get()); + } - @Test - public void testIndex_3() { - Value[] inputArray = { StringValue.of("Hello"), NullValue.of() }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - ListValue output = (ListValue) indexer.index(input); - List inputList = input.get(); - List outputList = output.get(); - assertEquals(((StringValue) inputList.get(0)).get().toUpperCase(Locale.ENGLISH), outputList.get(0).get()); - assertEquals(inputList.get(1).get(), outputList.get(1).get()); - } + @Test + public void testIndex_3() { + Value[] inputArray = { StringValue.of("Hello"), NullValue.of() }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + ListValue output = (ListValue) indexer.index(input); + List inputList = input.get(); + List outputList = output.get(); + assertEquals(((StringValue) inputList.get(0)).get().toUpperCase(Locale.ENGLISH), + outputList.get(0).get()); + assertEquals(inputList.get(1).get(), outputList.get(1).get()); + } - @Test(expected = IndexingException.class) - public void testIndex_4() { - StringValue input = StringValue.of("Hello World"); - try { - Value output = indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_4() { + StringValue input = StringValue.of("Hello World"); + try { + Value output = indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } - @Test(expected = IndexingException.class) - public void testIndex_5() { - Value[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) }; - ListValue input = ListValue.of(Arrays.asList(inputArray)); - try { - ListValue output = (ListValue) indexer.index(input); - } catch (Exception exp) { - LOGGER.log(Level.INFO, exp.toString()); - throw exp; - } - } + @Test(expected = IndexingException.class) + public void testIndex_5() { + Value[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) }; + ListValue input = ListValue.of(Arrays.asList(inputArray)); + try { + ListValue output = (ListValue) indexer.index(input); + } catch (Exception exp) { + LOGGER.log(Level.INFO, exp.toString()); + throw exp; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/Adder.java b/src/test/java/com/jmethods/catatumbo/listeners/Adder.java index e1645eb..91877ea 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/Adder.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/Adder.java @@ -35,50 +35,50 @@ @EntityListener public class Adder { - @PreInsert - public void beforeInsert(CalculatorEntity entity) { - entity.setSum(entity.getOperand1() + entity.getOperand2()); - } + @PreInsert + public void beforeInsert(CalculatorEntity entity) { + entity.setSum(entity.getOperand1() + entity.getOperand2()); + } - @PreUpdate - public void beforeUpdate(CalculatorEntity entity) { - entity.setSum(entity.getOperand1() + entity.getOperand2()); - } + @PreUpdate + public void beforeUpdate(CalculatorEntity entity) { + entity.setSum(entity.getOperand1() + entity.getOperand2()); + } - @PreUpsert - public void beforeUpsert(CalculatorEntity entity) { - entity.setSum(entity.getOperand1() + entity.getOperand2()); - } + @PreUpsert + public void beforeUpsert(CalculatorEntity entity) { + entity.setSum(entity.getOperand1() + entity.getOperand2()); + } - @PreDelete - public void beforeDelete(CalculatorEntity entity) { - entity.setSum(entity.getOperand1() + entity.getOperand2()); - } + @PreDelete + public void beforeDelete(CalculatorEntity entity) { + entity.setSum(entity.getOperand1() + entity.getOperand2()); + } - @PostInsert - public void afterInsert(CalculatorEntity entity) { - entity.setSum2(entity.getSum() * 2); - } + @PostInsert + public void afterInsert(CalculatorEntity entity) { + entity.setSum2(entity.getSum() * 2); + } - @PostUpdate - public void afterUpdate(CalculatorEntity entity) { - entity.setSum2(entity.getSum() * 3); - } + @PostUpdate + public void afterUpdate(CalculatorEntity entity) { + entity.setSum2(entity.getSum() * 3); + } - @PostUpsert - public void afterUpsert(CalculatorEntity entity) { - entity.setSum2(entity.getSum() * 4); - } + @PostUpsert + public void afterUpsert(CalculatorEntity entity) { + entity.setSum2(entity.getSum() * 4); + } - @PostDelete - public void afterDelete(CalculatorEntity entity) { - entity.setSum2(entity.getSum() * 5); - } + @PostDelete + public void afterDelete(CalculatorEntity entity) { + entity.setSum2(entity.getSum() * 5); + } - @PostLoad - public void afterLoad(CalculatorEntity entity) { - entity.setSum(entity.getOperand1() + entity.getOperand2()); - entity.setSum2(entity.getSum() * 6); - } + @PostLoad + public void afterLoad(CalculatorEntity entity) { + entity.setSum(entity.getOperand1() + entity.getOperand2()); + entity.setSum2(entity.getSum() * 6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/AnimalListener.java b/src/test/java/com/jmethods/catatumbo/listeners/AnimalListener.java index ba5f4d8..c58031c 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/AnimalListener.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/AnimalListener.java @@ -27,14 +27,14 @@ @EntityListener public class AnimalListener { - @PreInsert - public void beforeInsert(Animal animal) { - String value = animal.getValue(); - if (value.trim().length() > 0) { - value += "->"; - } - value += AnimalListener.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - animal.setValue(value); - } + @PreInsert + public void beforeInsert(Animal animal) { + String value = animal.getValue(); + if (value.trim().length() > 0) { + value += "->"; + } + value += AnimalListener.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + animal.setValue(value); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener1.java b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener1.java index ef5f78d..d6673fe 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener1.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener1.java @@ -24,9 +24,9 @@ */ public class BadExternalListener1 { - @PostInsert - public void afterInsert(Object obj) { - System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); - } + @PostInsert + public void afterInsert(Object obj) { + System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener2.java b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener2.java index 2b2a5c1..1d0cf19 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener2.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener2.java @@ -28,24 +28,24 @@ @EntityListener public class BadExternalListener2 { - @PostInsert - public void afterInsert(Object obj) { - System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); - } - - @PostUpdate - public void afterUpdate(Object obj) { - System.out.printf("Object %s of type %s updated\n", obj, obj.getClass().getName()); - } - - @PostDelete - public void afterDelete(Object obj) { - System.out.printf("Object %s of type %s deleted\n", obj, obj.getClass().getName()); - } - - @PostInsert - public void afterInsert2(Object obj) { - System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); - } + @PostInsert + public void afterInsert(Object obj) { + System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); + } + + @PostUpdate + public void afterUpdate(Object obj) { + System.out.printf("Object %s of type %s updated\n", obj, obj.getClass().getName()); + } + + @PostDelete + public void afterDelete(Object obj) { + System.out.printf("Object %s of type %s deleted\n", obj, obj.getClass().getName()); + } + + @PostInsert + public void afterInsert2(Object obj) { + System.out.printf("Object %s of type %s inserted\n", obj, obj.getClass().getName()); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener3.java b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener3.java index 480f0a7..ffb072d 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener3.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadExternalListener3.java @@ -28,11 +28,11 @@ @EntityListener public class BadExternalListener3 { - @PreInsert - @PreUpdate - @PreUpsert - public void beforePersist() { + @PreInsert + @PreUpdate + @PreUpsert + public void beforePersist() { - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener1.java b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener1.java index f3b1986..57b7d8a 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener1.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener1.java @@ -26,9 +26,9 @@ @Entity public class BadInternalListener1 { - @PreInsert - public void beforeInsert(Object obj) { + @PreInsert + public void beforeInsert(Object obj) { - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener2.java b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener2.java index 328ecf1..620789a 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener2.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener2.java @@ -26,9 +26,9 @@ @Entity public class BadInternalListener2 { - @PreInsert - public int beforeInsert() { - return 0; - } + @PreInsert + public int beforeInsert() { + return 0; + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener3.java b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener3.java index eb81c4f..17d0320 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener3.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener3.java @@ -26,8 +26,8 @@ @Entity public class BadInternalListener3 { - @PreInsert - public static void beforeInsert() { - } + @PreInsert + public static void beforeInsert() { + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener4.java b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener4.java index a6268e8..6005d38 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener4.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/BadInternalListener4.java @@ -26,8 +26,8 @@ @Entity public class BadInternalListener4 { - @PreInsert - private void beforeInsert() { - } + @PreInsert + private void beforeInsert() { + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/FarmAnimalListener.java b/src/test/java/com/jmethods/catatumbo/listeners/FarmAnimalListener.java index fb4b1ad..2ba5d19 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/FarmAnimalListener.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/FarmAnimalListener.java @@ -27,14 +27,14 @@ @EntityListener public class FarmAnimalListener { - @PreInsert - public void beforeInsert(FarmAnimal farmAnimal) { - String value = farmAnimal.getValue(); - if (value.trim().length() > 0) { - value += "->"; - } - value += FarmAnimalListener.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); - farmAnimal.setValue(value); - } + @PreInsert + public void beforeInsert(FarmAnimal farmAnimal) { + String value = farmAnimal.getValue(); + if (value.trim().length() > 0) { + value += "->"; + } + value += FarmAnimalListener.class.getSimpleName() + "." + PreInsert.class.getSimpleName(); + farmAnimal.setValue(value); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/GoodExternalListener1.java b/src/test/java/com/jmethods/catatumbo/listeners/GoodExternalListener1.java index 9aa4214..141ccf4 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/GoodExternalListener1.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/GoodExternalListener1.java @@ -28,15 +28,15 @@ @EntityListener public class GoodExternalListener1 { - @PreInsert - @PreUpdate - public void preInsert(Object obj) { + @PreInsert + @PreUpdate + public void preInsert(Object obj) { - } + } - @PostLoad - public void afterLoad(Object entity) { + @PostLoad + public void afterLoad(Object entity) { - } + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/Multiplier.java b/src/test/java/com/jmethods/catatumbo/listeners/Multiplier.java index 9b896b6..0527398 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/Multiplier.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/Multiplier.java @@ -35,50 +35,50 @@ @EntityListener public class Multiplier { - @PreInsert - public void beforeInsert(CalculatorEntity entity) { - entity.setProduct(entity.getOperand1() * entity.getOperand2()); - } + @PreInsert + public void beforeInsert(CalculatorEntity entity) { + entity.setProduct(entity.getOperand1() * entity.getOperand2()); + } - @PreUpdate - public void beforeUpdate(CalculatorEntity entity) { - entity.setProduct(entity.getOperand1() * entity.getOperand2()); - } + @PreUpdate + public void beforeUpdate(CalculatorEntity entity) { + entity.setProduct(entity.getOperand1() * entity.getOperand2()); + } - @PreUpsert - public void beforeUpsert(CalculatorEntity entity) { - entity.setProduct(entity.getOperand1() * entity.getOperand2()); - } + @PreUpsert + public void beforeUpsert(CalculatorEntity entity) { + entity.setProduct(entity.getOperand1() * entity.getOperand2()); + } - @PreDelete - public void beforeDelete(CalculatorEntity entity) { - entity.setProduct(entity.getOperand1() * entity.getOperand2()); - } + @PreDelete + public void beforeDelete(CalculatorEntity entity) { + entity.setProduct(entity.getOperand1() * entity.getOperand2()); + } - @PostInsert - public void afterInsert(CalculatorEntity entity) { - entity.setProduct2(entity.getProduct() * 2); - } + @PostInsert + public void afterInsert(CalculatorEntity entity) { + entity.setProduct2(entity.getProduct() * 2); + } - @PostUpdate - public void afterUpdate(CalculatorEntity entity) { - entity.setProduct2(entity.getProduct() * 3); - } + @PostUpdate + public void afterUpdate(CalculatorEntity entity) { + entity.setProduct2(entity.getProduct() * 3); + } - @PostUpsert - public void afterUpsert(CalculatorEntity entity) { - entity.setProduct2(entity.getProduct() * 4); - } + @PostUpsert + public void afterUpsert(CalculatorEntity entity) { + entity.setProduct2(entity.getProduct() * 4); + } - @PostDelete - public void afterDelete(CalculatorEntity entity) { - entity.setProduct2(entity.getProduct() * 5); - } + @PostDelete + public void afterDelete(CalculatorEntity entity) { + entity.setProduct2(entity.getProduct() * 5); + } - @PostLoad - public void afterLoad(CalculatorEntity entity) { - entity.setProduct(entity.getOperand1() * entity.getOperand2()); - entity.setProduct2(entity.getProduct() * 6); - } + @PostLoad + public void afterLoad(CalculatorEntity entity) { + entity.setProduct(entity.getOperand1() * entity.getOperand2()); + entity.setProduct2(entity.getProduct() * 6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/listeners/Subtractor.java b/src/test/java/com/jmethods/catatumbo/listeners/Subtractor.java index f284df2..9f19fbc 100644 --- a/src/test/java/com/jmethods/catatumbo/listeners/Subtractor.java +++ b/src/test/java/com/jmethods/catatumbo/listeners/Subtractor.java @@ -35,50 +35,50 @@ @EntityListener public class Subtractor { - @PreInsert - public void beforeInsert(CalculatorEntity entity) { - entity.setDifference(entity.getOperand1() - entity.getOperand2()); - } + @PreInsert + public void beforeInsert(CalculatorEntity entity) { + entity.setDifference(entity.getOperand1() - entity.getOperand2()); + } - @PreUpdate - public void beforeUpdate(CalculatorEntity entity) { - entity.setDifference(entity.getOperand1() - entity.getOperand2()); - } + @PreUpdate + public void beforeUpdate(CalculatorEntity entity) { + entity.setDifference(entity.getOperand1() - entity.getOperand2()); + } - @PreUpsert - public void beforeUpsert(CalculatorEntity entity) { - entity.setDifference(entity.getOperand1() - entity.getOperand2()); - } + @PreUpsert + public void beforeUpsert(CalculatorEntity entity) { + entity.setDifference(entity.getOperand1() - entity.getOperand2()); + } - @PreDelete - public void beforeDelete(CalculatorEntity entity) { - entity.setDifference(entity.getOperand1() - entity.getOperand2()); - } + @PreDelete + public void beforeDelete(CalculatorEntity entity) { + entity.setDifference(entity.getOperand1() - entity.getOperand2()); + } - @PostInsert - public void afterInsert(CalculatorEntity entity) { - entity.setDifference2(entity.getDifference() * 2); - } + @PostInsert + public void afterInsert(CalculatorEntity entity) { + entity.setDifference2(entity.getDifference() * 2); + } - @PostUpdate - public void afterUpdate(CalculatorEntity entity) { - entity.setDifference2(entity.getDifference() * 3); - } + @PostUpdate + public void afterUpdate(CalculatorEntity entity) { + entity.setDifference2(entity.getDifference() * 3); + } - @PostUpsert - public void afterUpsert(CalculatorEntity entity) { - entity.setDifference2(entity.getDifference() * 4); - } + @PostUpsert + public void afterUpsert(CalculatorEntity entity) { + entity.setDifference2(entity.getDifference() * 4); + } - @PostDelete - public void afterDelete(CalculatorEntity entity) { - entity.setDifference2(entity.getDifference() * 5); - } + @PostDelete + public void afterDelete(CalculatorEntity entity) { + entity.setDifference2(entity.getDifference() * 5); + } - @PostLoad - public void afterLoad(CalculatorEntity entity) { - entity.setDifference(entity.getOperand1() - entity.getOperand2()); - entity.setDifference2(entity.getDifference() * 6); - } + @PostLoad + public void afterLoad(CalculatorEntity entity) { + entity.setDifference(entity.getOperand1() - entity.getOperand2()); + entity.setDifference2(entity.getDifference() * 6); + } } diff --git a/src/test/java/com/jmethods/catatumbo/mappers/AllTests.java b/src/test/java/com/jmethods/catatumbo/mappers/AllTests.java index b88d4bb..a202749 100644 --- a/src/test/java/com/jmethods/catatumbo/mappers/AllTests.java +++ b/src/test/java/com/jmethods/catatumbo/mappers/AllTests.java @@ -26,7 +26,7 @@ */ @RunWith(Suite.class) @SuiteClasses({ DecimalMapperTest.class, FloatMapperTest.class, OffsetDateTimeMapperTest.class, - ZonedDateTimeMapperTest.class }) + ZonedDateTimeMapperTest.class }) public class AllTests { } diff --git a/src/test/java/com/jmethods/catatumbo/mappers/DecimalMapperTest.java b/src/test/java/com/jmethods/catatumbo/mappers/DecimalMapperTest.java index 17d3e4b..0bdec1f 100644 --- a/src/test/java/com/jmethods/catatumbo/mappers/DecimalMapperTest.java +++ b/src/test/java/com/jmethods/catatumbo/mappers/DecimalMapperTest.java @@ -16,7 +16,8 @@ package com.jmethods.catatumbo.mappers; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.math.BigDecimal; @@ -32,249 +33,249 @@ */ public class DecimalMapperTest { - @Test(expected = IllegalArgumentException.class) - public void testConstructor1() { - try { - DecimalMapper mapper = new DecimalMapper(5, 7); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructor2() { - try { - DecimalMapper mapper = new DecimalMapper(0, 0); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructor3() { - try { - DecimalMapper mapper = new DecimalMapper(20, 2); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructor4() { - try { - DecimalMapper mapper = new DecimalMapper(-1, 0); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructor5() { - try { - DecimalMapper mapper = new DecimalMapper(5, -2); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test - public void testConstructor6() { - DecimalMapper mapper = new DecimalMapper(1, 0); - assertEquals(1, mapper.getPrecision()); - assertEquals(0, mapper.getScale()); - } - - @Test - public void testConstructor7() { - DecimalMapper mapper = new DecimalMapper(10, 5); - assertEquals(10, mapper.getPrecision()); - assertEquals(5, mapper.getScale()); - } - - @Test - public void testConstructor8() { - DecimalMapper mapper = new DecimalMapper(18, 18); - assertEquals(18, mapper.getPrecision()); - assertEquals(18, mapper.getScale()); - } - - @Test - public void testConstructor9() { - DecimalMapper mapper = new DecimalMapper(18, 0); - assertEquals(18, mapper.getPrecision()); - assertEquals(0, mapper.getScale()); - } - - @Test - public void testToDatastore1() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("9999.99")).build(); - assertTrue(value instanceof LongValue); - assertEquals(999999L, value.get()); - } - - @Test - public void testToDatastore2() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("0")).build(); - assertTrue(value instanceof LongValue); - assertEquals(0L, value.get()); - } - - @Test - public void testToDatastore3() { - DecimalMapper mapper = new DecimalMapper(18, 6); - Value value = mapper.toDatastore(new BigDecimal("123456789012.123456")).build(); - assertTrue(value instanceof LongValue); - assertEquals(123456789012123456L, value.get()); - } - - @Test - public void testToDatastore4() { - DecimalMapper mapper = new DecimalMapper(18, 6); - Value value = mapper.toDatastore(new BigDecimal("-123456789012.123456")).build(); - assertTrue(value instanceof LongValue); - assertEquals(-123456789012123456L, value.get()); - } - - @Test - public void testToDatastore6() { - DecimalMapper mapper = new DecimalMapper(1, 0); - Value value = mapper.toDatastore(new BigDecimal("9")).build(); - assertEquals(9L, value.get()); - } - - @Test - public void testToDatastore7() { - DecimalMapper mapper = new DecimalMapper(1, 1); - Value value = mapper.toDatastore(new BigDecimal("0.5")).build(); - assertTrue(value instanceof LongValue); - assertEquals(5L, value.get()); - } - - @Test - public void testToDatastore8() { - DecimalMapper mapper = new DecimalMapper(1, 1); - Value value = mapper.toDatastore(new BigDecimal("0.500")).build(); - assertEquals(5L, value.get()); - } - - @Test - public void testToDatastore9() { - DecimalMapper mapper = new DecimalMapper(18, 18); - Value value = mapper.toDatastore(new BigDecimal("0.000000000000000565")).build(); - assertTrue(value instanceof LongValue); - assertEquals(565L, value.get()); - } - - @Test - public void testToDatastore10() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("0.1")).build(); - assertTrue(value instanceof LongValue); - assertEquals(10L, value.get()); - } - - @Test - public void testToDatastore11() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("0.10")).build(); - assertTrue(value instanceof LongValue); - assertEquals(10L, value.get()); - } - - @Test - public void testToDatastore12() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("0.0")).build(); - assertTrue(value instanceof LongValue); - assertEquals(0L, value.get()); - } - - @Test - public void testToDatastore13() { - DecimalMapper mapper = new DecimalMapper(6, 2); - Value value = mapper.toDatastore(new BigDecimal("0.01")).build(); - assertTrue(value instanceof LongValue); - assertEquals(1L, value.get()); - } - - @Test(expected = MappingException.class) - public void testToDatastore14() { - try { - DecimalMapper mapper = new DecimalMapper(5, 2); - Value value = mapper.toDatastore(new BigDecimal("1234.5")).build(); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = MappingException.class) - public void testToDatastore15() { - try { - DecimalMapper mapper = new DecimalMapper(5, 2); - Value value = mapper.toDatastore(new BigDecimal("1.234")).build(); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test - public void testToModel1() { - DecimalMapper mapper = new DecimalMapper(6, 2); - LongValue input = LongValue.of(999999L); - BigDecimal output = (BigDecimal) mapper.toModel(input); - assertEquals(new BigDecimal("9999.99"), output); - - } - - @Test - public void testToModel2() { - DecimalMapper mapper = new DecimalMapper(6, 2); - LongValue input = LongValue.of(0); - BigDecimal output = (BigDecimal) mapper.toModel(input); - assertEquals(new BigDecimal("0.00"), output); - } - - @Test - public void testToModel3() { - DecimalMapper mapper = new DecimalMapper(18, 18); - LongValue input = LongValue.of(999999999999999999L); - BigDecimal output = (BigDecimal) mapper.toModel(input); - assertEquals(new BigDecimal("0.999999999999999999"), output); - } - - @Test(expected = MappingException.class) - public void testToModel4() { - try { - DecimalMapper mapper = new DecimalMapper(5, 2); - LongValue input = LongValue.of(123456); - BigDecimal output = (BigDecimal) mapper.toModel(input); - assertEquals(new BigDecimal("123.456"), output); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test - public void testToModel5() { - try { - DecimalMapper mapper = new DecimalMapper(5, 2); - LongValue input = LongValue.of(12345L); - BigDecimal output = (BigDecimal) mapper.toModel(input); - assertEquals(new BigDecimal("123.45"), output); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } + @Test(expected = IllegalArgumentException.class) + public void testConstructor1() { + try { + DecimalMapper mapper = new DecimalMapper(5, 7); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructor2() { + try { + DecimalMapper mapper = new DecimalMapper(0, 0); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructor3() { + try { + DecimalMapper mapper = new DecimalMapper(20, 2); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructor4() { + try { + DecimalMapper mapper = new DecimalMapper(-1, 0); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructor5() { + try { + DecimalMapper mapper = new DecimalMapper(5, -2); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test + public void testConstructor6() { + DecimalMapper mapper = new DecimalMapper(1, 0); + assertEquals(1, mapper.getPrecision()); + assertEquals(0, mapper.getScale()); + } + + @Test + public void testConstructor7() { + DecimalMapper mapper = new DecimalMapper(10, 5); + assertEquals(10, mapper.getPrecision()); + assertEquals(5, mapper.getScale()); + } + + @Test + public void testConstructor8() { + DecimalMapper mapper = new DecimalMapper(18, 18); + assertEquals(18, mapper.getPrecision()); + assertEquals(18, mapper.getScale()); + } + + @Test + public void testConstructor9() { + DecimalMapper mapper = new DecimalMapper(18, 0); + assertEquals(18, mapper.getPrecision()); + assertEquals(0, mapper.getScale()); + } + + @Test + public void testToDatastore1() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("9999.99")).build(); + assertTrue(value instanceof LongValue); + assertEquals(999999L, value.get()); + } + + @Test + public void testToDatastore2() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("0")).build(); + assertTrue(value instanceof LongValue); + assertEquals(0L, value.get()); + } + + @Test + public void testToDatastore3() { + DecimalMapper mapper = new DecimalMapper(18, 6); + Value value = mapper.toDatastore(new BigDecimal("123456789012.123456")).build(); + assertTrue(value instanceof LongValue); + assertEquals(123456789012123456L, value.get()); + } + + @Test + public void testToDatastore4() { + DecimalMapper mapper = new DecimalMapper(18, 6); + Value value = mapper.toDatastore(new BigDecimal("-123456789012.123456")).build(); + assertTrue(value instanceof LongValue); + assertEquals(-123456789012123456L, value.get()); + } + + @Test + public void testToDatastore6() { + DecimalMapper mapper = new DecimalMapper(1, 0); + Value value = mapper.toDatastore(new BigDecimal("9")).build(); + assertEquals(9L, value.get()); + } + + @Test + public void testToDatastore7() { + DecimalMapper mapper = new DecimalMapper(1, 1); + Value value = mapper.toDatastore(new BigDecimal("0.5")).build(); + assertTrue(value instanceof LongValue); + assertEquals(5L, value.get()); + } + + @Test + public void testToDatastore8() { + DecimalMapper mapper = new DecimalMapper(1, 1); + Value value = mapper.toDatastore(new BigDecimal("0.500")).build(); + assertEquals(5L, value.get()); + } + + @Test + public void testToDatastore9() { + DecimalMapper mapper = new DecimalMapper(18, 18); + Value value = mapper.toDatastore(new BigDecimal("0.000000000000000565")).build(); + assertTrue(value instanceof LongValue); + assertEquals(565L, value.get()); + } + + @Test + public void testToDatastore10() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("0.1")).build(); + assertTrue(value instanceof LongValue); + assertEquals(10L, value.get()); + } + + @Test + public void testToDatastore11() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("0.10")).build(); + assertTrue(value instanceof LongValue); + assertEquals(10L, value.get()); + } + + @Test + public void testToDatastore12() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("0.0")).build(); + assertTrue(value instanceof LongValue); + assertEquals(0L, value.get()); + } + + @Test + public void testToDatastore13() { + DecimalMapper mapper = new DecimalMapper(6, 2); + Value value = mapper.toDatastore(new BigDecimal("0.01")).build(); + assertTrue(value instanceof LongValue); + assertEquals(1L, value.get()); + } + + @Test(expected = MappingException.class) + public void testToDatastore14() { + try { + DecimalMapper mapper = new DecimalMapper(5, 2); + Value value = mapper.toDatastore(new BigDecimal("1234.5")).build(); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = MappingException.class) + public void testToDatastore15() { + try { + DecimalMapper mapper = new DecimalMapper(5, 2); + Value value = mapper.toDatastore(new BigDecimal("1.234")).build(); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test + public void testToModel1() { + DecimalMapper mapper = new DecimalMapper(6, 2); + LongValue input = LongValue.of(999999L); + BigDecimal output = (BigDecimal) mapper.toModel(input); + assertEquals(new BigDecimal("9999.99"), output); + + } + + @Test + public void testToModel2() { + DecimalMapper mapper = new DecimalMapper(6, 2); + LongValue input = LongValue.of(0); + BigDecimal output = (BigDecimal) mapper.toModel(input); + assertEquals(new BigDecimal("0.00"), output); + } + + @Test + public void testToModel3() { + DecimalMapper mapper = new DecimalMapper(18, 18); + LongValue input = LongValue.of(999999999999999999L); + BigDecimal output = (BigDecimal) mapper.toModel(input); + assertEquals(new BigDecimal("0.999999999999999999"), output); + } + + @Test(expected = MappingException.class) + public void testToModel4() { + try { + DecimalMapper mapper = new DecimalMapper(5, 2); + LongValue input = LongValue.of(123456); + BigDecimal output = (BigDecimal) mapper.toModel(input); + assertEquals(new BigDecimal("123.456"), output); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test + public void testToModel5() { + try { + DecimalMapper mapper = new DecimalMapper(5, 2); + LongValue input = LongValue.of(12345L); + BigDecimal output = (BigDecimal) mapper.toModel(input); + assertEquals(new BigDecimal("123.45"), output); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/mappers/FloatMapperTest.java b/src/test/java/com/jmethods/catatumbo/mappers/FloatMapperTest.java index bd8de34..f257f4b 100644 --- a/src/test/java/com/jmethods/catatumbo/mappers/FloatMapperTest.java +++ b/src/test/java/com/jmethods/catatumbo/mappers/FloatMapperTest.java @@ -16,7 +16,8 @@ package com.jmethods.catatumbo.mappers; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -31,178 +32,178 @@ */ public class FloatMapperTest { - @Test - public void testToModel_1() { - double d = 0.000000; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(0.000000f == output); - } - - @Test - public void testToModel_2() { - double d = 3.1415927; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(3.1415927f == output); - } - - @Test - public void testToModel_3() { - double d = Float.MAX_VALUE; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(Float.MAX_VALUE == output); - } - - @Test - public void testToModel_4() { - double d = -Float.MAX_VALUE; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(-Float.MAX_VALUE == output); - } - - @Test(expected = MappingException.class) - public void testToModel_5() { - double d = Float.MAX_VALUE * 2d; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - try { - float output = (float) mapper.toModel(input); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test(expected = MappingException.class) - public void testToModel_6() { - double d = -Float.MAX_VALUE * 2d; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - try { - float output = (float) mapper.toModel(input); - } catch (Exception e) { - System.err.println(e); - throw e; - } - } - - @Test - public void testToModel_7() { - double d = 1.0000; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(1.0000f == output); - } - - @Test - public void testToModel_8() { - double d = 999.9999; - DoubleValue input = DoubleValue.of(d); - FloatMapper mapper = new FloatMapper(); - float output = (float) mapper.toModel(input); - System.out.printf("%s ---> %s%n", d, output); - assertTrue(999.9999f == output); - } - - @Test - public void testToModel_9() { - FloatMapper mapper = new FloatMapper(); - Object output = mapper.toModel(NullValue.of()); - assertNull(output); - } - - @Test - public void testToDatastore_1() { - float f = 0.0f; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_2() { - float f = 1.00000f; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_3() { - float f = -1.00000f; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_4() { - float f = 3.1415927f; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_5() { - float f = 1f / 3f; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_6() { - float f = Float.MAX_VALUE; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_7() { - float f = -Float.MAX_VALUE; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_8() { - float f = Float.MIN_VALUE; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } - - @Test - public void testToDatastore_9() { - float f = -Float.MIN_VALUE; - FloatMapper mapper = new FloatMapper(); - Value output = mapper.toDatastore(f).build(); - System.out.printf("%s ---> %s%n", f, output.get()); - assertTrue(Double.valueOf(f).equals(output.get())); - } + @Test + public void testToModel_1() { + double d = 0.000000; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(0.000000f == output); + } + + @Test + public void testToModel_2() { + double d = 3.1415927; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(3.1415927f == output); + } + + @Test + public void testToModel_3() { + double d = Float.MAX_VALUE; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(Float.MAX_VALUE == output); + } + + @Test + public void testToModel_4() { + double d = -Float.MAX_VALUE; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(-Float.MAX_VALUE == output); + } + + @Test(expected = MappingException.class) + public void testToModel_5() { + double d = Float.MAX_VALUE * 2d; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + try { + float output = (float) mapper.toModel(input); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test(expected = MappingException.class) + public void testToModel_6() { + double d = -Float.MAX_VALUE * 2d; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + try { + float output = (float) mapper.toModel(input); + } catch (Exception e) { + System.err.println(e); + throw e; + } + } + + @Test + public void testToModel_7() { + double d = 1.0000; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(1.0000f == output); + } + + @Test + public void testToModel_8() { + double d = 999.9999; + DoubleValue input = DoubleValue.of(d); + FloatMapper mapper = new FloatMapper(); + float output = (float) mapper.toModel(input); + System.out.printf("%s ---> %s%n", d, output); + assertTrue(999.9999f == output); + } + + @Test + public void testToModel_9() { + FloatMapper mapper = new FloatMapper(); + Object output = mapper.toModel(NullValue.of()); + assertNull(output); + } + + @Test + public void testToDatastore_1() { + float f = 0.0f; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_2() { + float f = 1.00000f; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_3() { + float f = -1.00000f; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_4() { + float f = 3.1415927f; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_5() { + float f = 1f / 3f; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_6() { + float f = Float.MAX_VALUE; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_7() { + float f = -Float.MAX_VALUE; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_8() { + float f = Float.MIN_VALUE; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } + + @Test + public void testToDatastore_9() { + float f = -Float.MIN_VALUE; + FloatMapper mapper = new FloatMapper(); + Value output = mapper.toDatastore(f).build(); + System.out.printf("%s ---> %s%n", f, output.get()); + assertTrue(Double.valueOf(f).equals(output.get())); + } } diff --git a/src/test/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapperTest.java b/src/test/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapperTest.java index d8a9eb2..0a7034a 100644 --- a/src/test/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapperTest.java +++ b/src/test/java/com/jmethods/catatumbo/mappers/OffsetDateTimeMapperTest.java @@ -38,57 +38,58 @@ */ public class OffsetDateTimeMapperTest { - @Test - public void testToDatastore_Now() { - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - OffsetDateTime now = OffsetDateTime.now(); - Timestamp ts = ((TimestampValue) mapper.toDatastore(now).build()).get(); - assertEquals(now.toEpochSecond(), ts.getSeconds()); - assertEquals(now.getNano(), ts.getNanos()); - } + @Test + public void testToDatastore_Now() { + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + OffsetDateTime now = OffsetDateTime.now(); + Timestamp ts = ((TimestampValue) mapper.toDatastore(now).build()).get(); + assertEquals(now.toEpochSecond(), ts.getSeconds()); + assertEquals(now.getNano(), ts.getNanos()); + } - @Test - public void testToDatastorel_Nanos() { - OffsetDateTime input = OffsetDateTime.now().withNano(999999999); - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - Timestamp ts = ((TimestampValue) mapper.toDatastore(input).build()).get(); - assertEquals(ts.getSeconds(), input.toEpochSecond()); - assertEquals(TimeUnit.NANOSECONDS.toMicros(input.getNano()), TimeUnit.NANOSECONDS.toMicros(ts.getNanos())); - } + @Test + public void testToDatastorel_Nanos() { + OffsetDateTime input = OffsetDateTime.now().withNano(999999999); + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + Timestamp ts = ((TimestampValue) mapper.toDatastore(input).build()).get(); + assertEquals(ts.getSeconds(), input.toEpochSecond()); + assertEquals(TimeUnit.NANOSECONDS.toMicros(input.getNano()), + TimeUnit.NANOSECONDS.toMicros(ts.getNanos())); + } - @Test - public void testToDatastore_Null() { - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - NullValue v = (NullValue) mapper.toDatastore(null).build(); - assertNull(v.get()); - } + @Test + public void testToDatastore_Null() { + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + NullValue v = (NullValue) mapper.toDatastore(null).build(); + assertNull(v.get()); + } - @Test - public void testToModel_Now() { - Calendar now = Calendar.getInstance(); - TimestampValue v = TimestampValue.newBuilder(Timestamp.of(now.getTime())).build(); - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - OffsetDateTime output = (OffsetDateTime) mapper.toModel(v); - assertTrue(now.getTimeInMillis() == output.toInstant().toEpochMilli()); - } + @Test + public void testToModel_Now() { + Calendar now = Calendar.getInstance(); + TimestampValue v = TimestampValue.newBuilder(Timestamp.of(now.getTime())).build(); + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + OffsetDateTime output = (OffsetDateTime) mapper.toModel(v); + assertTrue(now.getTimeInMillis() == output.toInstant().toEpochMilli()); + } - @Test - public void testToModel_Null() { - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - OffsetDateTime output = (OffsetDateTime) mapper.toModel(NullValue.of()); - assertNull(output); - } + @Test + public void testToModel_Null() { + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + OffsetDateTime output = (OffsetDateTime) mapper.toModel(NullValue.of()); + assertNull(output); + } - @Test(expected = MappingException.class) - public void testToModel2() { - StringValue v = StringValue.of("Hello"); - OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); - try { - mapper.toModel(v); - } catch (MappingException e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = MappingException.class) + public void testToModel2() { + StringValue v = StringValue.of("Hello"); + OffsetDateTimeMapper mapper = new OffsetDateTimeMapper(); + try { + mapper.toModel(v); + } catch (MappingException e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/src/test/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapperTest.java b/src/test/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapperTest.java index ebd8d1c..6cb4a3b 100644 --- a/src/test/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapperTest.java +++ b/src/test/java/com/jmethods/catatumbo/mappers/ZonedDateTimeMapperTest.java @@ -36,58 +36,59 @@ */ public class ZonedDateTimeMapperTest { - @Test - public void testToDatastore_Now() { - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - ZonedDateTime now = ZonedDateTime.now(); - Timestamp ts = ((TimestampValue) mapper.toDatastore(now).build()).get(); - assertEquals(now.toEpochSecond(), ts.getSeconds()); - assertEquals(now.getNano(), ts.getNanos()); - } + @Test + public void testToDatastore_Now() { + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + ZonedDateTime now = ZonedDateTime.now(); + Timestamp ts = ((TimestampValue) mapper.toDatastore(now).build()).get(); + assertEquals(now.toEpochSecond(), ts.getSeconds()); + assertEquals(now.getNano(), ts.getNanos()); + } - @Test - public void testToDatastorel_Nanos() { - ZonedDateTime input = ZonedDateTime.now().withNano(999999999); - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - Timestamp ts = ((TimestampValue) mapper.toDatastore(input).build()).get(); - assertEquals(ts.getSeconds(), input.toEpochSecond()); - assertEquals(TimeUnit.NANOSECONDS.toMicros(input.getNano()), TimeUnit.NANOSECONDS.toMicros(ts.getNanos())); - } + @Test + public void testToDatastorel_Nanos() { + ZonedDateTime input = ZonedDateTime.now().withNano(999999999); + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + Timestamp ts = ((TimestampValue) mapper.toDatastore(input).build()).get(); + assertEquals(ts.getSeconds(), input.toEpochSecond()); + assertEquals(TimeUnit.NANOSECONDS.toMicros(input.getNano()), + TimeUnit.NANOSECONDS.toMicros(ts.getNanos())); + } - @Test - public void testToDatastore_Null() { - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - NullValue v = (NullValue) mapper.toDatastore(null).build(); - assertNull(v.get()); - } + @Test + public void testToDatastore_Null() { + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + NullValue v = (NullValue) mapper.toDatastore(null).build(); + assertNull(v.get()); + } - @Test - public void testToModel_Now() { - Timestamp now = Timestamp.now(); - TimestampValue v = TimestampValue.newBuilder(now).build(); - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - ZonedDateTime output = (ZonedDateTime) mapper.toModel(v); - assertEquals(now.getSeconds(), output.toEpochSecond()); - assertEquals(now.getNanos(), output.getNano()); - } + @Test + public void testToModel_Now() { + Timestamp now = Timestamp.now(); + TimestampValue v = TimestampValue.newBuilder(now).build(); + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + ZonedDateTime output = (ZonedDateTime) mapper.toModel(v); + assertEquals(now.getSeconds(), output.toEpochSecond()); + assertEquals(now.getNanos(), output.getNano()); + } - @Test - public void testToModel_Null() { - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - ZonedDateTime output = (ZonedDateTime) mapper.toModel(NullValue.of()); - assertNull(output); - } + @Test + public void testToModel_Null() { + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + ZonedDateTime output = (ZonedDateTime) mapper.toModel(NullValue.of()); + assertNull(output); + } - @Test(expected = MappingException.class) - public void testToModel2() { - StringValue v = StringValue.of("Hello"); - ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); - try { - mapper.toModel(v); - } catch (MappingException e) { - e.printStackTrace(); - throw e; - } - } + @Test(expected = MappingException.class) + public void testToModel2() { + StringValue v = StringValue.of("Hello"); + ZonedDateTimeMapper mapper = new ZonedDateTimeMapper(); + try { + mapper.toModel(v); + } catch (MappingException e) { + e.printStackTrace(); + throw e; + } + } }