From 9f702948784b07139ef51795fb66913f0511f403 Mon Sep 17 00:00:00 2001 From: Marvin Froeder Date: Wed, 14 Feb 2024 09:06:05 +1300 Subject: [PATCH] Formatted sources and poms java -jar ~/Downloads/google-java-format-1.18.1-all-deps.jar -i $(find . -type f -name "*.java" | grep ".*/src/.*java") mvn com.github.ekryd.sortpom:sortpom-maven-plugin:3.3.0:sort -Dsort.predefinedSortOrder=recommended_2008_06 -Dsort.createBackupFile=false -Pall --- pom.xml | 350 +- querydsl-ant-test/src/test/Test.java | 9 +- querydsl-apt/pom.xml | 58 +- .../java/com/querydsl/apt/APTOptions.java | 150 +- .../apt/AbstractQuerydslProcessor.java | 1019 ++-- .../java/com/querydsl/apt/Configuration.java | 98 +- .../main/java/com/querydsl/apt/Context.java | 42 +- .../querydsl/apt/DefaultConfiguration.java | 1101 ++-- .../com/querydsl/apt/ExtendedTypeFactory.java | 987 ++-- .../java/com/querydsl/apt/QueryTypeImpl.java | 29 +- .../apt/QuerydslAnnotationProcessor.java | 41 +- .../apt/SimpleTypeVisitorAdapter.java | 61 +- .../com/querydsl/apt/TypeElementHandler.java | 312 +- .../java/com/querydsl/apt/TypeExtractor.java | 168 +- .../main/java/com/querydsl/apt/TypeUtils.java | 99 +- .../java/com/querydsl/apt/VisitorConfig.java | 83 +- .../HibernateAnnotationProcessor.java | 44 +- .../apt/hibernate/HibernateConfiguration.java | 52 +- .../querydsl/apt/hibernate/package-info.java | 4 +- .../apt/jdo/JDOAnnotationProcessor.java | 37 +- .../querydsl/apt/jdo/JDOConfiguration.java | 109 +- .../com/querydsl/apt/jdo/package-info.java | 4 +- .../apt/jpa/JPAAnnotationProcessor.java | 38 +- .../querydsl/apt/jpa/JPAConfiguration.java | 252 +- .../com/querydsl/apt/jpa/package-info.java | 4 +- .../morphia/MorphiaAnnotationProcessor.java | 65 +- .../querydsl/apt/morphia/package-info.java | 4 +- .../java/com/querydsl/apt/package-info.java | 4 +- .../apt/roo/RooAnnotationProcessor.java | 44 +- .../com/querydsl/apt/roo/package-info.java | 4 +- .../apt/com/querydsl/BooleanExtensions.java | 17 +- .../apt/com/querydsl/BooleanExtensions2.java | 17 +- .../test/apt/com/querydsl/ExampleEntity.java | 7 +- .../test/apt/com/querydsl/ExampleEntity2.java | 2 +- .../apt/com/querydsl/InnerExtensions.java | 10 +- .../apt/com/querydsl/IntegerExtensions.java | 9 +- .../com/querydsl/eclipse/SimpleEntity.java | 73 +- querydsl-apt/src/test/java/Entity.java | 5 +- .../querydsl/apt/AbstractProcessorTest.java | 104 +- .../querydsl/apt/BooleanExtensionsTest.java | 55 +- .../java/com/querydsl/apt/DateExtensions.java | 14 +- .../com/querydsl/apt/DateExtensionsTest.java | 67 +- .../querydsl/apt/EclipseCompilationTest.java | 101 +- .../java/com/querydsl/apt/EmbeddableTest.java | 13 +- .../com/querydsl/apt/EntityExtensions.java | 11 +- .../querydsl/apt/EntityExtensionsTest.java | 70 +- .../querydsl/apt/EntityWithExtensions.java | 8 +- .../com/querydsl/apt/ExcludedClassesTest.java | 27 +- .../querydsl/apt/ExcludedPackagesTest.java | 26 +- .../com/querydsl/apt/GenericExporterTest.java | 284 +- .../java/com/querydsl/apt/GenericTest.java | 27 +- .../com/querydsl/apt/IncludedClassesTest.java | 37 +- .../querydsl/apt/IncludedPackagesTest.java | 26 +- .../apt/IncrementalCompilationTest.java | 58 +- .../querydsl/apt/IntegerExtensionsTest.java | 32 +- .../java/com/querydsl/apt/NamePrefixTest.java | 29 +- .../java/com/querydsl/apt/NameSuffixTest.java | 30 +- .../test/java/com/querydsl/apt/NoteTest.java | 92 +- .../com/querydsl/apt/PackageSuffixTest.java | 30 +- .../apt/QuerydslAnnotationProcessorTest.java | 281 +- .../querydsl/apt/UnknownAsEmbeddableTest.java | 44 +- .../apt/domain/AbstractClasses2Test.java | 120 +- .../apt/domain/AbstractClassesTest.java | 99 +- .../apt/domain/AbstractEntityTest.java | 35 +- .../apt/domain/AbstractProperties2Test.java | 97 +- .../apt/domain/AbstractProperties3Test.java | 103 +- .../apt/domain/AbstractPropertiesTest.java | 40 +- .../apt/domain/AbstractSecurable.java | 15 +- .../com/querydsl/apt/domain/AbstractTest.java | 72 +- .../java/com/querydsl/apt/domain/Address.java | 22 +- .../com/querydsl/apt/domain/AnimalTest.java | 35 +- .../apt/domain/AnnotatedGettersTest.java | 20 +- .../apt/domain/AnnotationTypeTest.java | 27 +- .../com/querydsl/apt/domain/AnyPathTest.java | 69 +- .../com/querydsl/apt/domain/AnyUsageTest.java | 121 +- .../com/querydsl/apt/domain/Array2Test.java | 24 +- .../com/querydsl/apt/domain/Array3Test.java | 56 +- .../com/querydsl/apt/domain/ArrayExtTest.java | 85 +- .../com/querydsl/apt/domain/ArrayTest.java | 28 +- .../test/java/com/querydsl/apt/domain/B.java | 4 +- .../com/querydsl/apt/domain/BlockingTest.java | 49 +- .../java/com/querydsl/apt/domain/City.java | 20 +- .../querydsl/apt/domain/CollectionTest.java | 95 +- .../querydsl/apt/domain/ComparableTest.java | 66 +- .../querydsl/apt/domain/ConstructorTest.java | 52 +- .../querydsl/apt/domain/CustomCollection.java | 54 +- .../querydsl/apt/domain/CustomMethods.java | 4 +- .../apt/domain/DeepInitializationTest.java | 141 +- .../querydsl/apt/domain/Delegate2Test.java | 35 +- .../querydsl/apt/domain/Delegate3Test.java | 43 +- .../com/querydsl/apt/domain/DelegateTest.java | 138 +- .../querydsl/apt/domain/Embeddable2Test.java | 57 +- .../querydsl/apt/domain/Embeddable3Test.java | 41 +- .../apt/domain/EmbeddableDeepTest.java | 120 +- .../apt/domain/EmbeddableInterfaceTest.java | 61 +- .../querydsl/apt/domain/EmbeddableTest.java | 74 +- .../querydsl/apt/domain/Embedded2Test.java | 87 +- .../com/querydsl/apt/domain/EmbeddedTest.java | 51 +- .../apt/domain/EntityInheritanceTest.java | 34 +- .../com/querydsl/apt/domain/EntityTest.java | 170 +- .../com/querydsl/apt/domain/Enum2Test.java | 25 +- .../com/querydsl/apt/domain/Enum3Test.java | 89 +- .../com/querydsl/apt/domain/Enum4Test.java | 84 +- .../com/querydsl/apt/domain/EnumTest.java | 56 +- .../querydsl/apt/domain/ExampleEntity.java | 3 +- .../com/querydsl/apt/domain/Examples.java | 84 +- .../apt/domain/ExcludedClassTest.java | 28 +- .../com/querydsl/apt/domain/Expression.java | 4 +- .../querydsl/apt/domain/ExpressionTest.java | 190 +- .../apt/domain/ExtendsAndSuperTest.java | 83 +- .../apt/domain/ExternalEmbeddableTest.java | 15 +- .../apt/domain/ExternalEntityTest.java | 18 +- .../querydsl/apt/domain/FileAttachment.java | 62 +- .../querydsl/apt/domain/Generic10Test.java | 60 +- .../querydsl/apt/domain/Generic11Test.java | 35 +- .../querydsl/apt/domain/Generic12Test.java | 105 +- .../querydsl/apt/domain/Generic13Test.java | 47 +- .../querydsl/apt/domain/Generic14Test.java | 85 +- .../querydsl/apt/domain/Generic15Test.java | 43 +- .../querydsl/apt/domain/Generic16Test.java | 50 +- .../com/querydsl/apt/domain/Generic2Test.java | 69 +- .../com/querydsl/apt/domain/Generic3Test.java | 40 +- .../com/querydsl/apt/domain/Generic4Test.java | 29 +- .../com/querydsl/apt/domain/Generic5Test.java | 38 +- .../com/querydsl/apt/domain/Generic6Test.java | 28 +- .../com/querydsl/apt/domain/Generic7Test.java | 40 +- .../com/querydsl/apt/domain/Generic8Test.java | 57 +- .../com/querydsl/apt/domain/Generic9Test.java | 85 +- .../apt/domain/GenericSignatureTest.java | 85 +- .../apt/domain/GenericStackOverflowTest.java | 28 +- .../com/querydsl/apt/domain/GenericTest.java | 194 +- .../querydsl/apt/domain/Hierarchy2Test.java | 47 +- .../querydsl/apt/domain/HierarchyTest.java | 71 +- .../com/querydsl/apt/domain/InitTest.java | 54 +- .../apt/domain/InnerExtensionsTest.java | 32 +- .../apt/domain/InterfaceType2Test.java | 147 +- .../apt/domain/InterfaceType3Test.java | 46 +- .../apt/domain/InterfaceTypeTest.java | 131 +- .../java/com/querydsl/apt/domain/JDOTest.java | 99 +- .../java/com/querydsl/apt/domain/JPATest.java | 32 +- .../querydsl/apt/domain/JodaMoneyHelpers.java | 19 +- .../querydsl/apt/domain/JodaMoneyTest.java | 14 +- .../com/querydsl/apt/domain/JodaTest.java | 40 +- .../apt/domain/JodaTimeSupportTest.java | 64 +- .../com/querydsl/apt/domain/KeywordsTest.java | 45 +- .../apt/domain/LiteralEntityTest.java | 20 +- .../com/querydsl/apt/domain/Location.java | 3 +- .../querydsl/apt/domain/ManagedEmailTest.java | 44 +- .../querydsl/apt/domain/ManyToManyTest.java | 32 +- .../querydsl/apt/domain/MonitoredCompany.java | 33 +- .../apt/domain/MonitoredCompanyTest.java | 13 +- .../com/querydsl/apt/domain/NumberTest.java | 12 +- .../com/querydsl/apt/domain/OneToOneTest.java | 29 +- .../com/querydsl/apt/domain/OrderTest.java | 31 +- .../java/com/querydsl/apt/domain/Path.java | 4 +- .../com/querydsl/apt/domain/PathInits.java | 4 +- .../com/querydsl/apt/domain/PathMetadata.java | 4 +- .../querydsl/apt/domain/PathMetadataTest.java | 66 +- .../com/querydsl/apt/domain/PathTest.java | 9 +- .../java/com/querydsl/apt/domain/Person.java | 235 +- .../com/querydsl/apt/domain/PersonTest.java | 9 +- .../java/com/querydsl/apt/domain/Private.java | 4 +- .../querydsl/apt/domain/Properties2Test.java | 38 +- .../querydsl/apt/domain/Properties3Test.java | 35 +- .../querydsl/apt/domain/Properties4Test.java | 18 +- .../querydsl/apt/domain/PropertiesTest.java | 134 +- .../querydsl/apt/domain/PropertyTypeTest.java | 24 +- .../java/com/querydsl/apt/domain/Public.java | 4 +- .../apt/domain/QueryByExampleTest.java | 42 +- .../apt/domain/QueryEmbeddable2Test.java | 39 +- .../apt/domain/QueryEmbeddable3Test.java | 131 +- .../apt/domain/QueryEmbeddableTest.java | 32 +- .../apt/domain/QueryEmbedded2Test.java | 33 +- .../apt/domain/QueryEmbedded3Test.java | 39 +- .../apt/domain/QueryEmbedded4Test.java | 92 +- .../apt/domain/QueryEmbedded5Test.java | 147 +- .../apt/domain/QueryEmbedded6Test.java | 34 +- .../apt/domain/QueryEmbedded7Test.java | 43 +- .../apt/domain/QueryEmbeddedTest.java | 66 +- .../querydsl/apt/domain/QueryExcludeTest.java | 27 +- .../querydsl/apt/domain/QueryInit2Test.java | 55 +- .../querydsl/apt/domain/QueryInit3Test.java | 34 +- .../querydsl/apt/domain/QueryInit4Test.java | 86 +- .../querydsl/apt/domain/QueryInit5Test.java | 71 +- .../querydsl/apt/domain/QueryInit6Test.java | 275 +- .../querydsl/apt/domain/QueryInit7Test.java | 158 +- .../querydsl/apt/domain/QueryInitTest.java | 114 +- .../apt/domain/QueryProjectionTest.java | 144 +- .../apt/domain/QuerySuperTypeTest.java | 31 +- .../domain/QueryTypeOverTransientTest.java | 46 +- .../querydsl/apt/domain/QueryTypeTest.java | 66 +- .../apt/domain/QuerydslConfig2Test.java | 60 +- .../apt/domain/QuerydslConfigTest.java | 43 +- .../java/com/querydsl/apt/domain/RawTest.java | 29 +- .../com/querydsl/apt/domain/RelationTest.java | 262 +- .../apt/domain/ReservedNamesInTypesTest.java | 11 +- .../apt/domain/ReservedNamesTest.java | 98 +- .../com/querydsl/apt/domain/Revision.java | 7 +- .../com/querydsl/apt/domain/RooEntities.java | 30 +- .../querydsl/apt/domain/RooEntitiesTest.java | 17 +- .../querydsl/apt/domain/SecurableEntity.java | 24 +- .../querydsl/apt/domain/SignatureTest.java | 38 +- .../querydsl/apt/domain/SimpleTypesTest.java | 575 +- .../java/com/querydsl/apt/domain/SubCat.java | 4 +- .../com/querydsl/apt/domain/Subclass.java | 18 +- .../querydsl/apt/domain/Superclass2Test.java | 48 +- .../querydsl/apt/domain/Superclass3Test.java | 22 +- .../querydsl/apt/domain/Superclass4Test.java | 38 +- .../querydsl/apt/domain/Superclass5Test.java | 44 +- .../querydsl/apt/domain/SuperclassTest.java | 28 +- .../querydsl/apt/domain/Temporal2Test.java | 49 +- .../com/querydsl/apt/domain/TemporalTest.java | 32 +- .../querydsl/apt/domain/TransientTest.java | 38 +- .../com/querydsl/apt/domain/UserUtils.java | 11 +- .../apt/domain/custom/CustomNumber.java | 65 +- .../apt/domain/custom/EmbeddedType.java | 4 +- .../apt/domain/custom/EmbeddedType2.java | 4 +- .../apt/domain/custom/EmbeddedType3.java | 4 +- .../querydsl/apt/domain/custom/Entity.java | 12 +- .../com/querydsl/apt/domain/p1/SEntity1.java | 2 +- .../apt/domain/p10/AbstractPersistable.java | 5 +- .../apt/domain/p10/BasePersistable.java | 6 +- .../p10/BaseReferencablePersistable.java | 6 +- .../querydsl/apt/domain/p10/Persistable.java | 4 +- .../querydsl/apt/domain/p10/UpdateInfo.java | 4 +- .../querydsl/apt/domain/p10/UserAccount.java | 4 +- .../com/querydsl/apt/domain/p2/SEntity2.java | 3 +- .../com/querydsl/apt/domain/p3/SEntity3.java | 2 +- .../querydsl/apt/domain/p4/SSupertype.java | 3 +- .../com/querydsl/apt/domain/p6/Type1.java | 15 +- .../com/querydsl/apt/domain/p6/Type2.java | 15 +- .../com/querydsl/apt/domain/p6/TypeTest.java | 14 +- .../querydsl/apt/domain/p6/package-info.java | 3 +- .../com/querydsl/apt/domain/p7/MyEntity.java | 4 +- .../com/querydsl/apt/domain/p8/Custom.java | 4 +- .../com/querydsl/apt/domain/p8/Entity.java | 29 +- .../com/querydsl/apt/domain/p9/Article.java | 7 +- .../com/querydsl/apt/domain/p9/Content.java | 3 +- .../com/querydsl/apt/domain/p9/Person.java | 2 +- .../com/querydsl/apt/domain/package-info.java | 8 +- .../apt/domain/rel/RelationType2.java | 5 +- .../querydsl/apt/domain/rel/SimpleType.java | 4 +- .../querydsl/apt/domain/rel/SimpleType2.java | 4 +- .../java/com/querydsl/apt/domain2/BImpl.java | 4 +- .../apt/inheritance/Inheritance11Test.java | 42 +- .../apt/inheritance/Inheritance2Test.java | 43 +- .../apt/inheritance/Inheritance3Test.java | 125 +- .../apt/inheritance/Inheritance4Test.java | 79 +- .../apt/inheritance/Inheritance5Test.java | 59 +- .../apt/inheritance/Inheritance6Test.java | 128 +- .../apt/inheritance/Inheritance7Test.java | 100 +- .../apt/inheritance/Inheritance8Test.java | 32 +- .../apt/inheritance/Inheritance9Test.java | 37 +- .../apt/inheritance/InheritanceTest.java | 97 +- querydsl-bom/pom.xml | 328 +- querydsl-codegen-utils/pom.xml | 83 +- .../codegen/utils/AbstractCodeWriter.java | 128 +- .../utils/AbstractEvaluatorFactory.java | 298 +- .../querydsl/codegen/utils/CodeWriter.java | 105 +- .../codegen/utils/CodegenException.java | 23 +- .../codegen/utils/ECJEvaluatorFactory.java | 452 +- .../com/querydsl/codegen/utils/Evaluator.java | 28 +- .../codegen/utils/EvaluatorFactory.java | 65 +- .../codegen/utils/JDKEvaluatorFactory.java | 77 +- .../querydsl/codegen/utils/JavaWriter.java | 891 ++-- .../codegen/utils/LocationAndKind.java | 54 +- .../codegen/utils/MemClassLoader.java | 152 +- .../codegen/utils/MemFileManager.java | 237 +- .../codegen/utils/MemFileSystemRegistry.java | 65 +- .../codegen/utils/MemJavaFileObject.java | 69 +- .../codegen/utils/MemSourceFileObject.java | 76 +- .../codegen/utils/MethodEvaluator.java | 59 +- .../codegen/utils/MultiSuppressWarnings.java | 26 +- .../querydsl/codegen/utils/ScalaWriter.java | 1108 ++-- .../codegen/utils/SimpleCompiler.java | 147 +- .../querydsl/codegen/utils/StringUtils.java | 47 +- .../com/querydsl/codegen/utils/Symbols.java | 40 +- .../codegen/utils/model/ClassType.java | 332 +- .../codegen/utils/model/Constructor.java | 44 +- .../codegen/utils/model/Parameter.java | 64 +- .../codegen/utils/model/SimpleType.java | 494 +- .../querydsl/codegen/utils/model/Type.java | 37 +- .../codegen/utils/model/TypeAdapter.java | 214 +- .../codegen/utils/model/TypeCategory.java | 200 +- .../codegen/utils/model/TypeExtends.java | 82 +- .../codegen/utils/model/TypeSuper.java | 89 +- .../querydsl/codegen/utils/model/Types.java | 116 +- .../codegen/utils/support/ClassUtils.java | 127 +- .../utils/support/ScalaSyntaxUtils.java | 69 +- .../codegen/utils/support/package-info.java | 1 - .../src/test/java/NestedTest.java | 26 +- .../querydsl/codegen/utils/Annotation.java | 9 +- .../querydsl/codegen/utils/Annotation2.java | 11 +- .../codegen/utils/Annotation2Impl.java | 25 +- .../querydsl/codegen/utils/Annotation3.java | 5 +- .../codegen/utils/AnnotationTest.java | 103 +- .../codegen/utils/ComplexEvaluationTest.java | 423 +- .../utils/ECJEvaluatorFactoryTest.java | 203 +- .../com/querydsl/codegen/utils/Entity.java | 6 +- .../codegen/utils/InnerClassesTest.java | 83 +- .../utils/JDKEvaluatorFactoryTest.java | 203 +- .../codegen/utils/JavaWriterTest.java | 583 ++- .../com/querydsl/codegen/utils/MaxImpl.java | 51 +- .../codegen/utils/MemJavaFileObjectTest.java | 35 +- .../utils/MemSourceFileObjectTest.java | 40 +- .../com/querydsl/codegen/utils/MinImpl.java | 51 +- .../querydsl/codegen/utils/NotNullImpl.java | 41 +- .../codegen/utils/ScalaWriterTest.java | 788 +-- .../codegen/utils/SimpleCompilerTest.java | 107 +- .../codegen/utils/SurefireBooterTest.java | 26 +- .../codegen/utils/model/ClassTypeTest.java | 235 +- .../codegen/utils/model/ConstructorTest.java | 26 +- .../codegen/utils/model/ParameterTest.java | 20 +- .../codegen/utils/model/SimpleTypeTest.java | 156 +- .../codegen/utils/model/TypeAdapterTest.java | 30 +- .../codegen/utils/model/TypeCategoryTest.java | 56 +- .../codegen/utils/model/TypeExtendsTest.java | 45 +- .../codegen/utils/model/TypeSuperTest.java | 42 +- .../codegen/utils/model/TypeTest.java | 332 +- .../querydsl/codegen/utils/support/Cat.java | 272 +- .../codegen/utils/support/ClassUtilsTest.java | 63 +- querydsl-codegen/pom.xml | 38 +- .../com/querydsl/codegen/AbstractModule.java | 244 +- .../querydsl/codegen/AnnotationHelper.java | 48 +- .../com/querydsl/codegen/BeanSerializer.java | 464 +- .../com/querydsl/codegen/ClassPathUtils.java | 98 +- .../com/querydsl/codegen/CodegenModule.java | 91 +- .../codegen/DefaultEmbeddableSerializer.java | 152 +- .../codegen/DefaultEntitySerializer.java | 1798 ++++--- .../com/querydsl/codegen/DefaultFiler.java | 19 +- .../codegen/DefaultProjectionSerializer.java | 245 +- .../codegen/DefaultSupertypeSerializer.java | 53 +- .../codegen/DefaultVariableNameFunction.java | 23 +- .../java/com/querydsl/codegen/Delegate.java | 99 +- .../codegen/EmbeddableSerializer.java | 3 +- .../querydsl/codegen/EntitySerializer.java | 3 +- .../java/com/querydsl/codegen/EntityType.java | 497 +- .../java/com/querydsl/codegen/Extension.java | 17 +- .../main/java/com/querydsl/codegen/Filer.java | 10 +- .../codegen/GeneratedAnnotationResolver.java | 113 +- .../com/querydsl/codegen/GenericExporter.java | 1430 ++--- .../codegen/GroovyBeanSerializer.java | 217 +- .../querydsl/codegen/JavaTypeMappings.java | 51 +- .../java/com/querydsl/codegen/Keywords.java | 141 +- .../com/querydsl/codegen/NamingFunction.java | 3 +- .../codegen/ParameterizedTypeImpl.java | 70 +- .../codegen/ProjectionSerializer.java | 4 +- .../java/com/querydsl/codegen/Property.java | 280 +- .../querydsl/codegen/PropertyHandling.java | 218 +- .../querydsl/codegen/QueryTypeFactory.java | 21 +- .../codegen/QueryTypeFactoryImpl.java | 76 +- .../java/com/querydsl/codegen/Serializer.java | 24 +- .../querydsl/codegen/SerializerConfig.java | 61 +- .../codegen/SimpleSerializerConfig.java | 91 +- .../java/com/querydsl/codegen/Supertype.java | 82 +- .../querydsl/codegen/SupertypeSerializer.java | 4 +- .../com/querydsl/codegen/TypeFactory.java | 436 +- .../com/querydsl/codegen/TypeMappings.java | 193 +- .../com/querydsl/codegen/TypeResolver.java | 169 +- .../com/querydsl/codegen/package-info.java | 4 +- querydsl-codegen/src/test/java/Entity.java | 21 +- querydsl-codegen/src/test/java/Entity2.java | 15 +- .../src/test/java/com/SomeClass.java | 4 +- .../java/com/applejuice/ShouldBeLoaded.java | 3 +- .../codegen/AbstractExporterTest.java | 14 +- .../querydsl/codegen/BeanSerializerTest.java | 365 +- .../querydsl/codegen/ClassPathUtilsTest.java | 55 +- .../querydsl/codegen/CodegenModuleTest.java | 61 +- .../com/querydsl/codegen/CompileUtils.java | 52 +- .../com/querydsl/codegen/CustomTypeTest.java | 49 +- .../com/querydsl/codegen/DelegateTest.java | 57 +- .../codegen/EmbeddableSerializerTest.java | 381 +- .../com/querydsl/codegen/Embedded2Test.java | 64 +- .../com/querydsl/codegen/EmbeddedTest.java | 36 +- .../codegen/EntityInheritanceTest.java | 21 +- .../codegen/EntitySerializerTest.java | 416 +- .../com/querydsl/codegen/EntityTypeTest.java | 62 +- .../querydsl/codegen/ExampleEmbeddable.java | 17 +- .../com/querydsl/codegen/ExampleEmbedded.java | 15 +- .../com/querydsl/codegen/ExampleEntity.java | 93 +- .../codegen/ExampleEntityInterface.java | 4 +- .../querydsl/codegen/ExampleSupertype.java | 14 +- .../java/com/querydsl/codegen/Examples.java | 136 +- .../codegen/ExternalEmbeddableTest.java | 14 +- .../GeneratedAnnotationResolverTest.java | 49 +- .../com/querydsl/codegen/Generic2Test.java | 101 +- .../querydsl/codegen/GenericExporterTest.java | 290 +- .../com/querydsl/codegen/GenericTest.java | 41 +- .../codegen/GroovyBeanSerializerTest.java | 105 +- .../test/java/com/querydsl/codegen/Group.java | 4 +- .../querydsl/codegen/Inheritance2Test.java | 112 +- .../querydsl/codegen/PackageSuffixTest.java | 37 +- .../test/java/com/querydsl/codegen/Point.java | 22 +- .../codegen/ProjectionSerializerTest.java | 119 +- .../com/querydsl/codegen/PropertyTest.java | 57 +- .../codegen/QueryEmbeddable2Test.java | 33 +- .../com/querydsl/codegen/QueryEntityImpl.java | 14 +- .../codegen/QueryTypeFactoryTest.java | 54 +- .../com/querydsl/codegen/ScalaTypeDump.java | 81 +- .../com/querydsl/codegen/SerializerTest.java | 165 +- .../com/querydsl/codegen/SomeOtherClass.java | 8 +- .../com/querydsl/codegen/SomeOtherClass2.java | 5 +- .../com/querydsl/codegen/TypeFactoryTest.java | 430 +- .../querydsl/codegen/TypeMappingsTest.java | 69 +- .../querydsl/codegen/TypeResolverTest.java | 2 +- .../querydsl/codegen/sub/ExampleEntity2.java | 15 +- .../java/com/suntanning/ShouldBeLoaded.java | 3 +- querydsl-collections/pom.xml | 24 +- .../collections/AbstractCollQuery.java | 365 +- .../collections/CollDeleteClause.java | 64 +- .../com/querydsl/collections/CollQuery.java | 121 +- .../collections/CollQueryFactory.java | 112 +- .../collections/CollQueryFunctions.java | 538 +- .../querydsl/collections/CollQueryMixin.java | 52 +- .../collections/CollQuerySerializer.java | 339 +- .../collections/CollQueryTemplates.java | 117 +- .../collections/CollUpdateClause.java | 146 +- .../collections/DefaultEvaluatorFactory.java | 445 +- .../collections/DefaultQueryEngine.java | 354 +- .../collections/EvaluatorFunction.java | 24 +- .../collections/FunctionalHelpers.java | 77 +- .../collections/JodaTimeTemplates.java | 35 +- .../querydsl/collections/MultiComparator.java | 70 +- .../querydsl/collections/PathComparator.java | 68 +- .../com/querydsl/collections/PathMatcher.java | 77 +- .../com/querydsl/collections/QueryEngine.java | 57 +- .../querydsl/collections/package-info.java | 4 +- .../collections/AbstractQueryTest.java | 123 +- .../querydsl/collections/AggregationTest.java | 90 +- .../com/querydsl/collections/AliasTest.java | 245 +- .../java/com/querydsl/collections/Animal.java | 128 +- .../com/querydsl/collections/AnimalTest.java | 24 +- .../querydsl/collections/BigDecimalTest.java | 39 +- .../com/querydsl/collections/BooleanTest.java | 59 +- .../java/com/querydsl/collections/Car.java | 44 +- .../com/querydsl/collections/CastTest.java | 53 +- .../java/com/querydsl/collections/Cat.java | 218 +- .../com/querydsl/collections/CatTest.java | 27 +- .../collections/CollDeleteClauseTest.java | 32 +- .../collections/CollQueryFunctionsTest.java | 60 +- .../collections/CollQueryStandardTest.java | 272 +- .../collections/CollQueryTemplatesTest.java | 28 +- .../querydsl/collections/CollQueryTest.java | 280 +- .../collections/CollUpdateClauseTest.java | 23 +- .../collections/CollectionAnyTest.java | 188 +- .../querydsl/collections/CollectionTest.java | 180 +- .../java/com/querydsl/collections/Color.java | 3 +- .../com/querydsl/collections/Comment.java | 86 +- .../collections/CompilationOverheadTest.java | 45 +- .../querydsl/collections/DistinctTest.java | 87 +- .../com/querydsl/collections/Document.java | 34 +- .../querydsl/collections/DocumentTest.java | 101 +- .../collections/ECJEvaluatorFactoryTest.java | 22 +- .../collections/EntityWithLongId.java | 22 +- .../collections/EntityWithLongIdTest.java | 74 +- .../collections/EvaluatorTransformerTest.java | 35 +- .../collections/FirstResultContractTest.java | 9 +- .../collections/FunctionalHelpersTest.java | 34 +- .../querydsl/collections/GroupBy2Test.java | 265 +- .../querydsl/collections/GroupBy3Test.java | 175 +- .../querydsl/collections/GroupBy4Test.java | 507 +- .../com/querydsl/collections/GroupByTest.java | 472 +- .../querydsl/collections/InnerClassTest.java | 38 +- .../querydsl/collections/InnerJoinTest.java | 87 +- .../querydsl/collections/IterationTest.java | 58 +- .../com/querydsl/collections/JacocoTest.java | 93 +- .../collections/JodaTimeTemplatesTest.java | 85 +- .../querydsl/collections/LeftJoinTest.java | 86 +- .../com/querydsl/collections/LoadTest.java | 125 +- .../collections/MappingProjectionTest.java | 52 +- .../com/querydsl/collections/MathTest.java | 111 +- .../com/querydsl/collections/MockTest.java | 21 +- .../collections/MultiComparatorTest.java | 31 +- .../querydsl/collections/NullSafetyTest.java | 45 +- .../com/querydsl/collections/NumberTest.java | 20 +- .../com/querydsl/collections/OrderTest.java | 122 +- .../com/querydsl/collections/PagingTest.java | 70 +- .../collections/PathComparatorTest.java | 74 +- .../querydsl/collections/PathMatcherTest.java | 55 +- .../querydsl/collections/PatternsTest.java | 17 +- .../java/com/querydsl/collections/Person.java | 14 +- .../java/com/querydsl/collections/Post.java | 90 +- .../com/querydsl/collections/Projection.java | 6 +- .../querydsl/collections/PropertiesTest.java | 35 +- .../java/com/querydsl/collections/QCar.java | 21 +- .../com/querydsl/collections/QPerson.java | 17 +- .../collections/QueryMetadataTest.java | 25 +- .../collections/QueryMutabilityTest.java | 28 +- .../collections/QueryPerformanceTest.java | 75 +- .../collections/SerializationTest.java | 275 +- .../querydsl/collections/StateHistory.java | 14 +- .../collections/StateHistoryOwner.java | 9 +- .../collections/StringHandlingTest.java | 63 +- .../querydsl/collections/TemplatesTest.java | 4 +- .../querydsl/collections/TypeCastTest.java | 20 +- .../collections/UniqueResultContractTest.java | 24 +- .../java/com/querydsl/collections/User.java | 54 +- querydsl-core/pom.xml | 36 +- .../com/querydsl/core/BooleanBuilder.java | 336 +- .../querydsl/core/DefaultQueryMetadata.java | 667 ++- .../java/com/querydsl/core/EmptyMetadata.java | 347 +- .../java/com/querydsl/core/Fetchable.java | 133 +- .../com/querydsl/core/FetchableQuery.java | 51 +- .../com/querydsl/core/FilteredClause.java | 20 +- .../com/querydsl/core/JoinExpression.java | 177 +- .../main/java/com/querydsl/core/JoinFlag.java | 203 +- .../main/java/com/querydsl/core/JoinType.java | 60 +- .../core/NonUniqueResultException.java | 26 +- .../main/java/com/querydsl/core/Query.java | 34 +- .../com/querydsl/core/QueryException.java | 22 +- .../java/com/querydsl/core/QueryFactory.java | 15 +- .../java/com/querydsl/core/QueryFlag.java | 195 +- .../java/com/querydsl/core/QueryMetadata.java | 481 +- .../com/querydsl/core/QueryModifiers.java | 193 +- .../java/com/querydsl/core/QueryResults.java | 176 +- .../com/querydsl/core/ResultTransformer.java | 21 +- .../java/com/querydsl/core/SimpleQuery.java | 91 +- .../main/java/com/querydsl/core/Tuple.java | 101 +- .../java/com/querydsl/core/alias/Alias.java | 856 ++- .../com/querydsl/core/alias/AliasFactory.java | 245 +- .../core/alias/DefaultPathFactory.java | 170 +- .../core/alias/DefaultTypeSystem.java | 34 +- .../querydsl/core/alias/ManagedObject.java | 18 +- .../com/querydsl/core/alias/MethodType.java | 109 +- .../com/querydsl/core/alias/PathFactory.java | 272 +- .../PropertyAccessInvocationHandler.java | 477 +- .../com/querydsl/core/alias/TypeSystem.java | 62 +- .../com/querydsl/core/alias/package-info.java | 5 +- .../com/querydsl/core/annotations/Config.java | 34 +- .../querydsl/core/annotations/Generated.java | 18 +- .../querydsl/core/annotations/Immutable.java | 3 +- .../core/annotations/PropertyType.java | 63 +- .../core/annotations/QueryDelegate.java | 12 +- .../core/annotations/QueryEmbeddable.java | 7 +- .../core/annotations/QueryEmbedded.java | 7 +- .../core/annotations/QueryEntities.java | 10 +- .../core/annotations/QueryEntity.java | 7 +- .../core/annotations/QueryExclude.java | 5 +- .../querydsl/core/annotations/QueryInit.java | 10 +- .../core/annotations/QueryProjection.java | 14 +- .../core/annotations/QuerySupertype.java | 8 +- .../core/annotations/QueryTransient.java | 11 +- .../querydsl/core/annotations/QueryType.java | 9 +- .../core/annotations/package-info.java | 5 +- .../java/com/querydsl/core/dml/DMLClause.java | 13 +- .../com/querydsl/core/dml/DeleteClause.java | 6 +- .../com/querydsl/core/dml/InsertClause.java | 44 +- .../com/querydsl/core/dml/StoreClause.java | 74 +- .../com/querydsl/core/dml/UpdateClause.java | 21 +- .../com/querydsl/core/dml/package-info.java | 4 +- .../group/AbstractGroupByTransformer.java | 135 +- .../core/group/AbstractGroupExpression.java | 107 +- .../java/com/querydsl/core/group/GAvg.java | 77 +- .../java/com/querydsl/core/group/GList.java | 47 +- .../java/com/querydsl/core/group/GMap.java | 247 +- .../java/com/querydsl/core/group/GMax.java | 49 +- .../java/com/querydsl/core/group/GMin.java | 49 +- .../java/com/querydsl/core/group/GOne.java | 58 +- .../java/com/querydsl/core/group/GSet.java | 98 +- .../java/com/querydsl/core/group/GSum.java | 57 +- .../java/com/querydsl/core/group/Group.java | 171 +- .../java/com/querydsl/core/group/GroupBy.java | 657 +-- .../querydsl/core/group/GroupByBuilder.java | 507 +- .../core/group/GroupByGenericCollection.java | 89 +- .../core/group/GroupByGenericMap.java | 82 +- .../querydsl/core/group/GroupByIterate.java | 143 +- .../com/querydsl/core/group/GroupByList.java | 88 +- .../com/querydsl/core/group/GroupByMap.java | 76 +- .../core/group/GroupByProjection.java | 40 +- .../querydsl/core/group/GroupCollector.java | 28 +- .../querydsl/core/group/GroupExpression.java | 34 +- .../com/querydsl/core/group/GroupImpl.java | 191 +- .../core/group/MixinGroupExpression.java | 73 +- .../java/com/querydsl/core/group/QPair.java | 34 +- .../com/querydsl/core/group/package-info.java | 4 +- .../java/com/querydsl/core/package-info.java | 5 +- .../core/support/CollectionAnyVisitor.java | 186 +- .../support/ConstantHidingExpression.java | 107 +- .../com/querydsl/core/support/Context.java | 43 +- .../querydsl/core/support/EnumConversion.java | 79 +- .../core/support/ExtendedSubQuery.java | 316 +- .../core/support/FetchableQueryBase.java | 92 +- .../core/support/FetchableSubQueryBase.java | 290 +- .../core/support/NumberConversion.java | 71 +- .../core/support/NumberConversions.java | 93 +- .../core/support/OrderedQueryMetadata.java | 66 +- .../querydsl/core/support/PathsExtractor.java | 87 +- .../com/querydsl/core/support/QueryBase.java | 339 +- .../com/querydsl/core/support/QueryMixin.java | 807 +-- .../querydsl/core/support/ReplaceVisitor.java | 247 +- .../querydsl/core/support/SerializerBase.java | 561 +- .../querydsl/core/support/package-info.java | 4 +- .../types/AppendingFactoryExpression.java | 68 +- .../types/ArrayConstructorExpression.java | 100 +- .../core/types/CollectionExpression.java | 6 +- .../com/querydsl/core/types/Constant.java | 14 +- .../com/querydsl/core/types/ConstantImpl.java | 215 +- .../core/types/ConstructorExpression.java | 217 +- .../com/querydsl/core/types/EntityPath.java | 16 +- .../com/querydsl/core/types/Expression.java | 59 +- .../querydsl/core/types/ExpressionBase.java | 50 +- .../core/types/ExpressionException.java | 22 +- .../querydsl/core/types/ExpressionUtils.java | 1637 +++--- .../querydsl/core/types/ExtractorVisitor.java | 83 +- .../core/types/FactoryExpression.java | 37 +- .../core/types/FactoryExpressionBase.java | 120 +- .../core/types/FactoryExpressionUtils.java | 253 +- .../querydsl/core/types/HashCodeVisitor.java | 70 +- .../querydsl/core/types/JavaTemplates.java | 142 +- .../querydsl/core/types/MapExpression.java | 5 +- .../core/types/MappingProjection.java | 97 +- .../core/types/MutableExpressionBase.java | 37 +- .../querydsl/core/types/NullExpression.java | 18 +- .../com/querydsl/core/types/Operation.java | 44 +- .../querydsl/core/types/OperationImpl.java | 95 +- .../com/querydsl/core/types/Operator.java | 28 +- .../java/com/querydsl/core/types/Ops.java | 549 +- .../java/com/querydsl/core/types/Order.java | 13 +- .../querydsl/core/types/OrderSpecifier.java | 201 +- .../querydsl/core/types/ParamExpression.java | 38 +- .../core/types/ParamExpressionImpl.java | 92 +- .../core/types/ParamNotSetException.java | 10 +- .../core/types/ParameterizedExpression.java | 19 +- .../core/types/ParameterizedPathImpl.java | 22 +- .../querydsl/core/types/ParamsVisitor.java | 136 +- .../java/com/querydsl/core/types/Path.java | 46 +- .../querydsl/core/types/PathExtractor.java | 82 +- .../com/querydsl/core/types/PathImpl.java | 113 +- .../com/querydsl/core/types/PathMetadata.java | 126 +- .../core/types/PathMetadataFactory.java | 200 +- .../com/querydsl/core/types/PathType.java | 79 +- .../com/querydsl/core/types/Predicate.java | 14 +- .../core/types/PredicateOperation.java | 28 +- .../core/types/PredicateTemplate.java | 28 +- .../querydsl/core/types/ProjectionRole.java | 19 +- .../com/querydsl/core/types/Projections.java | 481 +- .../java/com/querydsl/core/types/QBean.java | 424 +- .../java/com/querydsl/core/types/QList.java | 127 +- .../java/com/querydsl/core/types/QMap.java | 142 +- .../java/com/querydsl/core/types/QTuple.java | 261 +- .../core/types/SubQueryExpression.java | 14 +- .../core/types/SubQueryExpressionImpl.java | 55 +- .../com/querydsl/core/types/Template.java | 561 +- .../core/types/TemplateExpression.java | 39 +- .../core/types/TemplateExpressionImpl.java | 107 +- .../querydsl/core/types/TemplateFactory.java | 448 +- .../com/querydsl/core/types/Templates.java | 611 ++- .../querydsl/core/types/ToStringVisitor.java | 181 +- .../core/types/ValidatingVisitor.java | 180 +- .../java/com/querydsl/core/types/Visitor.java | 114 +- .../core/types/dsl/ArrayExpression.java | 57 +- .../querydsl/core/types/dsl/ArrayPath.java | 137 +- .../com/querydsl/core/types/dsl/BeanPath.java | 604 +-- .../core/types/dsl/BooleanExpression.java | 416 +- .../core/types/dsl/BooleanOperation.java | 77 +- .../querydsl/core/types/dsl/BooleanPath.java | 69 +- .../core/types/dsl/BooleanTemplate.java | 57 +- .../querydsl/core/types/dsl/CaseBuilder.java | 515 +- .../core/types/dsl/CaseForEqBuilder.java | 590 ++- .../com/querydsl/core/types/dsl/Coalesce.java | 243 +- .../types/dsl/CollectionExpressionBase.java | 178 +- .../core/types/dsl/CollectionOperation.java | 61 +- .../core/types/dsl/CollectionPath.java | 131 +- .../core/types/dsl/CollectionPathBase.java | 121 +- .../core/types/dsl/ComparableEntityPath.java | 36 +- .../core/types/dsl/ComparableExpression.java | 893 ++-- .../types/dsl/ComparableExpressionBase.java | 252 +- .../core/types/dsl/ComparableOperation.java | 67 +- .../core/types/dsl/ComparablePath.java | 71 +- .../core/types/dsl/ComparableTemplate.java | 76 +- .../querydsl/core/types/dsl/Constants.java | 36 +- .../core/types/dsl/DateExpression.java | 442 +- .../core/types/dsl/DateOperation.java | 67 +- .../com/querydsl/core/types/dsl/DatePath.java | 69 +- .../querydsl/core/types/dsl/DateTemplate.java | 76 +- .../core/types/dsl/DateTimeExpression.java | 620 ++- .../core/types/dsl/DateTimeOperation.java | 66 +- .../querydsl/core/types/dsl/DateTimePath.java | 69 +- .../core/types/dsl/DateTimeTemplate.java | 76 +- .../core/types/dsl/DslExpression.java | 85 +- .../querydsl/core/types/dsl/DslOperation.java | 55 +- .../com/querydsl/core/types/dsl/DslPath.java | 60 +- .../querydsl/core/types/dsl/DslTemplate.java | 49 +- .../core/types/dsl/EntityPathBase.java | 33 +- .../core/types/dsl/EnumExpression.java | 197 +- .../core/types/dsl/EnumOperation.java | 63 +- .../com/querydsl/core/types/dsl/EnumPath.java | 68 +- .../querydsl/core/types/dsl/EnumTemplate.java | 76 +- .../querydsl/core/types/dsl/Expressions.java | 3786 +++++++------- .../core/types/dsl/ListExpression.java | 39 +- .../com/querydsl/core/types/dsl/ListPath.java | 221 +- .../core/types/dsl/LiteralExpression.java | 61 +- .../core/types/dsl/MapExpressionBase.java | 253 +- .../com/querydsl/core/types/dsl/MapPath.java | 266 +- .../core/types/dsl/MathExpressions.java | 528 +- .../core/types/dsl/NumberExpression.java | 1674 +++--- .../core/types/dsl/NumberOperation.java | 83 +- .../querydsl/core/types/dsl/NumberPath.java | 71 +- .../core/types/dsl/NumberTemplate.java | 76 +- .../com/querydsl/core/types/dsl/Param.java | 53 +- .../querydsl/core/types/dsl/PathBuilder.java | 989 ++-- .../core/types/dsl/PathBuilderFactory.java | 63 +- .../core/types/dsl/PathBuilderValidator.java | 103 +- .../querydsl/core/types/dsl/PathInits.java | 117 +- .../com/querydsl/core/types/dsl/SetPath.java | 129 +- .../core/types/dsl/SimpleExpression.java | 688 ++- .../core/types/dsl/SimpleOperation.java | 63 +- .../querydsl/core/types/dsl/SimplePath.java | 68 +- .../core/types/dsl/SimpleTemplate.java | 57 +- .../core/types/dsl/StringExpression.java | 1798 +++---- .../core/types/dsl/StringExpressions.java | 252 +- .../core/types/dsl/StringOperation.java | 63 +- .../querydsl/core/types/dsl/StringPath.java | 68 +- .../core/types/dsl/StringTemplate.java | 57 +- .../core/types/dsl/TemporalExpression.java | 82 +- .../core/types/dsl/TimeExpression.java | 347 +- .../core/types/dsl/TimeOperation.java | 66 +- .../com/querydsl/core/types/dsl/TimePath.java | 68 +- .../querydsl/core/types/dsl/TimeTemplate.java | 76 +- .../com/querydsl/core/types/dsl/Wildcard.java | 31 +- .../querydsl/core/types/dsl/package-info.java | 4 +- .../com/querydsl/core/types/package-info.java | 4 +- .../com/querydsl/core/util/Annotations.java | 64 +- .../com/querydsl/core/util/ArrayUtils.java | 78 +- .../java/com/querydsl/core/util/BeanMap.java | 1242 +++-- .../com/querydsl/core/util/BeanUtils.java | 51 +- .../querydsl/core/util/CollectionUtils.java | 440 +- .../querydsl/core/util/ConstructorUtils.java | 412 +- .../com/querydsl/core/util/FileUtils.java | 26 +- .../querydsl/core/util/JavaSyntaxUtils.java | 10 +- .../com/querydsl/core/util/MathUtils.java | 127 +- .../com/querydsl/core/util/MultiIterator.java | 107 +- .../util/NullSafeComparableComparator.java | 25 +- .../querydsl/core/util/PrimitiveUtils.java | 72 +- .../querydsl/core/util/ReflectionUtils.java | 262 +- .../querydsl/core/util/ResultSetAdapter.java | 1994 ++++--- .../com/querydsl/core/util/StringUtils.java | 28 +- .../com/querydsl/core/util/package-info.java | 4 +- .../com/querydsl/core/BooleanBuilderTest.java | 313 +- .../com/querydsl/core/BooleanConstant.java | 64 +- .../java/com/querydsl/core/CoverageTest.java | 178 +- .../core/CycleClassInitDependencyTest.java | 73 +- .../java/com/querydsl/core/DateConstant.java | 135 +- .../com/querydsl/core/DateConstantTest.java | 35 +- .../com/querydsl/core/DateTimeConstant.java | 169 +- .../querydsl/core/DateTimeConstantTest.java | 49 +- .../core/DefaultQueryMetadataTest.java | 514 +- .../com/querydsl/core/DependenciesTest.java | 42 +- .../test/java/com/querydsl/core/Entity.java | 22 +- .../java/com/querydsl/core/FilterFactory.java | 586 ++- .../querydsl/core/MatchingFiltersFactory.java | 539 +- .../com/querydsl/core/NullExpressionTest.java | 41 +- .../com/querydsl/core/NumberConstant.java | 189 +- .../com/querydsl/core/ProjectionsFactory.java | 349 +- .../querydsl/core/QDefaultQueryMetadata.java | 74 +- .../com/querydsl/core/QueryExecution.java | 548 +- .../core/QueryMetadaSerializationTest.java | 144 +- .../com/querydsl/core/QueryModifiersTest.java | 105 +- .../com/querydsl/core/QueryMutability.java | 69 +- .../com/querydsl/core/QueryResultsTest.java | 78 +- .../com/querydsl/core/QuerydslModule.java | 38 +- .../com/querydsl/core/SimpleConstant.java | 86 +- .../com/querydsl/core/StringConstant.java | 296 +- .../com/querydsl/core/StringConstantTest.java | 41 +- .../test/java/com/querydsl/core/Target.java | 86 +- .../com/querydsl/core/TemplatesTestBase.java | 52 +- .../java/com/querydsl/core/TimeConstant.java | 82 +- .../com/querydsl/core/TimeConstantTest.java | 33 +- .../com/querydsl/core/alias/AliasTest.java | 129 +- .../querydsl/core/alias/CollectionTest.java | 64 +- .../querydsl/core/alias/ComparableEntity.java | 21 +- .../core/alias/ComparablePropertyTest.java | 65 +- .../com/querydsl/core/alias/DomainType.java | 39 +- .../core/alias/FinalPropertyTest.java | 31 +- .../java/com/querydsl/core/alias/Gender.java | 6 +- .../querydsl/core/alias/MethodTypeTest.java | 41 +- .../querydsl/core/alias/PathFactoryTest.java | 198 +- .../querydsl/core/alias/ScalaAccessors.java | 6 +- .../core/alias/ScalaAccessorsTest.java | 15 +- .../test/java/com/querydsl/core/domain/A.java | 3 +- .../querydsl/core/domain/AbstractEntity.java | 4 +- .../java/com/querydsl/core/domain/Animal.java | 131 +- .../java/com/querydsl/core/domain/Cat.java | 67 +- .../core/domain/CommonIdentifiable.java | 12 +- .../core/domain/CommonPersistence.java | 15 +- .../com/querydsl/core/domain/Company.java | 17 +- .../querydsl/core/domain/CompanyGroup.java | 31 +- .../querydsl/core/domain/CompanyGroupPK.java | 34 +- .../com/querydsl/core/domain/CompanyPK.java | 15 +- .../core/domain/EmbeddableWithoutQType.java | 4 +- .../querydsl/core/domain/GenericEntity.java | 15 +- .../com/querydsl/core/domain/IdNamePair.java | 31 +- .../querydsl/core/domain/MyEmbeddable.java | 29 +- .../querydsl/core/domain/QAbstractEntity.java | 31 +- .../com/querydsl/core/domain/QAnimal.java | 51 +- .../java/com/querydsl/core/domain/QCat.java | 103 +- .../core/domain/QCommonIdentifiable.java | 49 +- .../core/domain/QCommonPersistence.java | 33 +- .../com/querydsl/core/domain/QCompany.java | 44 +- .../querydsl/core/domain/QCompanyGroup.java | 51 +- .../querydsl/core/domain/QCompanyGroupPK.java | 36 +- .../com/querydsl/core/domain/QCompanyPK.java | 34 +- .../com/querydsl/core/domain/QIdNamePair.java | 40 +- .../querydsl/core/domain/QMyEmbeddable.java | 33 +- .../querydsl/core/domain/QSuperSupertype.java | 33 +- .../com/querydsl/core/domain/QSuperclass.java | 36 +- .../querydsl/core/domain/SuperSupertype.java | 29 +- .../com/querydsl/core/domain/Superclass.java | 25 +- .../java/com/querydsl/core/domain/Tenant.java | 4 +- .../core/domain/query/QAbstractEntity.java | 31 +- .../querydsl/core/domain/query/QAnimal.java | 53 +- .../com/querydsl/core/domain/query/QCat.java | 103 +- .../domain/query/QCommonIdentifiable.java | 49 +- .../core/domain/query/QCommonPersistence.java | 33 +- .../querydsl/core/domain/query/QCompany.java | 44 +- .../core/domain/query/QCompanyGroup.java | 51 +- .../core/domain/query/QCompanyGroupPK.java | 36 +- .../core/domain/query/QCompanyPK.java | 34 +- .../core/domain/query/QIdNamePair.java | 40 +- .../core/domain/query/QMyEmbeddable.java | 33 +- .../core/domain/query/QSuperSupertype.java | 33 +- .../core/domain/query/QSuperclass.java | 36 +- .../domain/query2/QAbstractEntityType.java | 31 +- .../core/domain/query2/QAnimalType.java | 52 +- .../querydsl/core/domain/query2/QCatType.java | 103 +- .../query2/QCommonIdentifiableType.java | 49 +- .../domain/query2/QCommonPersistenceType.java | 33 +- .../domain/query2/QCompanyGroupPKType.java | 37 +- .../core/domain/query2/QCompanyGroupType.java | 52 +- .../core/domain/query2/QCompanyPKType.java | 34 +- .../core/domain/query2/QCompanyType.java | 44 +- .../core/domain/query2/QIdNamePairType.java | 40 +- .../core/domain/query2/QMyEmbeddableType.java | 33 +- .../domain/query2/QSuperSupertypeType.java | 34 +- .../core/domain/query2/QSuperclassType.java | 36 +- .../core/domain/query3/QTAbstractEntity.java | 31 +- .../querydsl/core/domain/query3/QTAnimal.java | 50 +- .../querydsl/core/domain/query3/QTCat.java | 103 +- .../domain/query3/QTCommonIdentifiable.java | 49 +- .../domain/query3/QTCommonPersistence.java | 33 +- .../core/domain/query3/QTCompany.java | 44 +- .../core/domain/query3/QTCompanyGroup.java | 52 +- .../core/domain/query3/QTCompanyGroupPK.java | 36 +- .../core/domain/query3/QTCompanyPK.java | 34 +- .../core/domain/query3/QTIdNamePair.java | 40 +- .../core/domain/query3/QTMyEmbeddable.java | 33 +- .../core/domain/query3/QTSuperSupertype.java | 33 +- .../core/domain/query3/QTSuperclass.java | 36 +- .../java/com/querydsl/core/domain2/ABase.java | 25 +- .../java/com/querydsl/core/domain2/AImpl.java | 4 +- .../com/querydsl/core/domain2/QABase.java | 47 +- .../com/querydsl/core/domain2/QAImpl.java | 62 +- .../querydsl/core/domain2/QTenantImpl.java | 32 +- .../com/querydsl/core/domain2/Tenant.java | 4 +- .../com/querydsl/core/domain2/TenantImpl.java | 4 +- .../core/group/AbstractGroupByTest.java | 355 +- .../java/com/querydsl/core/group/Comment.java | 94 +- .../core/group/GroupByIterateTest.java | 531 +- .../querydsl/core/group/GroupByListTest.java | 480 +- .../querydsl/core/group/GroupByMapTest.java | 666 +-- .../com/querydsl/core/group/MockTuple.java | 98 +- .../java/com/querydsl/core/group/Post.java | 60 +- .../java/com/querydsl/core/group/User.java | 50 +- .../core/serialization/DummySerializer.java | 31 +- .../core/serialization/JavaTemplatesTest.java | 22 +- .../serialization/SerializerBaseTest.java | 37 +- .../support/CollectionAnyVisitorTest.java | 122 +- .../support/ConstantHidingExpressionTest.java | 35 +- .../querydsl/core/support/DummyEntity.java | 33 +- .../querydsl/core/support/DummyFetchable.java | 86 +- .../core/support/DummyFetchableQuery.java | 99 +- .../core/support/EnumConversionTest.java | 70 +- .../core/support/NumberConversionsTest.java | 85 +- .../support/OrderedQueryMetadataTest.java | 148 +- .../support/QueryMixinPerformanceTest.java | 72 +- .../querydsl/core/support/QueryMixinTest.java | 277 +- .../core/support/ReplaceVisitorTest.java | 59 +- .../com/querydsl/core/testutil/CUBRID.java | 3 +- .../java/com/querydsl/core/testutil/DB2.java | 3 +- .../com/querydsl/core/testutil/Database.java | 7 +- .../com/querydsl/core/testutil/Derby.java | 3 +- .../core/testutil/EmbeddedDatabase.java | 7 +- .../core/testutil/EmptyStatement.java | 11 +- .../com/querydsl/core/testutil/ExcludeIn.java | 8 +- .../core/testutil/ExternalDatabase.java | 8 +- .../com/querydsl/core/testutil/Firebird.java | 3 +- .../java/com/querydsl/core/testutil/H2.java | 3 +- .../com/querydsl/core/testutil/HSQLDB.java | 3 +- .../com/querydsl/core/testutil/IncludeIn.java | 8 +- .../com/querydsl/core/testutil/MongoDB.java | 3 +- .../com/querydsl/core/testutil/MySQL.java | 3 +- .../com/querydsl/core/testutil/Oracle.java | 3 +- .../querydsl/core/testutil/Parallelized.java | 47 +- .../querydsl/core/testutil/Performance.java | 8 +- .../querydsl/core/testutil/PostgreSQL.java | 3 +- .../querydsl/core/testutil/ReportingOnly.java | 7 +- .../com/querydsl/core/testutil/SQLServer.java | 3 +- .../com/querydsl/core/testutil/SQLite.java | 3 +- .../querydsl/core/testutil/Serialization.java | 36 +- .../com/querydsl/core/testutil/SlowTest.java | 8 +- .../querydsl/core/testutil/ThreadSafety.java | 42 +- .../core/testutil/TravisFoldListener.java | 22 +- .../querydsl/core/types/Concatenation.java | 50 +- .../querydsl/core/types/ConstantImplTest.java | 23 +- .../core/types/ConstructorExpressionTest.java | 206 +- .../core/types/DeepPopulationTest.java | 99 +- .../types/ExpressionSerializationTest.java | 27 +- .../core/types/ExpressionUtilsTest.java | 348 +- .../querydsl/core/types/ExpressivityTest.java | 976 ++-- .../core/types/JavaTemplatesTest.java | 94 +- .../core/types/MappingProjectionTest.java | 75 +- .../core/types/NestedExpressionTest.java | 70 +- .../com/querydsl/core/types/ParamTest.java | 51 +- .../core/types/PredicateOperationTest.java | 17 +- .../core/types/PredicateTemplateTest.java | 11 +- .../core/types/ProjectionExample.java | 66 +- .../querydsl/core/types/ProjectionsTest.java | 355 +- .../core/types/QBeanFieldAccessTest.java | 167 +- .../core/types/QBeanPropertyTest.java | 84 +- .../com/querydsl/core/types/QBeanTest.java | 283 +- .../com/querydsl/core/types/QListTest.java | 21 +- .../com/querydsl/core/types/QMapTest.java | 138 +- .../com/querydsl/core/types/QTupleTest.java | 189 +- .../core/types/SerializationTest.java | 135 +- .../querydsl/core/types/SignatureTest.java | 82 +- .../com/querydsl/core/types/StringTest.java | 131 +- .../types/TemplateExpressionImplTest.java | 13 +- .../core/types/TemplateInfiniteLoop.java | 57 +- .../com/querydsl/core/types/TemplateTest.java | 77 +- .../core/types/TemplatesTestUtils.java | 51 +- .../core/types/ToStringVisitorTest.java | 76 +- .../com/querydsl/core/types/TypesTest.java | 28 +- .../core/types/ValidatingVisitorTest.java | 77 +- .../com/querydsl/core/types/VisitorTest.java | 26 +- .../dsl/ArrayConstructorExpressionTest.java | 34 +- .../core/types/dsl/ArrayPathTest.java | 16 +- .../querydsl/core/types/dsl/BeanPathTest.java | 153 +- .../core/types/dsl/BooleanExpressionTest.java | 86 +- .../core/types/dsl/BooleanTemplateTest.java | 17 +- .../core/types/dsl/CaseBuilderTest.java | 204 +- .../core/types/dsl/CaseForEqBuilderTest.java | 165 +- .../querydsl/core/types/dsl/CoalesceTest.java | 133 +- .../core/types/dsl/CollectionPathTest.java | 44 +- .../types/dsl/ComparableExpressionTest.java | 19 +- .../core/types/dsl/ExpressionsTest.java | 871 ++-- .../com/querydsl/core/types/dsl/Gender.java | 5 +- .../querydsl/core/types/dsl/ListPathTest.java | 48 +- .../querydsl/core/types/dsl/MapPathTest.java | 52 +- .../core/types/dsl/NumberExpressionTest.java | 19 +- .../core/types/dsl/NumberPathTest.java | 52 +- .../core/types/dsl/OperationTest.java | 66 +- .../types/dsl/PathBuilderFactoryTest.java | 49 +- .../core/types/dsl/PathBuilderTest.java | 211 +- .../types/dsl/PathBuilderValidatorTest.java | 115 +- .../core/types/dsl/PathInitsTest.java | 61 +- .../com/querydsl/core/types/dsl/PathTest.java | 302 +- .../querydsl/core/types/dsl/QTupleTest.java | 35 +- .../querydsl/core/types/dsl/SetPathTest.java | 44 +- .../core/types/dsl/SimpleExpressionTest.java | 132 +- .../types/dsl/TemplateExpressionTest.java | 106 +- .../com/querydsl/core/types/dsl/User.java | 55 +- .../querydsl/core/util/ArrayUtilsTest.java | 12 +- .../com/querydsl/core/util/BeanMapTest.java | 199 +- .../com/querydsl/core/util/BeanUtilsTest.java | 34 +- .../core/util/ConstructorUtilsTest.java | 76 +- .../java/com/querydsl/core/util/Entity.java | 43 +- .../com/querydsl/core/util/MathUtilsTest.java | 103 +- .../querydsl/core/util/MultiIteratorTest.java | 209 +- .../NullSafeComparableComparatorTest.java | 54 +- .../core/util/ReflectionUtilsTest.java | 37 +- .../example/jpa/guice/JpaInitializer.java | 8 +- .../example/jpa/guice/ServiceModule.java | 14 +- .../example/jpa/model/BaseEntity.java | 22 +- .../example/jpa/model/Identifiable.java | 2 +- .../querydsl/example/jpa/model/Location.java | 50 +- .../com/querydsl/example/jpa/model/Tweet.java | 79 +- .../com/querydsl/example/jpa/model/User.java | 51 +- .../jpa/repository/AbstractRepository.java | 79 +- .../example/jpa/repository/Repository.java | 15 +- .../jpa/repository/TweetRepository.java | 31 +- .../jpa/repository/UserRepository.java | 31 +- .../example/jpa/guice/GuiceTestRunner.java | 18 +- .../repository/AbstractPersistenceTest.java | 75 +- .../jpa/repository/TweetRepositoryTest.java | 160 +- .../jpa/repository/UserRepositoryTest.java | 37 +- .../example/sql/guice/ConnectionContext.java | 52 +- .../example/sql/guice/ServiceModule.java | 83 +- .../sql/guice/TransactionInterceptor.java | 50 +- .../example/sql/guice/Transactional.java | 3 +- .../sql/repository/AbstractRepository.java | 50 +- .../sql/repository/TweetRepository.java | 109 +- .../example/sql/repository/UserInfo.java | 25 +- .../sql/repository/UserRepository.java | 71 +- .../sql/guice/ConnectionContextTest.java | 29 +- .../example/sql/guice/GuiceTestRunner.java | 17 +- .../repository/AbstractPersistenceTest.java | 65 +- .../sql/repository/TweetRepositoryTest.java | 150 +- .../sql/repository/UserRepositoryTest.java | 85 +- .../example/config/AppConfiguration.java | 46 +- .../example/config/JdbcConfiguration.java | 70 +- .../com/querydsl/example/dao/CustomerDao.java | 12 +- .../querydsl/example/dao/CustomerDaoImpl.java | 183 +- .../com/querydsl/example/dao/OrderDao.java | 12 +- .../querydsl/example/dao/OrderDaoImpl.java | 182 +- .../com/querydsl/example/dao/PersonDao.java | 12 +- .../querydsl/example/dao/PersonDaoImpl.java | 81 +- .../com/querydsl/example/dao/ProductDao.java | 12 +- .../querydsl/example/dao/ProductDaoImpl.java | 161 +- .../com/querydsl/example/dao/SupplierDao.java | 12 +- .../querydsl/example/dao/SupplierDaoImpl.java | 99 +- .../com/querydsl/example/dto/Address.java | 8 +- .../com/querydsl/example/dto/Customer.java | 13 +- .../querydsl/example/dto/CustomerAddress.java | 8 +- .../example/dto/CustomerPaymentMethod.java | 11 +- .../java/com/querydsl/example/dto/Order.java | 17 +- .../querydsl/example/dto/OrderDelivery.java | 6 +- .../querydsl/example/dto/OrderProduct.java | 8 +- .../java/com/querydsl/example/dto/Person.java | 6 +- .../com/querydsl/example/dto/Product.java | 16 +- .../com/querydsl/example/dto/ProductL10n.java | 8 +- .../com/querydsl/example/dto/Supplier.java | 8 +- .../example/config/TestConfiguration.java | 9 +- .../example/config/TestDataService.java | 3 +- .../example/config/TestDataServiceImpl.java | 216 +- .../querydsl/example/dao/AbstractDaoTest.java | 12 +- .../querydsl/example/dao/CustomerDaoTest.java | 59 +- .../querydsl/example/dao/OrderDaoTest.java | 82 +- .../querydsl/example/dao/PersonDaoTest.java | 65 +- .../querydsl/example/dao/ProductDaoTest.java | 75 +- .../querydsl/example/dao/SupplierDaoTest.java | 63 +- querydsl-guava/pom.xml | 130 +- .../querydsl/core/group/guava/GMultimap.java | 248 +- .../com/querydsl/core/group/guava/GOne.java | 58 +- .../com/querydsl/core/group/guava/GTable.java | 272 +- .../core/group/guava/GroupByMultimap.java | 74 +- .../core/group/guava/GroupByTable.java | 83 +- .../core/group/guava/GuavaGroupBy.java | 871 ++-- .../core/group/guava/GuavaGroupByBuilder.java | 322 +- .../core/group/guava/package-info.java | 5 +- querydsl-hibernate-search/pom.xml | 73 +- .../hibernate/search/AbstractSearchQuery.java | 272 +- .../hibernate/search/SearchQuery.java | 41 +- .../hibernate/search/SearchSerializer.java | 46 +- .../hibernate/search/package-info.java | 4 +- .../hibernate/search/AbstractQueryTest.java | 89 +- .../com/querydsl/hibernate/search/QUser.java | 17 +- .../hibernate/search/SearchQueryTest.java | 287 +- .../search/SearchSerializerTest.java | 15 +- .../com/querydsl/hibernate/search/User.java | 90 +- querydsl-jdo/pom.xml | 189 +- .../com/querydsl/jdo/AbstractJDOQuery.java | 541 +- .../java/com/querydsl/jdo/JDOExpressions.java | 136 +- .../java/com/querydsl/jdo/JDOQLQuery.java | 99 +- .../com/querydsl/jdo/JDOQLSerializer.java | 523 +- .../java/com/querydsl/jdo/JDOQLTemplates.java | 56 +- .../main/java/com/querydsl/jdo/JDOQuery.java | 155 +- .../com/querydsl/jdo/JDOQueryFactory.java | 187 +- .../java/com/querydsl/jdo/JDOQueryMixin.java | 64 +- .../com/querydsl/jdo/dml/JDODeleteClause.java | 130 +- .../com/querydsl/jdo/dml/JDOUpdateClause.java | 103 +- .../com/querydsl/jdo/dml/package-info.java | 4 +- .../java/com/querydsl/jdo/package-info.java | 4 +- .../querydsl/jdo/sql/AbstractSQLQuery.java | 355 +- .../com/querydsl/jdo/sql/JDOSQLQuery.java | 81 +- .../com/querydsl/jdo/sql/package-info.java | 4 +- .../com/querydsl/jdo/AbstractJDOTest.java | 138 +- .../java/com/querydsl/jdo/AggregateTest.java | 64 +- .../java/com/querydsl/jdo/BasicsTest.java | 549 +- .../java/com/querydsl/jdo/CollectionTest.java | 143 +- .../com/querydsl/jdo/DependenciesTest.java | 28 +- .../java/com/querydsl/jdo/FetchPlanTest.java | 116 +- .../java/com/querydsl/jdo/GroupByTest.java | 85 +- .../com/querydsl/jdo/JDOQLMethodsTest.java | 128 +- .../com/querydsl/jdo/JDOQLTemplatesTest.java | 99 +- .../com/querydsl/jdo/JDOQueryFactoryTest.java | 53 +- .../querydsl/jdo/JDOQueryStandardTest.java | 313 +- .../com/querydsl/jdo/JDOSQLQueryTest.java | 243 +- .../java/com/querydsl/jdo/OrderingTest.java | 178 +- .../com/querydsl/jdo/PackageVerification.java | 53 +- .../com/querydsl/jdo/QueryMutabilityTest.java | 47 +- .../java/com/querydsl/jdo/SubqueriesTest.java | 220 +- .../java/com/querydsl/jdo/TemplatesTest.java | 4 +- .../querydsl/jdo/models/company/Account.java | 45 +- .../jdo/models/company/Department.java | 79 +- .../jdo/models/company/Developer.java | 48 +- .../jdo/models/company/DeveloperRC.java | 85 +- .../querydsl/jdo/models/company/Employee.java | 176 +- .../models/company/InsuranceDepartment.java | 37 +- .../querydsl/jdo/models/company/Manager.java | 81 +- .../querydsl/jdo/models/company/Office.java | 282 +- .../jdo/models/company/Organisation.java | 20 +- .../querydsl/jdo/models/company/Person.java | 304 +- .../jdo/models/company/PersonHolder.java | 166 +- .../querydsl/jdo/models/company/PersonRC.java | 129 +- .../jdo/models/company/PersonalDetails.java | 139 +- .../jdo/models/company/PhoneNumber.java | 41 +- .../querydsl/jdo/models/company/Project.java | 41 +- .../jdo/models/company/Qualification.java | 78 +- .../querydsl/jdo/models/fitness/Cloth.java | 14 +- .../com/querydsl/jdo/models/fitness/Gym.java | 313 +- .../jdo/models/fitness/GymEquipment.java | 38 +- .../querydsl/jdo/models/fitness/Wardrobe.java | 65 +- .../jdo/serialization/AbstractTest.java | 13 +- .../jdo/serialization/ContainerTest.java | 292 +- .../serialization/ExprSerializationTest.java | 216 +- .../jdo/serialization/GroupByTest.java | 29 +- .../serialization/QuerySerializationTest.java | 166 +- .../jdo/serialization/SubqueriesTest.java | 179 +- .../com/querydsl/jdo/test/domain/Book.java | 94 +- .../com/querydsl/jdo/test/domain/Product.java | 139 +- .../com/querydsl/jdo/test/domain/QBook.java | 43 +- .../querydsl/jdo/test/domain/QProduct.java | 41 +- .../com/querydsl/jdo/test/domain/QStore.java | 48 +- .../com/querydsl/jdo/test/domain/Store.java | 58 +- .../querydsl/jdo/test/domain/sql/SBook.java | 43 +- .../jdo/test/domain/sql/SProduct.java | 89 +- .../querydsl/jdo/test/domain/sql/SStore.java | 43 +- .../jdo/test/domain/sql/SStoreProducts.java | 45 +- .../test/domain/sql/SStoreProductsbyname.java | 46 +- querydsl-jpa-codegen/pom.xml | 30 +- .../jpa/codegen/AbstractDomainExporter.java | 516 +- .../com/querydsl/jpa/codegen/Constants.java | 102 +- .../jpa/codegen/JPADomainExporter.java | 373 +- .../jpa/codegen/ant/AntJPADomainExporter.java | 225 +- .../jpa/codegen/ant/package-info.java | 4 +- .../querydsl/jpa/codegen/package-info.java | 4 +- .../jpa/codegen/JPADomainExporterTest.java | 47 +- .../codegen/ant/AntJPADomainExporterTest.java | 53 +- querydsl-jpa/pom.xml | 182 +- .../com/querydsl/jpa/AbstractSQLQuery.java | 56 +- .../java/com/querydsl/jpa/BatooTemplates.java | 34 +- .../java/com/querydsl/jpa/Conversions.java | 162 +- .../querydsl/jpa/DataNucleusTemplates.java | 41 +- .../com/querydsl/jpa/DefaultQueryHandler.java | 93 +- .../com/querydsl/jpa/EclipseLinkHandler.java | 171 +- .../querydsl/jpa/EclipseLinkTemplates.java | 129 +- .../jpa/FactoryExpressionTransformer.java | 40 +- .../java/com/querydsl/jpa/HQLTemplates.java | 170 +- .../com/querydsl/jpa/Hibernate5Templates.java | 34 +- .../com/querydsl/jpa/HibernateHandler.java | 118 +- .../querydsl/jpa/JPACollectionAnyVisitor.java | 76 +- .../java/com/querydsl/jpa/JPAExpressions.java | 315 +- .../querydsl/jpa/JPAListAccessVisitor.java | 120 +- .../com/querydsl/jpa/JPAMapAccessVisitor.java | 165 +- .../java/com/querydsl/jpa/JPAQueryBase.java | 402 +- .../java/com/querydsl/jpa/JPAQueryMixin.java | 364 +- .../java/com/querydsl/jpa/JPASubQuery.java | 97 +- .../main/java/com/querydsl/jpa/JPQLOps.java | 33 +- .../main/java/com/querydsl/jpa/JPQLQuery.java | 584 ++- .../com/querydsl/jpa/JPQLQueryFactory.java | 174 +- .../java/com/querydsl/jpa/JPQLSerializer.java | 1007 ++-- .../java/com/querydsl/jpa/JPQLTemplates.java | 407 +- .../com/querydsl/jpa/NativeSQLSerializer.java | 365 +- .../com/querydsl/jpa/OpenJPATemplates.java | 22 +- .../java/com/querydsl/jpa/QueryHandler.java | 108 +- .../jpa/ScrollableResultsIterator.java | 84 +- .../querydsl/jpa/TransformingIterator.java | 96 +- .../jpa/hibernate/AbstractHibernateQuery.java | 642 ++- .../jpa/hibernate/DefaultSessionHolder.java | 30 +- .../jpa/hibernate/HibernateDeleteClause.java | 109 +- .../jpa/hibernate/HibernateInsertClause.java | 234 +- .../jpa/hibernate/HibernateQuery.java | 167 +- .../jpa/hibernate/HibernateQueryFactory.java | 178 +- .../jpa/hibernate/HibernateUpdateClause.java | 206 +- .../querydsl/jpa/hibernate/HibernateUtil.java | 136 +- .../jpa/hibernate/NoSessionHolder.java | 24 +- .../querydsl/jpa/hibernate/SessionHolder.java | 32 +- .../jpa/hibernate/StatelessSessionHolder.java | 30 +- .../querydsl/jpa/hibernate/package-info.java | 4 +- .../sql/AbstractHibernateSQLQuery.java | 506 +- .../jpa/hibernate/sql/HibernateSQLQuery.java | 90 +- .../jpa/hibernate/sql/package-info.java | 5 +- .../querydsl/jpa/impl/AbstractJPAQuery.java | 681 +-- .../querydsl/jpa/impl/JPADeleteClause.java | 89 +- .../querydsl/jpa/impl/JPAInsertClause.java | 203 +- .../com/querydsl/jpa/impl/JPAProvider.java | 127 +- .../java/com/querydsl/jpa/impl/JPAQuery.java | 135 +- .../querydsl/jpa/impl/JPAQueryFactory.java | 221 +- .../querydsl/jpa/impl/JPAUpdateClause.java | 183 +- .../java/com/querydsl/jpa/impl/JPAUtil.java | 61 +- .../com/querydsl/jpa/impl/package-info.java | 4 +- .../java/com/querydsl/jpa/package-info.java | 4 +- .../querydsl/jpa/sql/AbstractJPASQLQuery.java | 541 +- .../com/querydsl/jpa/sql/JPASQLQuery.java | 92 +- .../com/querydsl/jpa/sql/package-info.java | 4 +- .../querydsl/jpa/support/DialectSupport.java | 79 +- .../jpa/support/JPAPathBuilderValidator.java | 49 +- .../querydsl/jpa/support/QDerbyDialect.java | 41 +- .../com/querydsl/jpa/support/QH2Dialect.java | 16 +- .../querydsl/jpa/support/QHSQLDialect.java | 17 +- .../jpa/support/QMySQL57InnoDBDialect.java | 15 +- .../querydsl/jpa/support/QMySQL5Dialect.java | 15 +- .../jpa/support/QMySQL5InnoDBDialect.java | 16 +- .../jpa/support/QOracle10gDialect.java | 15 +- .../jpa/support/QPostgreSQL9Dialect.java | 15 +- .../jpa/support/QPostgreSQLDialect.java | 15 +- .../jpa/support/QSQLServer2005Dialect.java | 19 +- .../jpa/support/QSQLServer2008Dialect.java | 19 +- .../jpa/support/QSQLServer2012Dialect.java | 19 +- .../querydsl/jpa/support/package-info.java | 4 +- .../src/test/java/PackagelessEntityTest.java | 20 +- .../com/querydsl/jpa/AbstractJPATest.java | 3878 +++++++------- .../com/querydsl/jpa/AbstractQueryTest.java | 25 +- .../com/querydsl/jpa/AbstractSQLTest.java | 784 +-- .../com/querydsl/jpa/AggregationTest.java | 49 +- .../test/java/com/querydsl/jpa/Article.java | 8 +- .../querydsl/jpa/BooleanOperationsTest.java | 161 +- .../test/java/com/querydsl/jpa/CastTest.java | 75 +- .../java/com/querydsl/jpa/CollectionTest.java | 42 +- .../java/com/querydsl/jpa/ComparableTest.java | 62 +- .../test/java/com/querydsl/jpa/Constants.java | 149 +- .../com/querydsl/jpa/ConstructorsTest.java | 43 +- .../test/java/com/querydsl/jpa/Content.java | 4 +- .../querydsl/jpa/CustomExpressionsTest.java | 23 +- .../java/com/querydsl/jpa/CustomFinder.java | 40 +- .../java/com/querydsl/jpa/DateTimeTest.java | 73 +- .../com/querydsl/jpa/DependenciesTest.java | 30 +- .../com/querydsl/jpa/DummySessionHolder.java | 22 +- .../test/java/com/querydsl/jpa/EJBQLTest.java | 57 +- .../jpa/ExpressionSerializationTest.java | 29 +- .../java/com/querydsl/jpa/ExtDoubleType.java | 8 +- .../java/com/querydsl/jpa/FeaturesTest.java | 291 +- .../java/com/querydsl/jpa/HibernateBase.java | 255 +- .../querydsl/jpa/HibernateHandlerTest.java | 272 +- .../jpa/HibernateQueryFactoryTest.java | 73 +- .../jpa/HibernateQueryMutabilityTest.java | 65 +- .../com/querydsl/jpa/HibernateQueryTest.java | 39 +- .../com/querydsl/jpa/HibernateSQLBase.java | 105 +- .../java/com/querydsl/jpa/HibernateTest.java | 3 +- .../com/querydsl/jpa/IntegrationBase.java | 332 +- .../test/java/com/querydsl/jpa/JPABase.java | 537 +- .../jpa/JPACollectionAnyVisitorTest.java | 217 +- .../com/querydsl/jpa/JPAIntegrationBase.java | 82 +- .../com/querydsl/jpa/JPAProviderRule.java | 57 +- .../com/querydsl/jpa/JPAProviderTest.java | 160 +- .../com/querydsl/jpa/JPAQueryFactoryTest.java | 250 +- .../com/querydsl/jpa/JPAQueryMixinTest.java | 426 +- .../querydsl/jpa/JPAQueryMutability2Test.java | 181 +- .../querydsl/jpa/JPAQueryMutabilityTest.java | 76 +- .../java/com/querydsl/jpa/JPASQLBase.java | 226 +- .../test/java/com/querydsl/jpa/JPATest.java | 3 +- .../java/com/querydsl/jpa/JPQLQueryTest.java | 84 +- .../com/querydsl/jpa/JPQLSerializerTest.java | 589 ++- .../com/querydsl/jpa/JPQLTemplatesTest.java | 130 +- .../java/com/querydsl/jpa/JoinFlagsTest.java | 46 +- .../test/java/com/querydsl/jpa/JoinTest.java | 112 +- .../com/querydsl/jpa/MapOperationsTest.java | 21 +- .../test/java/com/querydsl/jpa/MathTest.java | 177 +- .../src/test/java/com/querydsl/jpa/Mode.java | 46 +- .../querydsl/jpa/NativeSQLSerializerTest.java | 79 +- .../java/com/querydsl/jpa/NoBatooJPA.java | 2 +- .../java/com/querydsl/jpa/NoEclipseLink.java | 2 +- .../java/com/querydsl/jpa/NoHibernate.java | 2 +- .../test/java/com/querydsl/jpa/NoOpenJPA.java | 2 +- .../querydsl/jpa/OrderExpressionsTest.java | 11 +- .../java/com/querydsl/jpa/OrderHelper.java | 90 +- .../com/querydsl/jpa/OrderHelperTest.java | 58 +- .../com/querydsl/jpa/PackageVerification.java | 68 +- .../java/com/querydsl/jpa/ParsingTest.java | 1380 ++--- .../test/java/com/querydsl/jpa/Person.java | 3 +- .../java/com/querydsl/jpa/Projection.java | 7 +- .../test/java/com/querydsl/jpa/QArticle.java | 62 +- .../test/java/com/querydsl/jpa/QContent.java | 56 +- .../test/java/com/querydsl/jpa/QPerson.java | 36 +- .../java/com/querydsl/jpa/QProjection.java | 19 +- .../com/querydsl/jpa/QueryHandlerTest.java | 14 +- .../java/com/querydsl/jpa/QueryHelper.java | 169 +- .../com/querydsl/jpa/QueryMutabilityTest.java | 69 +- .../querydsl/jpa/QueryPerformanceTest.java | 166 +- .../jpa/RelationalFunctionCallTest.java | 61 +- .../com/querydsl/jpa/SerializationBase.java | 137 +- .../java/com/querydsl/jpa/SignatureTest.java | 22 +- .../querydsl/jpa/StringOperationsTest.java | 67 +- .../java/com/querydsl/jpa/SubQueryTest.java | 333 +- .../java/com/querydsl/jpa/TargetRule.java | 48 +- .../java/com/querydsl/jpa/TemplatesTest.java | 4 +- .../test/java/com/querydsl/jpa/TupleTest.java | 42 +- .../java/com/querydsl/jpa/TypeCastTest.java | 86 +- .../com/querydsl/jpa/UniqueResultsTest.java | 60 +- .../java/com/querydsl/jpa/domain/Account.java | 60 +- .../java/com/querydsl/jpa/domain/Animal.java | 176 +- .../com/querydsl/jpa/domain/AuditLog.java | 10 +- .../java/com/querydsl/jpa/domain/Author.java | 51 +- .../java/com/querydsl/jpa/domain/Bar.java | 11 +- .../java/com/querydsl/jpa/domain/Book.java | 51 +- .../com/querydsl/jpa/domain/Calendar.java | 18 +- .../java/com/querydsl/jpa/domain/Cat.java | 184 +- .../com/querydsl/jpa/domain/CatSummary.java | 41 +- .../java/com/querydsl/jpa/domain/Catalog.java | 15 +- .../java/com/querydsl/jpa/domain/Child.java | 7 +- .../java/com/querydsl/jpa/domain/Color.java | 7 +- .../java/com/querydsl/jpa/domain/Company.java | 37 +- .../com/querydsl/jpa/domain/Customer.java | 13 +- .../com/querydsl/jpa/domain/Department.java | 20 +- .../com/querydsl/jpa/domain/Document.java | 14 +- .../java/com/querydsl/jpa/domain/Dolphin.java | 4 +- .../java/com/querydsl/jpa/domain/Domain.java | 139 +- .../com/querydsl/jpa/domain/DomesticCat.java | 8 +- .../querydsl/jpa/domain/DoubleProjection.java | 11 +- .../com/querydsl/jpa/domain/EmbeddedType.java | 4 +- .../com/querydsl/jpa/domain/Employee.java | 25 +- .../java/com/querydsl/jpa/domain/Entity1.java | 13 +- .../java/com/querydsl/jpa/domain/Entity2.java | 10 +- .../com/querydsl/jpa/domain/EvilType.java | 26 +- .../java/com/querydsl/jpa/domain/Family.java | 10 +- .../querydsl/jpa/domain/FloatProjection.java | 11 +- .../java/com/querydsl/jpa/domain/Foo.java | 25 +- .../java/com/querydsl/jpa/domain/FooDTO.java | 29 +- .../java/com/querydsl/jpa/domain/Formula.java | 23 +- .../java/com/querydsl/jpa/domain/Group.java | 5 +- .../java/com/querydsl/jpa/domain/Human.java | 5 +- .../jpa/domain/InheritedProperties.java | 5 +- .../java/com/querydsl/jpa/domain/Item.java | 10 +- .../com/querydsl/jpa/domain/JobFunction.java | 9 +- .../com/querydsl/jpa/domain/Location.java | 9 +- .../java/com/querydsl/jpa/domain/Mammal.java | 4 +- .../java/com/querydsl/jpa/domain/Name.java | 9 +- .../com/querydsl/jpa/domain/NameList.java | 11 +- .../java/com/querydsl/jpa/domain/Named.java | 9 +- .../com/querydsl/jpa/domain/Nationality.java | 11 +- .../java/com/querydsl/jpa/domain/Novel.java | 3 +- .../java/com/querydsl/jpa/domain/Numeric.java | 34 +- .../java/com/querydsl/jpa/domain/Order.java | 41 +- .../com/querydsl/jpa/domain/Parameter.java | 7 +- .../java/com/querydsl/jpa/domain/Parent.java | 9 +- .../java/com/querydsl/jpa/domain/Payment.java | 14 +- .../querydsl/jpa/domain/PaymentStatus.java | 6 +- .../java/com/querydsl/jpa/domain/Person.java | 26 +- .../com/querydsl/jpa/domain/PersonId.java | 12 +- .../java/com/querydsl/jpa/domain/Player.java | 11 +- .../java/com/querydsl/jpa/domain/Price.java | 13 +- .../java/com/querydsl/jpa/domain/Product.java | 8 +- .../java/com/querydsl/jpa/domain/Show.java | 26 +- .../com/querydsl/jpa/domain/SimpleTypes.java | 50 +- .../java/com/querydsl/jpa/domain/Status.java | 9 +- .../com/querydsl/jpa/domain/StatusChange.java | 11 +- .../java/com/querydsl/jpa/domain/Store.java | 14 +- .../com/querydsl/jpa/domain/Superclass.java | 22 +- .../java/com/querydsl/jpa/domain/User.java | 12 +- .../java/com/querydsl/jpa/domain/World.java | 8 +- .../com/querydsl/jpa/domain/package-info.java | 2 +- .../com/querydsl/jpa/domain/sql/SAccount.java | 67 +- .../com/querydsl/jpa/domain/sql/SAnimal.java | 144 +- .../querydsl/jpa/domain/sql/SAuditlog.java | 63 +- .../com/querydsl/jpa/domain/sql/SAuthor.java | 63 +- .../com/querydsl/jpa/domain/sql/SBar.java | 60 +- .../com/querydsl/jpa/domain/sql/SBook.java | 72 +- .../jpa/domain/sql/SBookBookmarks.java | 123 +- .../com/querydsl/jpa/domain/sql/SBookid.java | 60 +- .../querydsl/jpa/domain/sql/SBookversion.java | 88 +- .../querydsl/jpa/domain/sql/SCalendar.java | 62 +- .../jpa/domain/sql/SCalendarHolidays.java | 73 +- .../com/querydsl/jpa/domain/sql/SCatalog.java | 65 +- .../jpa/domain/sql/SCatalog_price.java | 70 +- .../querydsl/jpa/domain/sql/SCategory.java | 114 +- .../jpa/domain/sql/SCategory_category.java | 70 +- .../domain/sql/SCategory_categoryprop.java | 75 +- .../jpa/domain/sql/SCategoryprop.java | 76 +- .../com/querydsl/jpa/domain/sql/SChild2.java | 63 +- .../com/querydsl/jpa/domain/sql/SCompany.java | 89 +- .../jpa/domain/sql/SCompany_department.java | 69 +- .../querydsl/jpa/domain/sql/SCustomer.java | 78 +- .../querydsl/jpa/domain/sql/SDateTest.java | 54 +- .../querydsl/jpa/domain/sql/SDepartment.java | 73 +- .../jpa/domain/sql/SDepartment_employee.java | 72 +- .../querydsl/jpa/domain/sql/SDocument.java | 64 +- .../querydsl/jpa/domain/sql/SDocument2.java | 164 +- .../jpa/domain/sql/SDocumentprop.java | 76 +- .../querydsl/jpa/domain/sql/SEmployee.java | 87 +- .../jpa/domain/sql/SEmployeeJobFunctions.java | 68 +- .../com/querydsl/jpa/domain/sql/SEntity1.java | 69 +- .../querydsl/jpa/domain/sql/SEviltype.java | 192 +- .../com/querydsl/jpa/domain/sql/SFoo.java | 67 +- .../querydsl/jpa/domain/sql/SFooNames.java | 61 +- .../com/querydsl/jpa/domain/sql/SFormula.java | 64 +- .../jpa/domain/sql/SGeneratedKeys.java | 60 +- .../querydsl/jpa/domain/sql/SHumanHairs.java | 62 +- .../jpa/domain/sql/SInheritedproperties.java | 77 +- .../com/querydsl/jpa/domain/sql/SItem.java | 111 +- .../jpa/domain/sql/SItem_statuschange.java | 68 +- .../com/querydsl/jpa/domain/sql/SKittens.java | 72 +- .../querydsl/jpa/domain/sql/SKittensSet.java | 68 +- .../com/querydsl/jpa/domain/sql/SLibrary.java | 60 +- .../querydsl/jpa/domain/sql/SLineItems.java | 74 +- .../querydsl/jpa/domain/sql/SLocation.java | 63 +- .../com/querydsl/jpa/domain/sql/SMammal.java | 67 +- .../com/querydsl/jpa/domain/sql/SName.java | 71 +- .../jpa/domain/sql/SNameListNames.java | 63 +- .../com/querydsl/jpa/domain/sql/SNamed.java | 60 +- .../querydsl/jpa/domain/sql/SNamelist.java | 59 +- .../querydsl/jpa/domain/sql/SNationality.java | 67 +- .../com/querydsl/jpa/domain/sql/SNumeric.java | 68 +- .../com/querydsl/jpa/domain/sql/SOrder.java | 80 +- .../sql/SOrderDeliveredItemIndices.java | 78 +- .../querydsl/jpa/domain/sql/SOrder_item.java | 74 +- .../querydsl/jpa/domain/sql/SParameter.java | 59 +- .../com/querydsl/jpa/domain/sql/SParent.java | 64 +- .../com/querydsl/jpa/domain/sql/SParent2.java | 59 +- .../com/querydsl/jpa/domain/sql/SPerson.java | 82 +- .../querydsl/jpa/domain/sql/SPersonid.java | 69 +- .../com/querydsl/jpa/domain/sql/SPlayer.java | 59 +- .../jpa/domain/sql/SPlayerScores.java | 62 +- .../com/querydsl/jpa/domain/sql/SPrice.java | 71 +- .../com/querydsl/jpa/domain/sql/SShapes.java | 60 +- .../com/querydsl/jpa/domain/sql/SShow.java | 59 +- .../querydsl/jpa/domain/sql/SShowActs.java | 69 +- .../querydsl/jpa/domain/sql/SSimpletypes.java | 145 +- .../com/querydsl/jpa/domain/sql/SStatus.java | 66 +- .../jpa/domain/sql/SStatuschange.java | 64 +- .../com/querydsl/jpa/domain/sql/SStore.java | 67 +- .../jpa/domain/sql/SStore_customer.java | 67 +- .../com/querydsl/jpa/domain/sql/SSurvey.java | 64 +- .../com/querydsl/jpa/domain/sql/STest.java | 54 +- .../querydsl/jpa/domain/sql/STimeTest.java | 54 +- .../com/querydsl/jpa/domain/sql/SUser.java | 78 +- .../com/querydsl/jpa/domain/sql/SUser2.java | 117 +- .../jpa/domain/sql/SUser2_userprop.java | 70 +- .../querydsl/jpa/domain/sql/SUserprop.java | 111 +- .../jpa/domain/sql/SUserprop_category.java | 72 +- .../domain/sql/SUserprop_categoryprop.java | 75 +- .../com/querydsl/jpa/domain/sql/SWorld.java | 59 +- .../querydsl/jpa/domain/sql/SWorldMammal.java | 70 +- .../com/querydsl/jpa/domain2/Category.java | 169 +- .../querydsl/jpa/domain2/CategoryProp.java | 58 +- .../java/com/querydsl/jpa/domain2/Child.java | 16 +- .../com/querydsl/jpa/domain2/Contact.java | 53 +- .../com/querydsl/jpa/domain2/Document2.java | 192 +- .../querydsl/jpa/domain2/DocumentProp.java | 68 +- .../com/querydsl/jpa/domain2/Domain2.java | 20 +- .../java/com/querydsl/jpa/domain2/Parent.java | 45 +- .../java/com/querydsl/jpa/domain2/User2.java | 185 +- .../com/querydsl/jpa/domain2/UserProp.java | 164 +- .../querydsl/jpa/domain3/HardwareStore.java | 17 +- .../java/com/querydsl/jpa/domain3/Store.java | 117 +- .../querydsl/jpa/domain4/BookDefinition.java | 58 +- .../java/com/querydsl/jpa/domain4/BookID.java | 24 +- .../com/querydsl/jpa/domain4/BookMark.java | 36 +- .../com/querydsl/jpa/domain4/BookVersion.java | 74 +- .../querydsl/jpa/domain4/BookVersionPK.java | 34 +- .../com/querydsl/jpa/domain4/Library.java | 24 +- .../jpa/domain5/MyEmbeddedAttribute.java | 5 +- .../com/querydsl/jpa/domain5/MyEntity.java | 14 +- .../jpa/domain5/MyMappedSuperclass.java | 4 +- .../querydsl/jpa/domain5/MyOtherEntity.java | 3 +- .../querydsl/jpa/suites/AbstractJPASuite.java | 14 +- .../querydsl/jpa/suites/AbstractSuite.java | 14 +- .../jpa/suites/DerbyEclipseLinkTest.java | 61 +- .../querydsl/jpa/suites/DerbySuiteTest.java | 31 +- .../com/querydsl/jpa/suites/H2BatooTest.java | 27 +- .../jpa/suites/H2EclipseLinkTest.java | 25 +- .../querydsl/jpa/suites/H2OpenJPATest.java | 27 +- .../com/querydsl/jpa/suites/H2SuiteTest.java | 31 +- .../jpa/suites/HSQLDBEclipseLinkTest.java | 25 +- .../querydsl/jpa/suites/HSQLDBSuiteTest.java | 31 +- .../querydsl/jpa/suites/MSSQLSuiteTest.java | 31 +- .../jpa/suites/MySQLEclipseLinkTest.java | 99 +- .../querydsl/jpa/suites/MySQLSuiteTest.java | 47 +- .../querydsl/jpa/suites/OracleSuiteTest.java | 63 +- .../PostgreSQLEclipseLinkSuiteTest.java | 25 +- .../jpa/suites/PostgreSQLSuiteTest.java | 31 +- .../jpa/support/DialectSupportTest.java | 17 +- .../support/JPAPathBuilderValidatorTest.java | 48 +- .../querydsl/jpa/support/TeradataDialect.java | 635 ++- .../jpa/testutil/HibernateTestRunner.java | 196 +- .../querydsl/jpa/testutil/JPATestRunner.java | 178 +- querydsl-kotlin-codegen/pom.xml | 182 +- querydsl-kotlin/pom.xml | 253 +- querydsl-lucene3/pom.xml | 34 +- .../querydsl/lucene3/AbstractLuceneQuery.java | 563 +- .../IgnoreCaseUnsupportedException.java | 10 +- .../querydsl/lucene3/LuceneExpressions.java | 84 +- .../java/com/querydsl/lucene3/LuceneOps.java | 23 +- .../com/querydsl/lucene3/LuceneQuery.java | 25 +- .../querydsl/lucene3/LuceneSerializer.java | 1039 ++-- .../com/querydsl/lucene3/PhraseElement.java | 12 +- .../com/querydsl/lucene3/QueryElement.java | 13 +- .../com/querydsl/lucene3/ResultIterator.java | 88 +- .../com/querydsl/lucene3/TermElement.java | 10 +- .../java/com/querydsl/lucene3/TypedQuery.java | 46 +- .../com/querydsl/lucene3/package-info.java | 4 +- .../com/querydsl/lucene3/LuceneQueryTest.java | 1397 +++-- .../LuceneSerializerNotTokenizedTest.java | 349 +- .../lucene3/LuceneSerializerTest.java | 1266 ++--- .../java/com/querydsl/lucene3/Person.java | 47 +- .../querydsl/lucene3/PhraseElementTest.java | 51 +- .../java/com/querydsl/lucene3/QDocument.java | 20 +- .../querydsl/lucene3/QueryElementTest.java | 18 +- .../com/querydsl/lucene3/TermElementTest.java | 35 +- querydsl-lucene4/pom.xml | 32 +- .../querydsl/lucene4/AbstractLuceneQuery.java | 573 +- .../IgnoreCaseUnsupportedException.java | 10 +- .../querydsl/lucene4/LuceneExpressions.java | 85 +- .../java/com/querydsl/lucene4/LuceneOps.java | 23 +- .../com/querydsl/lucene4/LuceneQuery.java | 27 +- .../querydsl/lucene4/LuceneSerializer.java | 1046 ++-- .../com/querydsl/lucene4/PhraseElement.java | 12 +- .../com/querydsl/lucene4/QueryElement.java | 13 +- .../com/querydsl/lucene4/ResultIterator.java | 90 +- .../com/querydsl/lucene4/TermElement.java | 10 +- .../java/com/querydsl/lucene4/TypedQuery.java | 46 +- .../com/querydsl/lucene4/package-info.java | 4 +- .../com/querydsl/lucene4/LuceneQueryTest.java | 1404 +++-- .../LuceneSerializerNotTokenizedTest.java | 349 +- .../lucene4/LuceneSerializerTest.java | 1276 ++--- .../java/com/querydsl/lucene4/Person.java | 47 +- .../querydsl/lucene4/PhraseElementTest.java | 51 +- .../java/com/querydsl/lucene4/QDocument.java | 20 +- .../querydsl/lucene4/QueryElementTest.java | 18 +- .../com/querydsl/lucene4/TermElementTest.java | 35 +- querydsl-lucene5/pom.xml | 12 +- .../querydsl/lucene5/AbstractLuceneQuery.java | 642 ++- .../IgnoreCaseUnsupportedException.java | 13 +- .../querydsl/lucene5/LuceneExpressions.java | 102 +- .../java/com/querydsl/lucene5/LuceneOps.java | 21 +- .../com/querydsl/lucene5/LuceneQuery.java | 34 +- .../querydsl/lucene5/LuceneSerializer.java | 1086 ++-- .../com/querydsl/lucene5/PhraseElement.java | 10 +- .../com/querydsl/lucene5/QueryElement.java | 13 +- .../com/querydsl/lucene5/ResultIterator.java | 94 +- .../com/querydsl/lucene5/TermElement.java | 10 +- .../java/com/querydsl/lucene5/TypedQuery.java | 55 +- .../com/querydsl/lucene5/package-info.java | 5 +- .../com/querydsl/lucene5/LuceneQueryTest.java | 1537 +++--- .../LuceneSerializerNotTokenizedTest.java | 371 +- .../lucene5/LuceneSerializerTest.java | 1367 +++-- .../java/com/querydsl/lucene5/Person.java | 37 +- .../querydsl/lucene5/PhraseElementTest.java | 59 +- .../java/com/querydsl/lucene5/QDocument.java | 20 +- .../querydsl/lucene5/QueryElementTest.java | 22 +- .../com/querydsl/lucene5/TermElementTest.java | 45 +- querydsl-maven-plugin/pom.xml | 274 +- .../querydsl/maven/AbstractExporterMojo.java | 420 +- .../maven/AbstractMetaDataExportMojo.java | 1323 ++--- .../java/com/querydsl/maven/CompileMojo.java | 365 +- .../querydsl/maven/GenericExporterMojo.java | 4 +- .../com/querydsl/maven/JDOExporterMojo.java | 24 +- .../com/querydsl/maven/JPAExporterMojo.java | 27 +- .../maven/JPATemporalAnnotationHelper.java | 59 +- .../querydsl/maven/MetadataExportMojo.java | 13 +- .../maven/TestMetadataExportMojo.java | 13 +- .../java/com/querydsl/maven/package-info.java | 4 +- .../com/querydsl/maven/CompileMojoTest.java | 24 +- .../test/java/com/querydsl/maven/Entity.java | 10 +- .../maven/GenericExporterMojoTest.java | 95 +- .../querydsl/maven/JDOExporterMojoTest.java | 34 +- .../querydsl/maven/JPAExporterMojoTest.java | 34 +- .../maven/MetadataExportMojoTest.java | 693 +-- .../maven/TestMetadataExportMojoTest.java | 110 +- querydsl-mongodb/pom.xml | 19 +- .../mongodb/AbstractMongodbQuery.java | 798 +-- .../querydsl/mongodb/AnyEmbeddedBuilder.java | 27 +- .../com/querydsl/mongodb/JoinBuilder.java | 30 +- .../querydsl/mongodb/MongodbExpressions.java | 133 +- .../java/com/querydsl/mongodb/MongodbOps.java | 30 +- .../querydsl/mongodb/MongodbSerializer.java | 667 +-- .../main/java/com/querydsl/mongodb/Point.java | 54 +- .../AbstractFetchableMongodbQuery.java | 485 +- .../document/AbstractMongodbQuery.java | 406 +- .../mongodb/document/AnyEmbeddedBuilder.java | 26 +- .../mongodb/document/JoinBuilder.java | 29 +- .../document/MongodbDocumentSerializer.java | 685 +-- .../mongodb/document/MongodbExpressions.java | 55 +- .../mongodb/document/package-info.java | 4 +- .../mongodb/morphia/MorphiaQuery.java | 81 +- .../mongodb/morphia/MorphiaSerializer.java | 126 +- .../mongodb/morphia/package-info.java | 4 +- .../com/querydsl/mongodb/package-info.java | 4 +- .../querydsl/mongodb/GeoSpatialQueryTest.java | 155 +- .../java/com/querydsl/mongodb/JoinTest.java | 381 +- .../querydsl/mongodb/MongodbQueryTest.java | 1354 ++--- .../mongodb/MongodbSerializerTest.java | 543 +- .../querydsl/mongodb/PackageVerification.java | 56 +- .../mongodb/PolymorphicCollectionTest.java | 128 +- .../MongodbDocumentSerializerTest.java | 513 +- .../mongodb/document/MongodbQueryTest.java | 1401 ++--- .../mongodb/domain/AbstractEntity.java | 76 +- .../com/querydsl/mongodb/domain/Address.java | 20 +- .../com/querydsl/mongodb/domain/Chips.java | 6 +- .../com/querydsl/mongodb/domain/City.java | 20 +- .../com/querydsl/mongodb/domain/Country.java | 28 +- .../com/querydsl/mongodb/domain/Dates.java | 16 +- .../querydsl/mongodb/domain/DummyEntity.java | 17 +- .../com/querydsl/mongodb/domain/Fish.java | 24 +- .../com/querydsl/mongodb/domain/Food.java | 14 +- .../querydsl/mongodb/domain/GeoEntity.java | 25 +- .../com/querydsl/mongodb/domain/Item.java | 16 +- .../mongodb/domain/LocaleConverter.java | 46 +- .../querydsl/mongodb/domain/MapEntity.java | 17 +- .../com/querydsl/mongodb/domain/Person.java | 11 +- .../com/querydsl/mongodb/domain/User.java | 221 +- .../com/querydsl/mongodb/domain/UserTest.java | 53 +- .../querydsl/mongodb/domain/package-info.java | 1 - .../com/querydsl/mongodb/domain2/User.java | 7 +- .../mongodb/domain2/UserAttribute.java | 4 +- querydsl-scala/pom.xml | 118 +- .../src/main/scala/PlaceHolder.java | 4 +- querydsl-spatial/pom.xml | 31 +- .../AbstractGeometryCollectionExpression.java | 58 +- .../com/querydsl/spatial/CurveExpression.java | 136 +- .../spatial/GeometryCollectionExpression.java | 19 +- .../spatial/GeometryCollectionPath.java | 113 +- .../querydsl/spatial/GeometryExpression.java | 981 ++-- .../querydsl/spatial/GeometryExpressions.java | 497 +- .../querydsl/spatial/GeometryOperation.java | 71 +- .../com/querydsl/spatial/GeometryPath.java | 193 +- .../com/querydsl/spatial/GeometryPaths.java | 26 +- .../com/querydsl/spatial/LineExpression.java | 13 +- .../spatial/LineStringExpression.java | 65 +- .../querydsl/spatial/LineStringOperation.java | 63 +- .../com/querydsl/spatial/LineStringPath.java | 117 +- .../spatial/LinearRingExpression.java | 13 +- .../com/querydsl/spatial/LinearRingPath.java | 117 +- .../spatial/MultiCurveExpression.java | 62 +- .../spatial/MultiLineStringExpression.java | 16 +- .../querydsl/spatial/MultiLineStringPath.java | 117 +- .../spatial/MultiPointExpression.java | 22 +- .../com/querydsl/spatial/MultiPointPath.java | 117 +- .../spatial/MultiPolygonExpression.java | 16 +- .../querydsl/spatial/MultiPolygonPath.java | 117 +- .../spatial/MultiSurfaceExpression.java | 92 +- .../com/querydsl/spatial/PointExpression.java | 104 +- .../com/querydsl/spatial/PointOperation.java | 59 +- .../java/com/querydsl/spatial/PointPath.java | 111 +- .../querydsl/spatial/PolygonExpression.java | 89 +- .../querydsl/spatial/PolygonOperation.java | 62 +- .../com/querydsl/spatial/PolygonPath.java | 111 +- .../java/com/querydsl/spatial/SpatialOps.java | 193 +- .../querydsl/spatial/SurfaceExpression.java | 86 +- .../querydsl/spatial/apt/SpatialSupport.java | 123 +- .../querydsl/spatial/apt/package-info.java | 4 +- .../hibernate/HibernateSpatialSupport.java | 175 +- .../spatial/hibernate/package-info.java | 4 +- .../spatial/jts/JTSCurveExpression.java | 131 +- .../jts/JTSGeometryCollectionExpression.java | 61 +- .../jts/JTSGeometryCollectionPath.java | 116 +- .../spatial/jts/JTSGeometryExpression.java | 979 ++-- .../spatial/jts/JTSGeometryExpressions.java | 492 +- .../spatial/jts/JTSGeometryOperation.java | 64 +- .../querydsl/spatial/jts/JTSGeometryPath.java | 188 +- .../spatial/jts/JTSGeometryPaths.java | 26 +- .../spatial/jts/JTSLineExpression.java | 10 +- .../spatial/jts/JTSLineStringExpression.java | 59 +- .../spatial/jts/JTSLineStringOperation.java | 64 +- .../spatial/jts/JTSLineStringPath.java | 116 +- .../spatial/jts/JTSLinearRingExpression.java | 13 +- .../spatial/jts/JTSLinearRingPath.java | 116 +- .../spatial/jts/JTSMultiCurveExpression.java | 65 +- .../jts/JTSMultiLineStringExpression.java | 13 +- .../spatial/jts/JTSMultiLineStringPath.java | 112 +- .../spatial/jts/JTSMultiPointExpression.java | 19 +- .../spatial/jts/JTSMultiPointPath.java | 116 +- .../jts/JTSMultiPolygonExpression.java | 13 +- .../spatial/jts/JTSMultiPolygonPath.java | 116 +- .../jts/JTSMultiSurfaceExpression.java | 95 +- .../spatial/jts/JTSPointExpression.java | 101 +- .../spatial/jts/JTSPointOperation.java | 63 +- .../querydsl/spatial/jts/JTSPointPath.java | 110 +- .../spatial/jts/JTSPolygonExpression.java | 84 +- .../spatial/jts/JTSPolygonOperation.java | 63 +- .../querydsl/spatial/jts/JTSPolygonPath.java | 111 +- .../spatial/jts/JTSSurfaceExpression.java | 81 +- .../querydsl/spatial/jts/package-info.java | 4 +- .../locationtech/jts/JTSCurveExpression.java | 130 +- .../jts/JTSGeometryCollectionExpression.java | 60 +- .../jts/JTSGeometryCollectionPath.java | 116 +- .../jts/JTSGeometryExpression.java | 978 ++-- .../jts/JTSGeometryExpressions.java | 492 +- .../jts/JTSGeometryOperation.java | 62 +- .../locationtech/jts/JTSGeometryPath.java | 188 +- .../locationtech/jts/JTSGeometryPaths.java | 26 +- .../locationtech/jts/JTSLineExpression.java | 10 +- .../jts/JTSLineStringExpression.java | 58 +- .../jts/JTSLineStringOperation.java | 62 +- .../locationtech/jts/JTSLineStringPath.java | 116 +- .../jts/JTSLinearRingExpression.java | 13 +- .../locationtech/jts/JTSLinearRingPath.java | 116 +- .../jts/JTSMultiCurveExpression.java | 64 +- .../jts/JTSMultiLineStringExpression.java | 13 +- .../jts/JTSMultiLineStringPath.java | 112 +- .../jts/JTSMultiPointExpression.java | 19 +- .../locationtech/jts/JTSMultiPointPath.java | 116 +- .../jts/JTSMultiPolygonExpression.java | 13 +- .../locationtech/jts/JTSMultiPolygonPath.java | 116 +- .../jts/JTSMultiSurfaceExpression.java | 94 +- .../locationtech/jts/JTSPointExpression.java | 100 +- .../locationtech/jts/JTSPointOperation.java | 61 +- .../locationtech/jts/JTSPointPath.java | 110 +- .../jts/JTSPolygonExpression.java | 83 +- .../locationtech/jts/JTSPolygonOperation.java | 61 +- .../locationtech/jts/JTSPolygonPath.java | 111 +- .../jts/JTSSurfaceExpression.java | 80 +- .../locationtech/jts/package-info.java | 4 +- .../com/querydsl/spatial/package-info.java | 4 +- .../com/querydsl/spatial/GeometryEntity.java | 22 +- .../querydsl/spatial/GeometryPathTest.java | 26 +- .../HibernateSpatialSupportTest.java | 18 +- .../spatial/jts/JTSGeometryEntity.java | 19 +- .../spatial/jts/JTSGeometryPathTest.java | 29 +- querydsl-sql-codegen/pom.xml | 70 +- .../sql/codegen/AbstractNamingStrategy.java | 240 +- .../sql/codegen/DefaultNamingStrategy.java | 171 +- .../sql/codegen/ExtendedBeanSerializer.java | 222 +- .../sql/codegen/ExtendedNamingStrategy.java | 47 +- .../querydsl/sql/codegen/KeyDataFactory.java | 221 +- .../sql/codegen/MetaDataExporter.java | 1439 ++--- .../sql/codegen/MetaDataSerializer.java | 749 +-- .../java/com/querydsl/sql/codegen/Naming.java | 32 +- .../querydsl/sql/codegen/NamingStrategy.java | 318 +- .../codegen/OrdinalPositionComparator.java | 36 +- .../sql/codegen/OriginalNamingStrategy.java | 72 +- .../sql/codegen/SQLCodegenModule.java | 98 +- .../sql/codegen/SQLQueryTypeFactory.java | 80 +- .../sql/codegen/ant/AntMetaDataExporter.java | 1240 +++-- .../sql/codegen/ant/package-info.java | 4 +- .../querydsl/sql/codegen/package-info.java | 4 +- .../sql/codegen/support/ColumnData.java | 68 +- .../sql/codegen/support/CustomType.java | 7 +- .../sql/codegen/support/ForeignKeyData.java | 91 +- .../sql/codegen/support/IndexData.java | 41 +- .../support/InverseForeignKeyData.java | 90 +- .../querydsl/sql/codegen/support/KeyData.java | 17 +- .../querydsl/sql/codegen/support/Mapping.java | 13 +- .../sql/codegen/support/NotNullImpl.java | 41 +- .../sql/codegen/support/NumericMapping.java | 55 +- .../sql/codegen/support/PrimaryKeyData.java | 38 +- .../sql/codegen/support/RenameMapping.java | 168 +- .../sql/codegen/support/SizeImpl.java | 61 +- .../sql/codegen/support/TypeMapping.java | 63 +- .../sql/codegen/support/package-info.java | 4 +- .../querydsl/sql/codegen/CustomTypesTest.java | 148 +- .../codegen/DefaultNamingStrategyTest.java | 205 +- .../java/com/querydsl/sql/codegen/Export.java | 27 +- .../querydsl/sql/codegen/ExportBaseTest.java | 62 +- .../querydsl/sql/codegen/ExportDerbyTest.java | 14 +- .../querydsl/sql/codegen/ExportH2Test.java | 14 +- .../sql/codegen/ExportH2TwoSchemasTest.java | 70 +- .../sql/codegen/ExportHsqldbTest.java | 14 +- .../querydsl/sql/codegen/ExportMSSQLTest.java | 21 +- .../querydsl/sql/codegen/ExportMySQLTest.java | 14 +- .../sql/codegen/ExportOracleTest.java | 40 +- .../sql/codegen/ExportPostgreSQLTest.java | 14 +- .../sql/codegen/ExportSQLiteTest.java | 14 +- .../codegen/ExtendedBeanSerializerTest.java | 168 +- .../codegen/ExtendedNamingStrategyTest.java | 147 +- .../sql/codegen/KeyDataFactoryTest.java | 128 +- .../sql/codegen/MetaDataExporterAllTest.java | 262 +- .../sql/codegen/MetaDataExporterTest.java | 819 +-- .../sql/codegen/MetaDataSerializerTest.java | 291 +- .../querydsl/sql/codegen/MetaDataTest.java | 63 +- .../codegen/OriginalNamingStrategyTest.java | 125 +- .../codegen/ant/AntMetaDataExporterTest.java | 144 +- .../codegen/support/RenameMappingTest.java | 196 +- querydsl-sql-spatial/pom.xml | 51 +- .../querydsl/sql/spatial/GeoDBTemplates.java | 54 +- .../querydsl/sql/spatial/GeoDBWkbType.java | 88 +- .../querydsl/sql/spatial/GeometryWkbType.java | 70 +- .../sql/spatial/GeometryWktClobType.java | 72 +- .../querydsl/sql/spatial/GeometryWktType.java | 69 +- .../querydsl/sql/spatial/H2GISTemplates.java | 54 +- .../querydsl/sql/spatial/H2GISWkbType.java | 90 +- .../sql/spatial/MySQLSpatialTemplates.java | 54 +- .../querydsl/sql/spatial/MySQLWkbType.java | 101 +- .../sql/spatial/OracleSpatialTemplates.java | 52 +- .../querydsl/sql/spatial/PGgeometryType.java | 64 +- .../sql/spatial/PostGISTemplates.java | 56 +- .../querydsl/sql/spatial/QSpatialRefSys.java | 65 +- .../sql/spatial/RelationalPathSpatial.java | 134 +- .../querydsl/sql/spatial/SDOGeometryType.java | 74 +- .../SQLServer2008SpatialTemplates.java | 64 +- .../sql/spatial/SQLServerGeometryType.java | 72 +- .../querydsl/sql/spatial/SpatialRefSys.java | 62 +- .../querydsl/sql/spatial/SpatialSupport.java | 46 +- .../sql/spatial/SpatialTemplatesSupport.java | 205 +- .../sql/spatial/TeradataSpatialTemplates.java | 68 +- .../querydsl/sql/spatial/package-info.java | 4 +- .../sql/spatial/GeoDBTemplatesTest.java | 17 +- .../spatial/MySQLSpatialTemplatesTest.java | 16 +- .../sql/spatial/PostGISTemplatesTest.java | 16 +- .../com/querydsl/sql/spatial/QShapes.java | 62 +- .../SQLServer2008SpatialTemplatesTest.java | 17 +- .../java/com/querydsl/sql/spatial/Shapes.java | 29 +- .../com/querydsl/sql/spatial/SpatialBase.java | 822 +-- .../spatial/TeradataSpatialTemplatesTest.java | 16 +- .../spatial/suites/H2LiteralsSuiteTest.java | 22 +- .../sql/spatial/suites/H2SuiteTest.java | 20 +- .../suites/MSSQLLiteralsSuiteTest.java | 21 +- .../sql/spatial/suites/MSSQLSuiteTest.java | 19 +- .../suites/MySQLLiteralsSuiteTest.java | 20 +- .../sql/spatial/suites/MySQLSuiteTest.java | 18 +- .../suites/PostgreSQLLiteralsSuiteTest.java | 21 +- .../spatial/suites/PostgreSQLSuiteTest.java | 19 +- .../sql/spatial/suites/SpatialTest.java | 77 +- querydsl-sql-spring/pom.xml | 5 +- .../sql/spring/SpringConnectionProvider.java | 39 +- .../sql/spring/SpringExceptionTranslator.java | 48 +- .../com/querydsl/sql/spring/package-info.java | 4 +- querydsl-sql/pom.xml | 58 +- .../com/querydsl/sql/AbstractSQLQuery.java | 1258 ++--- .../querydsl/sql/AbstractSQLQueryFactory.java | 239 +- .../src/main/java/com/querydsl/sql/Beans.java | 19 +- .../com/querydsl/sql/CUBRIDTemplates.java | 234 +- .../main/java/com/querydsl/sql/Column.java | 16 +- .../java/com/querydsl/sql/ColumnImpl.java | 27 +- .../java/com/querydsl/sql/ColumnMetadata.java | 323 +- .../java/com/querydsl/sql/Configuration.java | 1022 ++-- .../java/com/querydsl/sql/DB2Templates.java | 306 +- .../main/java/com/querydsl/sql/DatePart.java | 22 +- .../sql/DefaultSQLExceptionTranslator.java | 51 +- .../java/com/querydsl/sql/DerbyTemplates.java | 265 +- .../com/querydsl/sql/FirebirdTemplates.java | 288 +- .../java/com/querydsl/sql/ForeignKey.java | 97 +- .../java/com/querydsl/sql/H2Templates.java | 147 +- .../com/querydsl/sql/HSQLDBTemplates.java | 228 +- .../com/querydsl/sql/JDBCTypeMapping.java | 269 +- .../com/querydsl/sql/JavaTypeMapping.java | 255 +- .../main/java/com/querydsl/sql/Keywords.java | 54 +- .../java/com/querydsl/sql/MySQLTemplates.java | 311 +- .../com/querydsl/sql/OracleTemplates.java | 460 +- .../com/querydsl/sql/PostgreSQLTemplates.java | 295 +- .../java/com/querydsl/sql/PrimaryKey.java | 69 +- .../com/querydsl/sql/ProjectableSQLQuery.java | 978 ++-- .../main/java/com/querydsl/sql/QBeans.java | 94 +- .../querydsl/sql/RelationalFunctionCall.java | 76 +- .../java/com/querydsl/sql/RelationalPath.java | 119 +- .../com/querydsl/sql/RelationalPathBase.java | 447 +- .../querydsl/sql/RelationalPathExtractor.java | 207 +- .../com/querydsl/sql/RelationalPathUtils.java | 60 +- .../com/querydsl/sql/SQLBaseListener.java | 127 +- .../java/com/querydsl/sql/SQLBindings.java | 31 +- .../com/querydsl/sql/SQLCloseListener.java | 28 +- .../java/com/querydsl/sql/SQLCommonQuery.java | 797 +-- .../querydsl/sql/SQLCommonQueryFactory.java | 128 +- .../com/querydsl/sql/SQLDetailedListener.java | 113 +- .../querydsl/sql/SQLExceptionTranslator.java | 33 +- .../java/com/querydsl/sql/SQLExpressions.java | 2486 ++++----- .../java/com/querydsl/sql/SQLListener.java | 168 +- .../com/querydsl/sql/SQLListenerAdapter.java | 256 +- .../com/querydsl/sql/SQLListenerContext.java | 205 +- .../querydsl/sql/SQLListenerContextImpl.java | 268 +- .../java/com/querydsl/sql/SQLListeners.java | 447 +- .../com/querydsl/sql/SQLNoCloseListener.java | 27 +- .../main/java/com/querydsl/sql/SQLOps.java | 152 +- .../main/java/com/querydsl/sql/SQLQuery.java | 230 +- .../com/querydsl/sql/SQLQueryFactory.java | 141 +- .../com/querydsl/sql/SQLResultIterator.java | 162 +- .../java/com/querydsl/sql/SQLSerializer.java | 1816 +++---- .../querydsl/sql/SQLServer2005Templates.java | 231 +- .../querydsl/sql/SQLServer2008Templates.java | 57 +- .../querydsl/sql/SQLServer2012Templates.java | 207 +- .../com/querydsl/sql/SQLServerTemplates.java | 423 +- .../java/com/querydsl/sql/SQLTemplates.java | 2060 ++++---- .../querydsl/sql/SQLTemplatesRegistry.java | 129 +- .../com/querydsl/sql/SQLiteTemplates.java | 240 +- .../java/com/querydsl/sql/SchemaAndTable.java | 70 +- .../com/querydsl/sql/StatementOptions.java | 126 +- .../com/querydsl/sql/TeradataTemplates.java | 238 +- .../src/main/java/com/querydsl/sql/Union.java | 101 +- .../main/java/com/querydsl/sql/UnionImpl.java | 202 +- .../java/com/querydsl/sql/UnionUtils.java | 31 +- .../com/querydsl/sql/WindowFirstLast.java | 135 +- .../java/com/querydsl/sql/WindowFunction.java | 318 +- .../java/com/querydsl/sql/WindowOver.java | 41 +- .../java/com/querydsl/sql/WindowRows.java | 213 +- .../java/com/querydsl/sql/WithBuilder.java | 22 +- .../java/com/querydsl/sql/WithinGroup.java | 169 +- .../java/com/querydsl/sql/ddl/ColumnData.java | 82 +- .../querydsl/sql/ddl/CreateTableClause.java | 361 +- .../com/querydsl/sql/ddl/DropTableClause.java | 49 +- .../querydsl/sql/ddl/ForeignKeyBuilder.java | 50 +- .../com/querydsl/sql/ddl/ForeignKeyData.java | 50 +- .../java/com/querydsl/sql/ddl/IndexData.java | 41 +- .../java/com/querydsl/sql/ddl/KeyData.java | 12 +- .../com/querydsl/sql/ddl/PrimaryKeyData.java | 38 +- .../com/querydsl/sql/dml/AbstractMapper.java | 27 +- .../querydsl/sql/dml/AbstractSQLClause.java | 432 +- .../sql/dml/AbstractSQLDeleteClause.java | 465 +- .../sql/dml/AbstractSQLInsertClause.java | 1051 ++-- .../sql/dml/AbstractSQLUpdateClause.java | 610 +-- .../querydsl/sql/dml/AnnotationMapper.java | 79 +- .../java/com/querydsl/sql/dml/BeanMapper.java | 66 +- .../com/querydsl/sql/dml/DefaultMapper.java | 83 +- .../com/querydsl/sql/dml/EmptyResultSet.java | 1630 +++--- .../java/com/querydsl/sql/dml/Mapper.java | 21 +- .../com/querydsl/sql/dml/SQLDeleteClause.java | 30 +- .../com/querydsl/sql/dml/SQLInsertBatch.java | 49 +- .../com/querydsl/sql/dml/SQLInsertClause.java | 60 +- .../com/querydsl/sql/dml/SQLMergeBatch.java | 56 +- .../com/querydsl/sql/dml/SQLMergeClause.java | 1110 ++-- .../com/querydsl/sql/dml/SQLUpdateBatch.java | 29 +- .../com/querydsl/sql/dml/SQLUpdateClause.java | 29 +- .../com/querydsl/sql/dml/package-info.java | 5 +- .../sql/mssql/AbstractSQLServerQuery.java | 47 +- .../querydsl/sql/mssql/SQLServerGrammar.java | 25 +- .../querydsl/sql/mssql/SQLServerQuery.java | 94 +- .../sql/mssql/SQLServerQueryFactory.java | 89 +- .../sql/mssql/SQLServerTableHints.java | 38 +- .../com/querydsl/sql/mssql/package-info.java | 5 +- .../sql/mysql/AbstractMySQLQuery.java | 410 +- .../com/querydsl/sql/mysql/MySQLQuery.java | 85 +- .../querydsl/sql/mysql/MySQLQueryFactory.java | 231 +- .../sql/mysql/MySQLReplaceClause.java | 28 +- .../com/querydsl/sql/mysql/package-info.java | 5 +- .../sql/namemapping/ChainedNameMapping.java | 68 +- .../ChangeLetterCaseNameMapping.java | 80 +- .../querydsl/sql/namemapping/NameMapping.java | 10 +- .../namemapping/PreConfiguredNameMapping.java | 92 +- .../sql/namemapping/package-info.java | 4 +- .../sql/oracle/AbstractOracleQuery.java | 165 +- .../querydsl/sql/oracle/OracleGrammar.java | 18 +- .../com/querydsl/sql/oracle/OracleQuery.java | 91 +- .../sql/oracle/OracleQueryFactory.java | 89 +- .../com/querydsl/sql/oracle/package-info.java | 5 +- .../java/com/querydsl/sql/package-info.java | 4 +- .../postgresql/AbstractPostgreSQLQuery.java | 115 +- .../sql/postgresql/PostgreSQLQuery.java | 85 +- .../postgresql/PostgreSQLQueryFactory.java | 110 +- .../querydsl/sql/postgresql/package-info.java | 4 +- .../support/JavaSE7SQLExceptionWrapper.java | 44 +- .../sql/support/SQLExceptionWrapper.java | 10 +- .../querydsl/sql/support/package-info.java | 4 +- .../sql/teradata/AbstractTeradataQuery.java | 58 +- .../sql/teradata/SetQueryBandClause.java | 213 +- .../querydsl/sql/teradata/TeradataQuery.java | 106 +- .../sql/teradata/TeradataQueryFactory.java | 110 +- .../querydsl/sql/teradata/package-info.java | 4 +- .../sql/types/AbstractDateTimeType.java | 45 +- .../sql/types/AbstractJSR310DateTimeType.java | 10 +- .../types/AbstractJodaTimeDateTimeType.java | 32 +- .../com/querydsl/sql/types/AbstractType.java | 26 +- .../com/querydsl/sql/types/ArrayType.java | 143 +- .../sql/types/BigDecimalAsDoubleType.java | 43 +- .../querydsl/sql/types/BigDecimalType.java | 39 +- .../sql/types/BigIntegerAsLongType.java | 43 +- .../querydsl/sql/types/BigIntegerType.java | 49 +- .../java/com/querydsl/sql/types/BlobType.java | 38 +- .../com/querydsl/sql/types/BooleanType.java | 58 +- .../java/com/querydsl/sql/types/ByteType.java | 48 +- .../com/querydsl/sql/types/BytesType.java | 39 +- .../com/querydsl/sql/types/CalendarType.java | 64 +- .../com/querydsl/sql/types/CharacterType.java | 49 +- .../java/com/querydsl/sql/types/ClobType.java | 38 +- .../com/querydsl/sql/types/CurrencyType.java | 51 +- .../com/querydsl/sql/types/DateTimeType.java | 63 +- .../java/com/querydsl/sql/types/DateType.java | 56 +- .../com/querydsl/sql/types/DoubleType.java | 48 +- .../querydsl/sql/types/EnumAsObjectType.java | 57 +- .../querydsl/sql/types/EnumByNameType.java | 44 +- .../querydsl/sql/types/EnumByOrdinalType.java | 44 +- .../com/querydsl/sql/types/FloatType.java | 48 +- .../querydsl/sql/types/InputStreamType.java | 48 +- .../com/querydsl/sql/types/IntegerType.java | 48 +- .../querydsl/sql/types/JSR310InstantType.java | 69 +- .../sql/types/JSR310LocalDateTimeType.java | 59 +- .../sql/types/JSR310LocalDateType.java | 57 +- .../sql/types/JSR310LocalTimeType.java | 57 +- .../sql/types/JSR310OffsetDateTimeType.java | 60 +- .../sql/types/JSR310OffsetTimeType.java | 57 +- .../sql/types/JSR310ZonedDateTimeType.java | 59 +- .../querydsl/sql/types/LocalDateTimeType.java | 65 +- .../com/querydsl/sql/types/LocalDateType.java | 64 +- .../com/querydsl/sql/types/LocalTimeType.java | 63 +- .../com/querydsl/sql/types/LocaleType.java | 64 +- .../java/com/querydsl/sql/types/LongType.java | 48 +- .../sql/types/LongVarBinaryBytesType.java | 8 +- .../java/com/querydsl/sql/types/Null.java | 8 +- .../sql/types/NumericBooleanType.java | 65 +- .../com/querydsl/sql/types/ObjectType.java | 39 +- .../com/querydsl/sql/types/SQLXMLType.java | 40 +- .../com/querydsl/sql/types/ShortType.java | 48 +- .../sql/types/StringAsObjectType.java | 66 +- .../com/querydsl/sql/types/StringType.java | 40 +- .../java/com/querydsl/sql/types/TimeType.java | 56 +- .../com/querydsl/sql/types/TimestampType.java | 56 +- .../com/querydsl/sql/types/TrueFalseType.java | 52 +- .../java/com/querydsl/sql/types/Type.java | 83 +- .../java/com/querydsl/sql/types/URLType.java | 39 +- .../com/querydsl/sql/types/UtilDateType.java | 56 +- .../com/querydsl/sql/types/UtilUUIDType.java | 70 +- .../querydsl/sql/types/XMLAsStringType.java | 54 +- .../com/querydsl/sql/types/YesNoType.java | 52 +- .../com/querydsl/sql/types/package-info.java | 5 +- .../src/test/java/com/example/Price.java | 31 +- .../com/querydsl/sql/AbstractBaseTest.java | 246 +- .../com/querydsl/sql/AbstractJDBCTest.java | 34 +- .../sql/AbstractSQLTemplatesTest.java | 309 +- .../java/com/querydsl/sql/ArrayTypesTest.java | 29 +- .../com/querydsl/sql/BeanPopulationBase.java | 145 +- .../com/querydsl/sql/CUBRIDTemplatesTest.java | 9 +- .../java/com/querydsl/sql/CoalesceTest.java | 29 +- .../com/querydsl/sql/ColumnMetadataTest.java | 70 +- .../com/querydsl/sql/ConfigurationTest.java | 243 +- .../java/com/querydsl/sql/Connections.java | 2144 ++++---- .../com/querydsl/sql/ConnectionsTest.java | 11 +- .../test/java/com/querydsl/sql/Constants.java | 38 +- .../com/querydsl/sql/DB2TemplatesTest.java | 71 +- .../com/querydsl/sql/DateArithmeticTest.java | 88 +- .../java/com/querydsl/sql/DeleteBase.java | 210 +- .../com/querydsl/sql/DependenciesTest.java | 38 +- .../com/querydsl/sql/DerbyTemplatesTest.java | 103 +- .../test/java/com/querydsl/sql/DummyBlob.java | 133 +- .../com/querydsl/sql/EncryptedString.java | 4 +- .../com/querydsl/sql/ExtendedSQLQuery.java | 124 +- .../com/querydsl/sql/ExtendedSQLTest.java | 168 +- .../querydsl/sql/FirebirdTemplatesTest.java | 122 +- .../java/com/querydsl/sql/ForeignKeyTest.java | 35 +- .../com/querydsl/sql/H2TemplatesTest.java | 75 +- .../com/querydsl/sql/HSQLDBTemplatesTest.java | 75 +- .../java/com/querydsl/sql/InsertBase.java | 888 ++-- .../com/querydsl/sql/JDBCTypeMappingTest.java | 175 +- .../com/querydsl/sql/JavaTypeMappingTest.java | 65 +- .../java/com/querydsl/sql/JoinFlagsTest.java | 147 +- .../java/com/querydsl/sql/JoinUsageTest.java | 16 +- .../com/querydsl/sql/KeyAccessorsTest.java | 73 +- .../test/java/com/querydsl/sql/KeyTest.java | 122 +- .../com/querydsl/sql/KeywordQuotingBase.java | 94 +- .../java/com/querydsl/sql/LikeEscapeBase.java | 84 +- .../com/querydsl/sql/ListSubQueryTest.java | 58 +- .../test/java/com/querydsl/sql/MergeBase.java | 394 +- .../java/com/querydsl/sql/MetadataTest.java | 70 +- .../test/java/com/querydsl/sql/Multikey.java | 118 +- .../java/com/querydsl/sql/MultikeyTest.java | 69 +- .../com/querydsl/sql/MySQLTemplatesTest.java | 160 +- .../com/querydsl/sql/OracleTemplatesTest.java | 214 +- .../java/com/querydsl/sql/OracleTimeTest.java | 42 +- .../java/com/querydsl/sql/OtherEmployee.java | 29 +- .../java/com/querydsl/sql/PaginationTest.java | 104 +- .../querydsl/sql/PostgreSQLTemplatesTest.java | 163 +- .../java/com/querydsl/sql/PrecedenceTest.java | 24 +- .../java/com/querydsl/sql/Projection.java | 22 +- .../java/com/querydsl/sql/QBean2Test.java | 124 +- .../test/java/com/querydsl/sql/QBeanTest.java | 67 +- .../java/com/querydsl/sql/QCompanies.java | 51 +- .../querydsl/sql/QGeneratedKeysEntity.java | 25 +- .../test/java/com/querydsl/sql/QPerson.java | 56 +- .../java/com/querydsl/sql/QPersonTest.java | 66 +- .../java/com/querydsl/sql/QProjection.java | 101 +- .../com/querydsl/sql/QueryMutabilityTest.java | 69 +- .../querydsl/sql/QueryPerformanceTest.java | 404 +- .../sql/RelationalFunctionCallTest.java | 76 +- .../sql/RelationalPathExtractorTest.java | 84 +- .../com/querydsl/sql/RelationalPathTest.java | 43 +- .../com/querydsl/sql/SQLBindingsTest.java | 82 +- .../querydsl/sql/SQLCloseListenerTest.java | 94 +- .../com/querydsl/sql/SQLListenersTest.java | 315 +- .../com/querydsl/sql/SQLQueryFactoryTest.java | 65 +- .../java/com/querydsl/sql/SQLQueryTest.java | 14 +- .../com/querydsl/sql/SQLSerializerTest.java | 888 ++-- .../sql/SQLServer2005TemplatesTest.java | 162 +- .../sql/SQLServer2012TemplatesTest.java | 143 +- .../querydsl/sql/SQLServerTemplatesTest.java | 101 +- .../com/querydsl/sql/SQLSubQueryTest.java | 299 +- .../sql/SQLTemplatesRegistryDump.java | 66 +- .../com/querydsl/sql/SQLTemplatesTest.java | 187 +- .../com/querydsl/sql/SQLTypeMappingTest.java | 22 +- .../com/querydsl/sql/SQLiteTemplatesTest.java | 95 +- .../com/querydsl/sql/SchemaAndTableTest.java | 15 +- .../java/com/querydsl/sql/SelectBase.java | 4614 +++++++++-------- .../com/querydsl/sql/SelectMySQLBase.java | 41 +- .../com/querydsl/sql/SelectOracleBase.java | 289 +- .../com/querydsl/sql/SelectTeradataBase.java | 38 +- .../sql/SelectWindowFunctionsBase.java | 413 +- .../com/querydsl/sql/SerializationTest.java | 485 +- .../com/querydsl/sql/SimpleProjection.java | 6 +- .../java/com/querydsl/sql/SkipForQuoted.java | 6 +- .../com/querydsl/sql/SkipForQuotedRule.java | 30 +- .../com/querydsl/sql/StoredProcedures.java | 65 +- .../java/com/querydsl/sql/SubqueriesBase.java | 391 +- .../test/java/com/querydsl/sql/Survey.java | 19 +- .../java/com/querydsl/sql/TargetRule.java | 47 +- .../java/com/querydsl/sql/TemplateTest.java | 46 +- .../java/com/querydsl/sql/TemplatesTest.java | 26 +- .../querydsl/sql/TeradataTemplatesTest.java | 132 +- .../com/querydsl/sql/TestLoggingListener.java | 224 +- .../test/java/com/querydsl/sql/TypesBase.java | 143 +- .../test/java/com/querydsl/sql/TypesDump.java | 62 +- .../test/java/com/querydsl/sql/UnionBase.java | 460 +- .../com/querydsl/sql/UnionSubQueryTest.java | 120 +- .../java/com/querydsl/sql/UpdateBase.java | 366 +- .../com/querydsl/sql/WindowFunctionTest.java | 293 +- .../com/querydsl/sql/WithinGroupTest.java | 145 +- .../java/com/querydsl/sql/ddl/ColumnData.java | 82 +- .../querydsl/sql/ddl/CreateTableClause.java | 367 +- .../com/querydsl/sql/ddl/DropTableClause.java | 53 +- .../querydsl/sql/ddl/ForeignKeyBuilder.java | 52 +- .../com/querydsl/sql/ddl/ForeignKeyData.java | 50 +- .../java/com/querydsl/sql/ddl/IndexData.java | 41 +- .../java/com/querydsl/sql/ddl/KeyData.java | 12 +- .../com/querydsl/sql/ddl/PrimaryKeyData.java | 38 +- .../querydsl/sql/dml/AbstractMapperTest.java | 62 +- .../sql/dml/AnnotationMapperTest.java | 61 +- .../com/querydsl/sql/dml/BeanMapperTest.java | 43 +- .../querydsl/sql/dml/DefaultMapperTest.java | 60 +- .../querydsl/sql/dml/SQLDeleteClauseTest.java | 83 +- .../querydsl/sql/dml/SQLInsertClauseTest.java | 109 +- .../querydsl/sql/dml/SQLMergeClauseTest.java | 23 +- .../querydsl/sql/dml/SQLUpdateClauseTest.java | 220 +- .../com/querydsl/sql/domain/Employee.java | 127 +- .../java/com/querydsl/sql/domain/IdName.java | 27 +- .../com/querydsl/sql/domain/QDateTest.java | 32 +- .../com/querydsl/sql/domain/QEmployee.java | 68 +- .../querydsl/sql/domain/QEmployeeNoPK.java | 64 +- .../java/com/querydsl/sql/domain/QIdName.java | 9 +- .../com/querydsl/sql/domain/QNumberTest.java | 61 +- .../java/com/querydsl/sql/domain/QSurvey.java | 46 +- .../com/querydsl/sql/domain/QSurveyNoPK.java | 41 +- .../java/com/querydsl/sql/domain/QTestX.java | 19 +- .../java/com/querydsl/sql/domain/QUuids.java | 60 +- .../com/querydsl/sql/domain/QXmlTest.java | 58 +- .../querydsl/sql/h2/GeneratedKeysH2Test.java | 104 +- .../java/com/querydsl/sql/h2/H2QueryTest.java | 76 +- .../querydsl/sql/hsqldb/HsqldbQueryTest.java | 73 +- .../sql/mssql/SQLServerQueryTest.java | 114 +- .../sql/mssql/WindowFunctionTest.java | 98 +- .../sql/mysql/GeneratedKeysMySQLTest.java | 85 +- .../sql/mysql/MySQLQueryFactoryTest.java | 193 +- .../querydsl/sql/mysql/MySQLQueryTest.java | 463 +- .../sql/oracle/OracleGrammarTest.java | 13 +- .../sql/oracle/OracleQueryFactoryTest.java | 67 +- .../querydsl/sql/oracle/OracleQueryTest.java | 102 +- .../PostgreSQLQueryFactoryTest.java | 67 +- .../sql/postgresql/PostgreSQLQueryTest.java | 200 +- .../querydsl/sql/suites/AbstractSuite.java | 13 +- .../sql/suites/CUBRIDLiteralsSuiteTest.java | 50 +- .../querydsl/sql/suites/CUBRIDSuiteTest.java | 48 +- .../sql/suites/DB2LiteralsSuiteTest.java | 53 +- .../com/querydsl/sql/suites/DB2SuiteTest.java | 51 +- .../sql/suites/DerbyLiteralsSuiteTest.java | 50 +- .../querydsl/sql/suites/DerbySuiteTest.java | 48 +- .../sql/suites/FirebirdLiteralsSuiteTest.java | 51 +- .../sql/suites/FirebirdSuiteTest.java | 49 +- .../sql/suites/H2ExceptionSuiteTest.java | 95 +- .../sql/suites/H2LiteralsSuiteTest.java | 50 +- .../com/querydsl/sql/suites/H2SuiteTest.java | 48 +- .../sql/suites/H2WithQuotingTest.java | 45 +- .../querydsl/sql/suites/H2WithSchemaTest.java | 49 +- .../sql/suites/HsqldbLiteralsSuiteTest.java | 50 +- .../querydsl/sql/suites/HsqldbSuiteTest.java | 48 +- .../sql/suites/MSSQLLiteralsSuiteTest.java | 53 +- .../querydsl/sql/suites/MSSQLSuiteTest.java | 51 +- .../sql/suites/MySQLLiteralsSuiteTest.java | 53 +- .../querydsl/sql/suites/MySQLSuiteTest.java | 51 +- .../sql/suites/MySQLWithQuotingTest.java | 48 +- .../sql/suites/OracleLiteralsSuiteTest.java | 56 +- .../querydsl/sql/suites/OracleSuiteTest.java | 54 +- .../sql/suites/OracleWithQuotingTest.java | 48 +- .../suites/PostgreSQLLiteralsSuiteTest.java | 80 +- .../sql/suites/PostgreSQLSuiteTest.java | 78 +- .../sql/suites/SQLiteLiteralsSuiteTest.java | 50 +- .../querydsl/sql/suites/SQLiteSuiteTest.java | 48 +- .../sql/teradata/SetQueryBandClauseTest.java | 87 +- .../com/querydsl/sql/types/ArrayTypeTest.java | 176 +- .../querydsl/sql/types/LocalDateTimeTest.java | 36 +- .../querydsl/sql/types/LocaleTypeTest.java | 36 +- .../java/com/querydsl/sql/types/TypeTest.java | 195 +- 2154 files changed, 137703 insertions(+), 138040 deletions(-) diff --git a/pom.xml b/pom.xml index 7ec9a35028..0807f7fdc9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,24 +1,101 @@ - + 4.0.0 - com.querydsl - querydsl-root - 5.0.1-SNAPSHOT - Querydsl - parent project for Querydsl modules - https://querydsl.github.io/ com.querydsl querydsl-parent 0.1.0 + com.querydsl + querydsl-root + 5.0.1-SNAPSHOT pom + Querydsl + parent project for Querydsl modules + https://querydsl.github.io/ 2007 + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + + timowest + Timo Westkämper + Mysema Ltd + + Project Manager + Architect + + + + ssaarela + Samppa Saarela + Mysema Ltd + + Developer + + + + ponzao + Vesa Marttila + Mysema Ltd + + Developer + + + + mangolas + Lassi Immonen + Mysema Ltd + + Developer + + + + Shredder121 + Ruben Dijkstra + + Developer + + + + johnktims + John Tims + + Developer + + + + robertandrewbain + Robert Bain + + Developer + + + + jwgmeligmeyling + Jan-Willem Gmelig Meyling + + Developer + + + + + + ${project.checkout} + ${project.checkout} + ${project.githubpage} + + false UTF-8 @@ -27,12 +104,10 @@ scm:git:git@github.com:querydsl/querydsl.git - - com.querydsl.core.testutil.ExternalDatabase, + com.querydsl.core.testutil.ExternalDatabase, com.querydsl.core.testutil.SlowTest, com.querydsl.core.testutil.Performance, - com.querydsl.core.testutil.ReportingOnly - + com.querydsl.core.testutil.ReportingOnly @@ -74,48 +149,10 @@ 1.7.20 - - * - + * ${osgi.import.package.root} - - - junit - junit - test - - - org.hamcrest - hamcrest - test - - - org.easymock - easymock - 4.3 - test - - - cglib - cglib-nodep - - - - - org.javassist - javassist - test - - - org.codehaus.mojo - animal-sniffer-annotations - ${animal-sniffer.version} - true - - - @@ -228,82 +265,43 @@ - - ${project.checkout} - ${project.checkout} - ${project.githubpage} - - - - - timowest - Timo Westkämper - Mysema Ltd - - Project Manager - Architect - - - - ssaarela - Samppa Saarela - Mysema Ltd - - Developer - - - - ponzao - Vesa Marttila - Mysema Ltd - - Developer - - - - mangolas - Lassi Immonen - Mysema Ltd - - Developer - - - - Shredder121 - Ruben Dijkstra - - Developer - - - - johnktims - John Tims - - Developer - - - - robertandrewbain - Robert Bain - - Developer - - - - jwgmeligmeyling - Jan-Willem Gmelig Meyling - - Developer - - - + + + junit + junit + test + + + org.hamcrest + hamcrest + test + + + org.easymock + easymock + 4.3 + test + + + cglib + cglib-nodep + + + + + org.javassist + javassist + test + + + org.codehaus.mojo + animal-sniffer-annotations + ${animal-sniffer.version} + true + + - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - + @@ -340,16 +338,14 @@ bundle-manifest - process-classes manifest + process-classes true - - ${osgi.import.package} - + ${osgi.import.package} com.querydsl.* @@ -362,10 +358,10 @@ ${dokka.version} - prepare-package javadocJar + prepare-package @@ -388,22 +384,22 @@ enforce-maven - validate enforce + validate - + enforce-banned-dependencies - validate enforce + validate @@ -468,10 +464,10 @@ - verify cmp + verify @@ -598,10 +594,10 @@ 3.2.1 - package jar + package @@ -639,10 +635,10 @@ ensure-java-1.6-class-library - test check + test @@ -650,13 +646,23 @@ org.apache.maven.plugins maven-checkstyle-plugin 3.1.2 + + **/generated/**/*,**/jmh_generated/**/*,**/com/querydsl/codegen/utils/**/* + + + + com.puppycrawl.tools + checkstyle + 9.3 + + checkstyle - validate check + validate src/main/resources/querydsl_checks_base.xml true @@ -665,36 +671,47 @@ checkstyle-main - validate check + validate src/main/resources/querydsl_checks_main.xml true - - - com.puppycrawl.tools - checkstyle - 9.3 - - - - **/generated/**/*,**/jmh_generated/**/*,**/com/querydsl/codegen/utils/**/* - - + + + + org.codehaus.mojo + junit-report-maven-plugin + devel + + true + + + + org.apache.maven.plugins + maven-jxr-plugin + 3.2.0 + + true + + + + all - true + + true + querydsl-core querydsl-codegen @@ -842,24 +859,20 @@ jenkins - - com.querydsl.core.testutil.Performance, + com.querydsl.core.testutil.Performance, com.querydsl.core.testutil.DB2, - com.querydsl.core.testutil.SQLServer - + com.querydsl.core.testutil.SQLServer travis - - com.querydsl.core.testutil.Performance, + com.querydsl.core.testutil.Performance, com.querydsl.core.testutil.ReportingOnly, - com.querydsl.core.testutil.Teradata - + com.querydsl.core.testutil.Teradata @@ -932,25 +945,4 @@ - - - - org.codehaus.mojo - junit-report-maven-plugin - devel - - true - - - - org.apache.maven.plugins - maven-jxr-plugin - 3.2.0 - - true - - - - - diff --git a/querydsl-ant-test/src/test/Test.java b/querydsl-ant-test/src/test/Test.java index 1785678916..1ada458803 100755 --- a/querydsl-ant-test/src/test/Test.java +++ b/querydsl-ant-test/src/test/Test.java @@ -1,15 +1,14 @@ package test; -import java.math.BigDecimal; import com.mysema.query.annotations.QueryEntity; - +import java.math.BigDecimal; @QueryEntity public class Test { - private String property; + private String property; - private int intProperty; + private int intProperty; - private BigDecimal bigDecimal; + private BigDecimal bigDecimal; } diff --git a/querydsl-apt/pom.xml b/querydsl-apt/pom.xml index c0dd456bed..c7b310bc80 100644 --- a/querydsl-apt/pom.xml +++ b/querydsl-apt/pom.xml @@ -1,5 +1,5 @@ - + 4.0.0 @@ -11,10 +11,10 @@ com.querydsl querydsl-apt + jar Querydsl - APT support APT based Source code generation for Querydsl ${project.homepage} - jar ${project.checkout} @@ -45,7 +45,7 @@ 2.2.3 provided - + org.datanucleus @@ -60,7 +60,7 @@ org.apache.commons - commons-lang3 + commons-lang3 commons-io @@ -78,14 +78,14 @@ ${morphia.version} provided - + joda-time joda-time ${jodatime.version} test - + org.hibernate hibernate-core @@ -93,11 +93,11 @@ test - javassist org.javassist + javassist - + org.hibernate hibernate-envers @@ -108,28 +108,30 @@ com.querydsl querydsl-core ${project.version} - test test-jar + test - + org.joda joda-money 1.0.1 test - + org.eclipse.jdt.core.compiler ecj test - + + + - junit @@ -62,7 +83,14 @@ provided - + + + + com.springsource.repository.bundles.release + http://repository.springsource.com/maven/bundles/release + + + @@ -94,33 +122,4 @@ - - - - com.springsource.repository.bundles.release - http://repository.springsource.com/maven/bundles/release - - - - - - - tiwe - Timo Westkämper - timo.westkamper@mysema.com - Mysema Ltd - - Architect - - - - laim - Lassi Immonen - lassi.immonen@mysema.com - Mysema Ltd - - Consultant - - - diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractCodeWriter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractCodeWriter.java index 8941de6078..8d472f0595 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractCodeWriter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractCodeWriter.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -17,83 +17,81 @@ /** * @author tiwe - * * @param */ -public abstract class AbstractCodeWriter> implements Appendable, - CodeWriter { +public abstract class AbstractCodeWriter> + implements Appendable, CodeWriter { - private final Appendable appendable; + private final Appendable appendable; - private final int spaces; + private final int spaces; - private final String spacesString; + private final String spacesString; - private String indent = ""; + private String indent = ""; - @SuppressWarnings("unchecked") - private final T self = (T) this; + @SuppressWarnings("unchecked") + private final T self = (T) this; - public AbstractCodeWriter(Appendable appendable, int spaces) { - if (appendable == null) { - throw new IllegalArgumentException("appendable is null"); - } - this.appendable = appendable; - this.spaces = spaces; - this.spacesString = StringUtils.repeat(' ', spaces); + public AbstractCodeWriter(Appendable appendable, int spaces) { + if (appendable == null) { + throw new IllegalArgumentException("appendable is null"); } - - @Override - public T append(char c) throws IOException { - appendable.append(c); - return self; - } - - @Override - public T append(CharSequence csq) throws IOException { - appendable.append(csq); - return self; + this.appendable = appendable; + this.spaces = spaces; + this.spacesString = StringUtils.repeat(' ', spaces); + } + + @Override + public T append(char c) throws IOException { + appendable.append(c); + return self; + } + + @Override + public T append(CharSequence csq) throws IOException { + appendable.append(csq); + return self; + } + + @Override + public T append(CharSequence csq, int start, int end) throws IOException { + appendable.append(csq, start, end); + return self; + } + + @Override + public T beginLine(String... segments) throws IOException { + append(indent); + for (String segment : segments) { + append(segment); } + return self; + } - @Override - public T append(CharSequence csq, int start, int end) throws IOException { - appendable.append(csq, start, end); - return self; - } - - @Override - public T beginLine(String... segments) throws IOException { - append(indent); - for (String segment : segments) { - append(segment); - } - return self; - } + protected T goIn() { + indent += spacesString; + return self; + } - protected T goIn() { - indent += spacesString; - return self; + protected T goOut() { + if (indent.length() >= spaces) { + indent = indent.substring(0, indent.length() - spaces); } - - protected T goOut() { - if (indent.length() >= spaces) { - indent = indent.substring(0, indent.length() - spaces); - } - return self; - } - - @Override - public T line(String... segments) throws IOException { - append(indent); - for (String segment : segments) { - append(segment); - } - return nl(); - } - - @Override - public T nl() throws IOException { - return append(System.lineSeparator()); + return self; + } + + @Override + public T line(String... segments) throws IOException { + append(indent); + for (String segment : segments) { + append(segment); } + return nl(); + } + @Override + public T nl() throws IOException { + return append(System.lineSeparator()); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractEvaluatorFactory.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractEvaluatorFactory.java index f54357ad62..ce6d7765b0 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractEvaluatorFactory.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/AbstractEvaluatorFactory.java @@ -1,6 +1,6 @@ /* * Copyright 2012, Mysema Ltd - * + * * 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 @@ -13,168 +13,186 @@ */ package com.querydsl.codegen.utils; -import java.io.IOException; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Map; -import java.util.WeakHashMap; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.Parameter; import com.querydsl.codegen.utils.model.SimpleType; import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.codegen.utils.support.ClassUtils; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Map; +import java.util.WeakHashMap; /** * @author tiwe - * */ public abstract class AbstractEvaluatorFactory implements EvaluatorFactory { - - private final Map cache = new WeakHashMap(); - - protected ClassLoader loader; - - /** - * @param source - * @param projection - * @param names - * @param types - * @param id - * @param constants - * @throws IOException - */ - protected abstract void compile(String source, ClassType projection, String[] names, Type[] types, - String id, Map constants) throws IOException; - - /** - * @param source - * @param projectionType - * @param names - * @param types - * @param id - * @param constants - * @return - * @throws IOException - */ - protected String createSource(String source, ClassType projectionType, String[] names, - Type[] types, String id, Map constants) throws IOException { - // create source - StringWriter writer = new StringWriter(); - JavaWriter javaw = new JavaWriter(writer); - SimpleType idType = new SimpleType(id, "", id); - javaw.beginClass(idType, null); - Parameter[] params = new Parameter[names.length + constants.size()]; - for (int i = 0; i < names.length; i++) { - params[i] = new Parameter(names[i], types[i]); - } - int i = names.length; - for (Map.Entry entry : constants.entrySet()) { - Type type = new ClassType(TypeCategory.SIMPLE, ClassUtils.normalize(entry.getValue().getClass())); - params[i++] = new Parameter(entry.getKey(), type); - } - javaw.beginStaticMethod(projectionType, "eval", params); - javaw.append(source); - javaw.end(); - javaw.end(); - return writer.toString(); + private final Map cache = new WeakHashMap(); + + protected ClassLoader loader; + + /** + * @param source + * @param projection + * @param names + * @param types + * @param id + * @param constants + * @throws IOException + */ + protected abstract void compile( + String source, + ClassType projection, + String[] names, + Type[] types, + String id, + Map constants) + throws IOException; + + /** + * @param source + * @param projectionType + * @param names + * @param types + * @param id + * @param constants + * @return + * @throws IOException + */ + protected String createSource( + String source, + ClassType projectionType, + String[] names, + Type[] types, + String id, + Map constants) + throws IOException { + // create source + StringWriter writer = new StringWriter(); + JavaWriter javaw = new JavaWriter(writer); + SimpleType idType = new SimpleType(id, "", id); + javaw.beginClass(idType, null); + Parameter[] params = new Parameter[names.length + constants.size()]; + for (int i = 0; i < names.length; i++) { + params[i] = new Parameter(names[i], types[i]); + } + int i = names.length; + for (Map.Entry entry : constants.entrySet()) { + Type type = + new ClassType(TypeCategory.SIMPLE, ClassUtils.normalize(entry.getValue().getClass())); + params[i++] = new Parameter(entry.getKey(), type); } - - @Override - public Evaluator createEvaluator(String source, Class projectionType, - String[] names, Class[] classes, Map constants) { - Type[] types = new Type[classes.length]; - for (int i = 0; i < types.length; i++) { - types[i] = new ClassType(TypeCategory.SIMPLE, classes[i]); - } - return createEvaluator(source, new ClassType(TypeCategory.SIMPLE, projectionType), names, - types, classes, constants); + javaw.beginStaticMethod(projectionType, "eval", params); + javaw.append(source); + javaw.end(); + javaw.end(); + return writer.toString(); + } + + @Override + public Evaluator createEvaluator( + String source, + Class projectionType, + String[] names, + Class[] classes, + Map constants) { + Type[] types = new Type[classes.length]; + for (int i = 0; i < types.length; i++) { + types[i] = new ClassType(TypeCategory.SIMPLE, classes[i]); } + return createEvaluator( + source, + new ClassType(TypeCategory.SIMPLE, projectionType), + names, + types, + classes, + constants); + } + /** + * Create a new Evaluator instance + * + * @param projection type + * @param source expression in Java source code form + * @param projection type of the source expression + * @param names names of the arguments + * @param types types of the arguments + * @param constants + * @return + */ + @SuppressWarnings("unchecked") + @Override + public synchronized Evaluator createEvaluator( + String source, + ClassType projection, + String[] names, + Type[] types, + Class[] classes, + Map constants) { + try { + final String id = toId(source, projection.getJavaClass(), types, constants.values()); + Method method = cache.get(id); - /** - * Create a new Evaluator instance - * - * @param - * projection type - * @param source - * expression in Java source code form - * @param projection - * type of the source expression - * @param names - * names of the arguments - * @param types - * types of the arguments - * @param constants - * @return - */ - @SuppressWarnings("unchecked") - @Override - public synchronized Evaluator createEvaluator(String source, ClassType projection, String[] names, - Type[] types, Class[] classes, Map constants) { + if (method == null) { + Class clazz; try { - final String id = toId(source, projection.getJavaClass(), types, constants.values()); - Method method = cache.get(id); - - if (method == null) { - Class clazz; - try { - clazz = loader.loadClass(id); - } catch (ClassNotFoundException e) { - compile(source, projection, names, types, id, constants); - // reload - clazz = loader.loadClass(id); - } - method = findEvalMethod(clazz); - cache.put(id, method); - } - - return new MethodEvaluator(method, constants, (Class) projection.getJavaClass()); + clazz = loader.loadClass(id); } catch (ClassNotFoundException e) { - throw new CodegenException(e); - } catch (SecurityException e) { - throw new CodegenException(e); - } catch (IOException e) { - throw new CodegenException(e); + compile(source, projection, names, types, id, constants); + // reload + clazz = loader.loadClass(id); } - } + method = findEvalMethod(clazz); + cache.put(id, method); + } - protected Method findEvalMethod(Class clazz) { - /* - * Note 1: - * Some Java instrumentation tools (e.g. JaCoCo) insert code into - * classes at runtime. This means that the static eval() method *could* - * not be the first method of our runtime generated classes anymore. - * - * Note 2: - * We can't use clazz.getDeclaredMethod(name, classes), as the argument - * types of the eval() method could be normalized (see createSource()). - */ - for (Method method : clazz.getDeclaredMethods()) { - if ("eval".equals(method.getName())) { - return method; - } - } + return new MethodEvaluator(method, constants, (Class) projection.getJavaClass()); + } catch (ClassNotFoundException e) { + throw new CodegenException(e); + } catch (SecurityException e) { + throw new CodegenException(e); + } catch (IOException e) { + throw new CodegenException(e); + } + } - throw new IllegalArgumentException("Couldn't find eval method!"); + protected Method findEvalMethod(Class clazz) { + /* + * Note 1: + * Some Java instrumentation tools (e.g. JaCoCo) insert code into + * classes at runtime. This means that the static eval() method *could* + * not be the first method of our runtime generated classes anymore. + * + * Note 2: + * We can't use clazz.getDeclaredMethod(name, classes), as the argument + * types of the eval() method could be normalized (see createSource()). + */ + for (Method method : clazz.getDeclaredMethods()) { + if ("eval".equals(method.getName())) { + return method; + } } - protected String toId(String source, Class returnType, Type[] types, Collection constants) { - StringBuilder b = new StringBuilder(128); - b.append("Q"); - b.append("_").append(source.hashCode()); - b.append("_").append(returnType.getName().hashCode()); - for (Type type : types) { - b.append("_").append(type.getFullName().hashCode()); - } - for (Object constant : constants) { - b.append("_").append(constant.getClass().getName().hashCode()); - } - return b.toString().replace('-', '0'); + throw new IllegalArgumentException("Couldn't find eval method!"); + } + + protected String toId( + String source, Class returnType, Type[] types, Collection constants) { + StringBuilder b = new StringBuilder(128); + b.append("Q"); + b.append("_").append(source.hashCode()); + b.append("_").append(returnType.getName().hashCode()); + for (Type type : types) { + b.append("_").append(type.getFullName().hashCode()); + } + for (Object constant : constants) { + b.append("_").append(constant.getClass().getName().hashCode()); } - + return b.toString().replace('-', '0'); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodeWriter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodeWriter.java index 555c2f502d..da9ed03fe0 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodeWriter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodeWriter.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -13,102 +13,107 @@ */ package com.querydsl.codegen.utils; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.Type; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.function.Function; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.Type; - /** * CodeWriter defines an interface for serializing Java source code - * + * * @author tiwe - * */ public interface CodeWriter extends Appendable { - String getRawName(Type type); - - String getGenericName(boolean asArgType, Type type); + String getRawName(Type type); - String getClassConstant(String className); + String getGenericName(boolean asArgType, Type type); - CodeWriter annotation(Annotation annotation) throws IOException; + String getClassConstant(String className); - CodeWriter annotation(Class annotation) throws IOException; + CodeWriter annotation(Annotation annotation) throws IOException; - CodeWriter beginClass(Type type) throws IOException; + CodeWriter annotation(Class annotation) throws IOException; - CodeWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException; + CodeWriter beginClass(Type type) throws IOException; - CodeWriter beginConstructor(Collection params, Function transformer) throws IOException; + CodeWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException; - CodeWriter beginConstructor(Parameter... params) throws IOException; + CodeWriter beginConstructor(Collection params, Function transformer) + throws IOException; - CodeWriter beginInterface(Type type, Type... interfaces) throws IOException; + CodeWriter beginConstructor(Parameter... params) throws IOException; - CodeWriter beginLine(String... segments) throws IOException; + CodeWriter beginInterface(Type type, Type... interfaces) throws IOException; - CodeWriter beginPublicMethod(Type returnType, String methodName, Collection parameters, - Function transformer) throws IOException; + CodeWriter beginLine(String... segments) throws IOException; - CodeWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) throws IOException; + CodeWriter beginPublicMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException; - CodeWriter beginStaticMethod(Type type, String name, Collection params, - Function transformer) throws IOException; + CodeWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) + throws IOException; - CodeWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) throws IOException; + CodeWriter beginStaticMethod( + Type type, String name, Collection params, Function transformer) + throws IOException; - CodeWriter end() throws IOException; + CodeWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) + throws IOException; - CodeWriter field(Type type, String name) throws IOException; + CodeWriter end() throws IOException; - CodeWriter imports(Class... imports) throws IOException; + CodeWriter field(Type type, String name) throws IOException; - CodeWriter imports(Package... imports) throws IOException; + CodeWriter imports(Class... imports) throws IOException; - CodeWriter importClasses(String... classes) throws IOException; + CodeWriter imports(Package... imports) throws IOException; - CodeWriter importPackages(String... packages) throws IOException; + CodeWriter importClasses(String... classes) throws IOException; - CodeWriter javadoc(String... lines) throws IOException; + CodeWriter importPackages(String... packages) throws IOException; - CodeWriter line(String... segments) throws IOException; + CodeWriter javadoc(String... lines) throws IOException; - CodeWriter nl() throws IOException; + CodeWriter line(String... segments) throws IOException; - CodeWriter packageDecl(String packageName) throws IOException; + CodeWriter nl() throws IOException; - CodeWriter privateField(Type type, String name) throws IOException; + CodeWriter packageDecl(String packageName) throws IOException; - CodeWriter privateFinal(Type type, String name) throws IOException; + CodeWriter privateField(Type type, String name) throws IOException; - CodeWriter privateFinal(Type type, String name, String value) throws IOException; + CodeWriter privateFinal(Type type, String name) throws IOException; - CodeWriter privateStaticFinal(Type type, String name, String value) throws IOException; + CodeWriter privateFinal(Type type, String name, String value) throws IOException; - CodeWriter protectedField(Type type, String name) throws IOException; + CodeWriter privateStaticFinal(Type type, String name, String value) throws IOException; - CodeWriter protectedFinal(Type type, String name) throws IOException; + CodeWriter protectedField(Type type, String name) throws IOException; - CodeWriter protectedFinal(Type type, String name, String value) throws IOException; + CodeWriter protectedFinal(Type type, String name) throws IOException; - CodeWriter publicField(Type type, String name) throws IOException; + CodeWriter protectedFinal(Type type, String name, String value) throws IOException; - CodeWriter publicField(Type type, String name, String value) throws IOException; + CodeWriter publicField(Type type, String name) throws IOException; - CodeWriter publicFinal(Type type, String name) throws IOException; + CodeWriter publicField(Type type, String name, String value) throws IOException; - CodeWriter publicFinal(Type type, String name, String value) throws IOException; + CodeWriter publicFinal(Type type, String name) throws IOException; - CodeWriter publicStaticFinal(Type type, String name, String value) throws IOException; + CodeWriter publicFinal(Type type, String name, String value) throws IOException; - CodeWriter staticimports(Class... imports) throws IOException; + CodeWriter publicStaticFinal(Type type, String name, String value) throws IOException; - CodeWriter suppressWarnings(String type) throws IOException; + CodeWriter staticimports(Class... imports) throws IOException; - CodeWriter suppressWarnings(String... types) throws IOException; + CodeWriter suppressWarnings(String type) throws IOException; -} \ No newline at end of file + CodeWriter suppressWarnings(String... types) throws IOException; +} diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodegenException.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodegenException.java index 52d34c9022..86707fbe3e 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodegenException.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/CodegenException.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -15,21 +15,20 @@ /** * @author tiwe - * */ public class CodegenException extends RuntimeException { - private static final long serialVersionUID = -8704782349669898467L; + private static final long serialVersionUID = -8704782349669898467L; - public CodegenException(String msg) { - super(msg); - } + public CodegenException(String msg) { + super(msg); + } - public CodegenException(String msg, Throwable t) { - super(msg, t); - } + public CodegenException(String msg, Throwable t) { + super(msg, t); + } - public CodegenException(Throwable t) { - super(t); - } + public CodegenException(Throwable t) { + super(t); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ECJEvaluatorFactory.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ECJEvaluatorFactory.java index 77ec0e39c0..329c28c923 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ECJEvaluatorFactory.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ECJEvaluatorFactory.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -13,8 +13,8 @@ */ package com.querydsl.codegen.utils; -import javax.tools.JavaFileObject; -import javax.tools.StandardLocation; +import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.Type; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -27,9 +27,8 @@ import java.util.Map; import java.util.StringTokenizer; import java.util.stream.Collectors; - -import com.querydsl.codegen.utils.model.ClassType; -import com.querydsl.codegen.utils.model.Type; +import javax.tools.JavaFileObject; +import javax.tools.StandardLocation; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.*; @@ -45,262 +44,279 @@ /** * EvaluatorFactory is a factory implementation for creating Evaluator instances - * + * * @author tiwe - * */ public class ECJEvaluatorFactory extends AbstractEvaluatorFactory { - - private final MemFileManager fileManager; - - private final ClassLoader parentClassLoader; - - private final List problemList = new ArrayList<>(); - - private final CompilerOptions compilerOptions; - - public static CompilerOptions getDefaultCompilerOptions() { - String javaSpecVersion = System.getProperty("java.specification.version"); - Map settings = new HashMap<>(); - settings.put(CompilerOptions.OPTION_Source, javaSpecVersion); - settings.put(CompilerOptions.OPTION_TargetPlatform, javaSpecVersion); - settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); - return new CompilerOptions(settings); - } - public ECJEvaluatorFactory(ClassLoader parent) { - this(parent, getDefaultCompilerOptions()); - } - - public ECJEvaluatorFactory(ClassLoader parent, CompilerOptions compilerOptions) { - this.parentClassLoader = parent; - this.fileManager = new MemFileManager(parent, new EclipseFileManager(Locale.getDefault(), Charset.defaultCharset())); - this.loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); - this.compilerOptions = compilerOptions; - } + private final MemFileManager fileManager; + + private final ClassLoader parentClassLoader; + + private final List problemList = new ArrayList<>(); + + private final CompilerOptions compilerOptions; - protected void compile(String source, ClassType projectionType, String[] names, Type[] types, - String id, Map constants) throws IOException { - // create source - source = createSource(source, projectionType, names, types, id, constants); + public static CompilerOptions getDefaultCompilerOptions() { + String javaSpecVersion = System.getProperty("java.specification.version"); + Map settings = new HashMap<>(); + settings.put(CompilerOptions.OPTION_Source, javaSpecVersion); + settings.put(CompilerOptions.OPTION_TargetPlatform, javaSpecVersion); + settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); + return new CompilerOptions(settings); + } - // compile - final char[] targetContents = source.toCharArray(); - final String targetName = id; - final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() { + public ECJEvaluatorFactory(ClassLoader parent) { + this(parent, getDefaultCompilerOptions()); + } + + public ECJEvaluatorFactory(ClassLoader parent, CompilerOptions compilerOptions) { + this.parentClassLoader = parent; + this.fileManager = + new MemFileManager( + parent, new EclipseFileManager(Locale.getDefault(), Charset.defaultCharset())); + this.loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); + this.compilerOptions = compilerOptions; + } + + protected void compile( + String source, + ClassType projectionType, + String[] names, + Type[] types, + String id, + Map constants) + throws IOException { + // create source + source = createSource(source, projectionType, names, types, id, constants); + + // compile + final char[] targetContents = source.toCharArray(); + final String targetName = id; + final ICompilationUnit[] targetCompilationUnits = + new ICompilationUnit[] { + new ICompilationUnit() { @Override public char[] getContents() { - return targetContents; + return targetContents; } @Override public char[] getMainTypeName() { - int dot = targetName.lastIndexOf('.'); - if (dot > 0) { - return targetName.substring(dot + 1).toCharArray(); - } else { - return targetName.toCharArray(); - } + int dot = targetName.lastIndexOf('.'); + if (dot > 0) { + return targetName.substring(dot + 1).toCharArray(); + } else { + return targetName.toCharArray(); + } } @Override public char[][] getPackageName() { - StringTokenizer tok = new StringTokenizer(targetName, "."); - char[][] result = new char[tok.countTokens() - 1][]; - for (int j = 0; j < result.length; j++) { - result[j] = tok.nextToken().toCharArray(); - } - return result; + StringTokenizer tok = new StringTokenizer(targetName, "."); + char[][] result = new char[tok.countTokens() - 1][]; + for (int j = 0; j < result.length; j++) { + result[j] = tok.nextToken().toCharArray(); + } + return result; } @Override public char[] getFileName() { - return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray()); + return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray()); } @Override public boolean ignoreOptionalProblems() { - return true; - } - } }; - - INameEnvironment env = new INameEnvironment() { - - private String join(char[][] compoundName, char separator) { - if (compoundName == null) { - return ""; - } else { - List parts = new ArrayList<>(compoundName.length); - for (char[] part: compoundName) { - parts.add(new String(part)); - } - return parts.stream().collect(Collectors.joining(new String(new char[] { separator }))); - } + return true; } - - @Override - public NameEnvironmentAnswer findType(char[][] compoundTypeName) { - return findType(join(compoundTypeName, '.')); + } + }; + + INameEnvironment env = + new INameEnvironment() { + + private String join(char[][] compoundName, char separator) { + if (compoundName == null) { + return ""; + } else { + List parts = new ArrayList<>(compoundName.length); + for (char[] part : compoundName) { + parts.add(new String(part)); + } + return parts.stream().collect(Collectors.joining(new String(new char[] {separator}))); } + } - @Override - public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { - return findType(CharOperation.arrayConcat(packageName, typeName)); + @Override + public NameEnvironmentAnswer findType(char[][] compoundTypeName) { + return findType(join(compoundTypeName, '.')); + } + + @Override + public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { + return findType(CharOperation.arrayConcat(packageName, typeName)); + } + + private boolean isClass(String result) { + if (result == null || result.isEmpty()) { + return false; } - private boolean isClass(String result) { - if (result == null || result.isEmpty()) { - return false; - } - - // if it's the class we're compiling, then of course it's a class - if (result.equals(targetName)) { - return true; + // if it's the class we're compiling, then of course it's a class + if (result.equals(targetName)) { + return true; + } + InputStream is = null; + try { + // if this is a class we've already compiled, it's a class + is = loader.getResourceAsStream(result); + if (is == null) { + // use our normal class loader now... + String resourceName = result.replace('.', '/') + ".class"; + is = parentClassLoader.getResourceAsStream(resourceName); + if (is == null && !result.contains(".")) { + // we couldn't find the class, and it has no package; is it a core class? + is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName); } - InputStream is = null; + } + return is != null; + } finally { + if (is != null) { try { - // if this is a class we've already compiled, it's a class - is = loader.getResourceAsStream(result); - if (is == null) { - // use our normal class loader now... - String resourceName = result.replace('.', '/') + ".class"; - is = parentClassLoader.getResourceAsStream(resourceName); - if (is == null && !result.contains(".")) { - // we couldn't find the class, and it has no package; is it a core class? - is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName); - } - } - return is != null; - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException ex) { } - } + is.close(); + } catch (IOException ex) { } + } } - - @Override - public boolean isPackage(char[][] parentPackageName, char[] packageName) { - // if the parent is a class, the child can't be a package - String parent = join(parentPackageName, '.'); - if (isClass(parent)) { - return false; - } + } - // if the child is a class, it's not a package - String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName); - return !isClass(qualifiedName); + @Override + public boolean isPackage(char[][] parentPackageName, char[] packageName) { + // if the parent is a class, the child can't be a package + String parent = join(parentPackageName, '.'); + if (isClass(parent)) { + return false; } - - @Override - public void cleanup() { - } - - private NameEnvironmentAnswer findType(String className) { - String resourceName = className.replace('.', '/') + ".class"; - InputStream is = null; - try { - // we're only asking ECJ to compile a single class; we shouldn't need this - if (className.equals(targetName)) { - return new NameEnvironmentAnswer(targetCompilationUnits[0], null); - } - - is = loader.getResourceAsStream(resourceName); - if (is == null) { - is = parentClassLoader.getResourceAsStream(resourceName); - } - - if (is != null) { - - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int nRead; - byte[] data = new byte[1024]; - while ((nRead = is.read(data, 0, data.length)) != -1) { - buffer.write(data, 0, nRead); - } - buffer.flush(); - - ClassFileReader cfr = new ClassFileReader(buffer.toByteArray(), className.toCharArray(), true); - return new NameEnvironmentAnswer(cfr, null); - } else { - return null; - } - } catch (ClassFormatException | IOException ex) { - throw new RuntimeException(ex); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { } - } + + // if the child is a class, it's not a package + String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName); + return !isClass(qualifiedName); + } + + @Override + public void cleanup() {} + + private NameEnvironmentAnswer findType(String className) { + String resourceName = className.replace('.', '/') + ".class"; + InputStream is = null; + try { + // we're only asking ECJ to compile a single class; we shouldn't need this + if (className.equals(targetName)) { + return new NameEnvironmentAnswer(targetCompilationUnits[0], null); + } + + is = loader.getResourceAsStream(resourceName); + if (is == null) { + is = parentClassLoader.getResourceAsStream(resourceName); + } + + if (is != null) { + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int nRead; + byte[] data = new byte[1024]; + while ((nRead = is.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); } - - } - }; - - ICompilerRequestor requestor = new ICompilerRequestor() { + buffer.flush(); - @Override - public void acceptResult(CompilationResult result) { - if (result.hasErrors()) { - for (CategorizedProblem problem: result.getProblems()) { - if (problem.isError()) { - problemList.add(problem.getMessage()); - } - } - } else { - for (ClassFile clazz: result.getClassFiles()) { - try { - MemJavaFileObject jfo = (MemJavaFileObject) fileManager - .getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, - new String(clazz.fileName()), JavaFileObject.Kind.CLASS, null); - OutputStream os = jfo.openOutputStream(); - os.write(clazz.getBytes()); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } + ClassFileReader cfr = + new ClassFileReader(buffer.toByteArray(), className.toCharArray(), true); + return new NameEnvironmentAnswer(cfr, null); + } else { + return null; + } + } catch (ClassFormatException | IOException ex) { + throw new RuntimeException(ex); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { } + } } + } }; - - problemList.clear(); - - IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems(); - IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); - - try { - //Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true); - Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory); - compiler.compile(targetCompilationUnits); - if (!problemList.isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (String problem: problemList) { - sb.append("\t").append(problem).append("\n"); + + ICompilerRequestor requestor = + new ICompilerRequestor() { + + @Override + public void acceptResult(CompilationResult result) { + if (result.hasErrors()) { + for (CategorizedProblem problem : result.getProblems()) { + if (problem.isError()) { + problemList.add(problem.getMessage()); } - throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString()); - } - } catch (RuntimeException ex) { - // if we encountered an IOException, unbox and throw it; - // if we encountered a ClassFormatException, box it as an IOException and throw it - // otherwise, it's a legit RuntimeException, - // not one of our checked exceptions boxed as unchecked; just rethrow - Throwable cause = ex.getCause(); - if (cause != null) { - if (cause instanceof IOException) { - throw (IOException) cause; - } else if (cause instanceof ClassFormatException) { - throw new IOException(cause); + } + } else { + for (ClassFile clazz : result.getClassFiles()) { + try { + MemJavaFileObject jfo = + (MemJavaFileObject) + fileManager.getJavaFileForOutput( + StandardLocation.CLASS_OUTPUT, + new String(clazz.fileName()), + JavaFileObject.Kind.CLASS, + null); + OutputStream os = jfo.openOutputStream(); + os.write(clazz.getBytes()); + } catch (IOException ex) { + throw new RuntimeException(ex); } + } } - throw ex; - } - } + } + }; + + problemList.clear(); - public CompilerOptions getCompilerOptions() { - return compilerOptions; + IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems(); + IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); + + try { + // Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, + // problemFactory, true); + Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory); + compiler.compile(targetCompilationUnits); + if (!problemList.isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String problem : problemList) { + sb.append("\t").append(problem).append("\n"); + } + throw new CodegenException( + "Compilation of " + id + " failed:\n" + source + "\n" + sb.toString()); + } + } catch (RuntimeException ex) { + // if we encountered an IOException, unbox and throw it; + // if we encountered a ClassFormatException, box it as an IOException and throw it + // otherwise, it's a legit RuntimeException, + // not one of our checked exceptions boxed as unchecked; just rethrow + Throwable cause = ex.getCause(); + if (cause != null) { + if (cause instanceof IOException) { + throw (IOException) cause; + } else if (cause instanceof ClassFormatException) { + throw new IOException(cause); + } + } + throw ex; } - + } + public CompilerOptions getCompilerOptions() { + return compilerOptions; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Evaluator.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Evaluator.java index d49d5dd175..5793eefc42 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Evaluator.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Evaluator.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -14,23 +14,21 @@ package com.querydsl.codegen.utils; /** - * Evaluator defines an interface for returning a value as a result of - * evaluating an expression using the given argument array - * + * Evaluator defines an interface for returning a value as a result of evaluating an expression + * using the given argument array + * * @author tiwe - * */ public interface Evaluator { - /** - * @param args - * @return - */ - T evaluate(Object... args); - - /** - * @return - */ - Class getType(); + /** + * @param args + * @return + */ + T evaluate(Object... args); + /** + * @return + */ + Class getType(); } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/EvaluatorFactory.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/EvaluatorFactory.java index 12a7d43ca4..0f30eed4eb 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/EvaluatorFactory.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/EvaluatorFactory.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -15,43 +15,44 @@ import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.Type; - import java.util.Map; /** - * * @author pgrant */ public interface EvaluatorFactory { - /** - * @param source - * @param projectionType - * @param names - * @param classes - * @param constants - * @return - */ - Evaluator createEvaluator(String source, Class projectionType, - String[] names, Class[] classes, Map constants); + /** + * @param source + * @param projectionType + * @param names + * @param classes + * @param constants + * @return + */ + Evaluator createEvaluator( + String source, + Class projectionType, + String[] names, + Class[] classes, + Map constants); - /** - * Create a new Evaluator instance - * - * @param - * projection type - * @param source - * expression in Java source code form - * @param projection - * type of the source expression - * @param names - * names of the arguments - * @param types - * types of the arguments - * @param constants - * @return - */ - Evaluator createEvaluator(String source, ClassType projection, String[] names, - Type[] types, Class[] classes, Map constants); - + /** + * Create a new Evaluator instance + * + * @param projection type + * @param source expression in Java source code form + * @param projection type of the source expression + * @param names names of the arguments + * @param types types of the arguments + * @param constants + * @return + */ + Evaluator createEvaluator( + String source, + ClassType projection, + String[] names, + Type[] types, + Class[] classes, + Map constants); } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JDKEvaluatorFactory.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JDKEvaluatorFactory.java index 2c5b731cd7..31ca1adccc 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JDKEvaluatorFactory.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JDKEvaluatorFactory.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -13,6 +13,8 @@ */ package com.querydsl.codegen.utils; +import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.Type; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; @@ -21,58 +23,65 @@ import java.util.Collections; import java.util.List; import java.util.Map; - import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardLocation; import javax.tools.ToolProvider; -import com.querydsl.codegen.utils.model.ClassType; -import com.querydsl.codegen.utils.model.Type; - /** * JDKEvaluatorFactory is a factory implementation for creating Evaluator instances - * + * * @author tiwe - * */ public class JDKEvaluatorFactory extends AbstractEvaluatorFactory { - private final MemFileManager fileManager; + private final MemFileManager fileManager; - private final String classpath; + private final String classpath; - private final List compilationOptions; + private final List compilationOptions; - private final JavaCompiler compiler; + private final JavaCompiler compiler; - public JDKEvaluatorFactory(URLClassLoader parent) { - this(parent, ToolProvider.getSystemJavaCompiler()); - } + public JDKEvaluatorFactory(URLClassLoader parent) { + this(parent, ToolProvider.getSystemJavaCompiler()); + } - public JDKEvaluatorFactory(URLClassLoader parent, JavaCompiler compiler) { - this.fileManager = new MemFileManager(parent, compiler.getStandardFileManager(null, null, null)); - this.compiler = compiler; - this.classpath = SimpleCompiler.getClassPath(parent); - this.loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); - this.compilationOptions = Arrays.asList("-classpath", classpath, "-g:none"); - } + public JDKEvaluatorFactory(URLClassLoader parent, JavaCompiler compiler) { + this.fileManager = + new MemFileManager(parent, compiler.getStandardFileManager(null, null, null)); + this.compiler = compiler; + this.classpath = SimpleCompiler.getClassPath(parent); + this.loader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); + this.compilationOptions = Arrays.asList("-classpath", classpath, "-g:none"); + } - protected void compile(String source, ClassType projectionType, String[] names, Type[] types, - String id, Map constants) throws IOException { - // create source - source = createSource(source, projectionType, names, types, id, constants); + protected void compile( + String source, + ClassType projectionType, + String[] names, + Type[] types, + String id, + Map constants) + throws IOException { + // create source + source = createSource(source, projectionType, names, types, id, constants); - // compile - SimpleJavaFileObject javaFileObject = new MemSourceFileObject(id, source); - Writer out = new StringWriter(); + // compile + SimpleJavaFileObject javaFileObject = new MemSourceFileObject(id, source); + Writer out = new StringWriter(); - CompilationTask task = compiler.getTask(out, fileManager, null, compilationOptions, null, - Collections.singletonList(javaFileObject)); - if (!task.call().booleanValue()) { - throw new CodegenException("Compilation of " + source + " failed.\n" + out.toString()); - } + CompilationTask task = + compiler.getTask( + out, + fileManager, + null, + compilationOptions, + null, + Collections.singletonList(javaFileObject)); + if (!task.call().booleanValue()) { + throw new CodegenException("Compilation of " + source + " failed.\n" + out.toString()); } - + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JavaWriter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JavaWriter.java index 762a2d5c87..3f1d36fc7c 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JavaWriter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/JavaWriter.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -13,6 +13,8 @@ */ package com.querydsl.codegen.utils; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.Type; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; @@ -24,469 +26,490 @@ import java.util.Stack; import java.util.function.Function; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.Type; - /** * JavaWriter is the default implementation of the CodeWriter interface - * + * * @author tiwe - * */ public final class JavaWriter extends AbstractCodeWriter { - private static final String EXTENDS = " extends "; + private static final String EXTENDS = " extends "; - private static final String IMPLEMENTS = " implements "; + private static final String IMPLEMENTS = " implements "; - private static final String IMPORT = "import "; + private static final String IMPORT = "import "; - private static final String IMPORT_STATIC = "import static "; + private static final String IMPORT_STATIC = "import static "; - private static final String PACKAGE = "package "; + private static final String PACKAGE = "package "; - private static final String PRIVATE = "private "; + private static final String PRIVATE = "private "; - private static final String PRIVATE_FINAL = "private final "; + private static final String PRIVATE_FINAL = "private final "; - private static final String PRIVATE_STATIC_FINAL = "private static final "; + private static final String PRIVATE_STATIC_FINAL = "private static final "; - private static final String PROTECTED = "protected "; + private static final String PROTECTED = "protected "; - private static final String PROTECTED_FINAL = "protected final "; + private static final String PROTECTED_FINAL = "protected final "; - private static final String PUBLIC = "public "; + private static final String PUBLIC = "public "; - private static final String PUBLIC_CLASS = "public class "; + private static final String PUBLIC_CLASS = "public class "; - private static final String PUBLIC_FINAL = "public final "; + private static final String PUBLIC_FINAL = "public final "; - private static final String PUBLIC_INTERFACE = "public interface "; + private static final String PUBLIC_INTERFACE = "public interface "; - private static final String PUBLIC_STATIC = "public static "; + private static final String PUBLIC_STATIC = "public static "; - private static final String PUBLIC_STATIC_FINAL = "public static final "; + private static final String PUBLIC_STATIC_FINAL = "public static final "; - private final Set classes = new HashSet(); + private final Set classes = new HashSet(); - private final Set packages = new HashSet(); + private final Set packages = new HashSet(); - private final Stack types = new Stack(); + private final Stack types = new Stack(); - public JavaWriter(Appendable appendable) { - super(appendable, 4); - this.packages.add("java.lang"); - } + public JavaWriter(Appendable appendable) { + super(appendable, 4); + this.packages.add("java.lang"); + } - @Override - public JavaWriter annotation(Annotation annotation) throws IOException { - beginLine().append("@").appendType(annotation.annotationType()); - Method[] methods = annotation.annotationType().getDeclaredMethods(); - if (methods.length == 1 && methods[0].getName().equals("value")) { - try { - Object value = methods[0].invoke(annotation); - append("("); - annotationConstant(value); - append(")"); - } catch (IllegalArgumentException e) { - throw new CodegenException(e); - } catch (IllegalAccessException e) { - throw new CodegenException(e); - } catch (InvocationTargetException e) { - throw new CodegenException(e); - } - } else { - boolean first = true; - for (Method method : methods) { - try { - Object value = method.invoke(annotation); - if (value == null || value.equals(method.getDefaultValue())) { - continue; - } else if (value.getClass().isArray() - && Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) { - continue; - } else if (!first) { - append(Symbols.COMMA); - } else { - append("("); - } - append(method.getName()).append("="); - annotationConstant(value); - } catch (IllegalArgumentException e) { - throw new CodegenException(e); - } catch (IllegalAccessException e) { - throw new CodegenException(e); - } catch (InvocationTargetException e) { - throw new CodegenException(e); - } - first = false; - } - if (!first) { - append(")"); - } - } - return nl(); - } - - @Override - public JavaWriter annotation(Class annotation) throws IOException { - return beginLine().append("@").appendType(annotation).nl(); - } - - @SuppressWarnings("unchecked") - private void annotationConstant(Object value) throws IOException { - if (value.getClass().isArray()) { - append("{"); - boolean first = true; - for (Object o : (Object[]) value) { - if (!first) { - append(", "); - } - annotationConstant(o); - first = false; - } - append("}"); - } else if (value instanceof Class) { - appendType((Class) value).append(".class"); - } else if (value instanceof Number || value instanceof Boolean) { - append(value.toString()); - } else if (value instanceof Enum) { - Enum enumValue = (Enum) value; - if (classes.contains(enumValue.getClass().getName()) - || packages.contains(enumValue.getClass().getPackage().getName())) { - append(enumValue.name()); - } else { - append(enumValue.getDeclaringClass().getName()).append(Symbols.DOT).append(enumValue.name()); - } - } else if (value instanceof String) { - String escaped = StringUtils.escapeJava(value.toString()); - append(Symbols.QUOTE).append(escaped.replace("\\/", "/")).append(Symbols.QUOTE); - } else { - throw new IllegalArgumentException("Unsupported annotation value : " + value); - } - } - - private JavaWriter appendType(Class type) throws IOException { - if (classes.contains(type.getName()) || packages.contains(type.getPackage().getName())) { - append(type.getSimpleName()); - } else { - append(type.getName()); - } - return this; - } - - @Override - public JavaWriter beginClass(Type type) throws IOException { - return beginClass(type, null); - } - - @Override - public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException { - packages.add(type.getPackageName()); - beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes)); - if (superClass != null) { - append(EXTENDS).append(superClass.getGenericName(false, packages, classes)); - } - if (interfaces.length > 0) { - append(IMPLEMENTS); - for (int i = 0; i < interfaces.length; i++) { - if (i > 0) { - append(Symbols.COMMA); - } - append(interfaces[i].getGenericName(false, packages, classes)); - } - } - append(" {").nl().nl(); - goIn(); - types.push(type); - return this; - } - - @Override - public JavaWriter beginConstructor(Collection parameters, - Function transformer) throws IOException { - types.push(types.peek()); - beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters, transformer) - .append(" {").nl(); - return goIn(); - } - - @Override - public JavaWriter beginConstructor(Parameter... parameters) throws IOException { - types.push(types.peek()); - beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl(); - return goIn(); - } - - @Override - public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException { - packages.add(type.getPackageName()); - beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes)); - if (interfaces.length > 0) { - append(EXTENDS); - for (int i = 0; i < interfaces.length; i++) { - if (i > 0) { - append(Symbols.COMMA); - } - append(interfaces[i].getGenericName(false, packages, classes)); - } - } - append(" {").nl().nl(); - goIn(); - types.push(type); - return this; - } - - private JavaWriter beginMethod(String modifiers, Type returnType, String methodName, - Parameter... args) throws IOException { - types.push(types.peek()); - beginLine( - modifiers, returnType.getGenericName(true, packages, classes), Symbols.SPACE, methodName) - .params(args).append(" {").nl(); - return goIn(); - } - - @Override - public JavaWriter beginPublicMethod(Type returnType, String methodName, - Collection parameters, Function transformer) throws IOException { - return beginMethod(PUBLIC, returnType, methodName, transform(parameters, transformer)); - } - - @Override - public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) - throws IOException { - return beginMethod(PUBLIC, returnType, methodName, args); - } - - @Override - public JavaWriter beginStaticMethod(Type returnType, String methodName, - Collection parameters, Function transformer) throws IOException { - return beginMethod(PUBLIC_STATIC, returnType, methodName, - transform(parameters, transformer)); - } - - @Override - public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) - throws IOException { - return beginMethod(PUBLIC_STATIC, returnType, methodName, args); - } - - @Override - public JavaWriter end() throws IOException { - types.pop(); - goOut(); - return line("}").nl(); - } - - @Override - public JavaWriter field(Type type, String name) throws IOException { - return line(type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.SEMICOLON).nl(); - } - - private JavaWriter field(String modifier, Type type, String name) throws IOException { - return line( - modifier, type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.SEMICOLON) - .nl(); - } - - private JavaWriter field(String modifier, Type type, String name, String value) - throws IOException { - return line( - modifier, type.getGenericName(true, packages, classes), Symbols.SPACE, name, - Symbols.ASSIGN, value, Symbols.SEMICOLON).nl(); - } - - - @Override - public String getClassConstant(String className) { - return className + ".class"; - } - - @Override - public String getGenericName(boolean asArgType, Type type) { - return type.getGenericName(asArgType, packages, classes); - } - - @Override - public String getRawName(Type type) { - return type.getRawName(packages, classes); - } - - @Override - public JavaWriter imports(Class... imports) throws IOException { - for (Class cl : imports) { - classes.add(cl.getName()); - line(IMPORT, cl.getName(), Symbols.SEMICOLON); - } - nl(); - return this; - } - - @Override - public JavaWriter imports(Package... imports) throws IOException { - for (Package p : imports) { - packages.add(p.getName()); - line(IMPORT, p.getName(), ".*;"); - } - nl(); - return this; - } - - @Override - public JavaWriter importClasses(String... imports) throws IOException { - for (String cl : imports) { - classes.add(cl); - line(IMPORT, cl, Symbols.SEMICOLON); - } - nl(); - return this; - } - - @Override - public JavaWriter importPackages(String... imports) throws IOException { - for (String p : imports) { - packages.add(p); - line(IMPORT, p, ".*;"); - } - nl(); - return this; - } - - @Override - public JavaWriter javadoc(String... lines) throws IOException { - line("/**"); - for (String line : lines) { - line(" * ", line); - } - return line(" */"); - } - - @Override - public JavaWriter packageDecl(String packageName) throws IOException { - packages.add(packageName); - return line(PACKAGE, packageName, Symbols.SEMICOLON).nl(); - } - - private JavaWriter params(Collection parameters, Function transformer) - throws IOException { + @Override + public JavaWriter annotation(Annotation annotation) throws IOException { + beginLine().append("@").appendType(annotation.annotationType()); + Method[] methods = annotation.annotationType().getDeclaredMethods(); + if (methods.length == 1 && methods[0].getName().equals("value")) { + try { + Object value = methods[0].invoke(annotation); append("("); - boolean first = true; - for (T param : parameters) { - if (!first) { - append(Symbols.COMMA); - } - param(transformer.apply(param)); - first = false; - } + annotationConstant(value); append(")"); - return this; - } - - private JavaWriter params(Parameter... params) throws IOException { - append("("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - append(Symbols.COMMA); - } - param(params[i]); + } catch (IllegalArgumentException e) { + throw new CodegenException(e); + } catch (IllegalAccessException e) { + throw new CodegenException(e); + } catch (InvocationTargetException e) { + throw new CodegenException(e); + } + } else { + boolean first = true; + for (Method method : methods) { + try { + Object value = method.invoke(annotation); + if (value == null || value.equals(method.getDefaultValue())) { + continue; + } else if (value.getClass().isArray() + && Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) { + continue; + } else if (!first) { + append(Symbols.COMMA); + } else { + append("("); + } + append(method.getName()).append("="); + annotationConstant(value); + } catch (IllegalArgumentException e) { + throw new CodegenException(e); + } catch (IllegalAccessException e) { + throw new CodegenException(e); + } catch (InvocationTargetException e) { + throw new CodegenException(e); } + first = false; + } + if (!first) { append(")"); - return this; - } - - private JavaWriter param(Parameter parameter) throws IOException { - append(parameter.getType().getGenericName(true, packages, classes)); - append(" "); - append(parameter.getName()); - return this; - } - - @Override - public JavaWriter privateField(Type type, String name) throws IOException { - return field(PRIVATE, type, name); - } - - @Override - public JavaWriter privateFinal(Type type, String name) throws IOException { - return field(PRIVATE_FINAL, type, name); - } - - @Override - public JavaWriter privateFinal(Type type, String name, String value) throws IOException { - return field(PRIVATE_FINAL, type, name, value); - } - - @Override - public JavaWriter privateStaticFinal(Type type, String name, String value) throws IOException { - return field(PRIVATE_STATIC_FINAL, type, name, value); - } - - @Override - public JavaWriter protectedField(Type type, String name) throws IOException { - return field(PROTECTED, type, name); - } - - @Override - public JavaWriter protectedFinal(Type type, String name) throws IOException { - return field(PROTECTED_FINAL, type, name); - } - - @Override - public JavaWriter protectedFinal(Type type, String name, String value) throws IOException { - return field(PROTECTED_FINAL, type, name, value); - } - - @Override - public JavaWriter publicField(Type type, String name) throws IOException { - return field(PUBLIC, type, name); - } - - @Override - public JavaWriter publicField(Type type, String name, String value) throws IOException { - return field(PUBLIC, type, name, value); - } - - @Override - public JavaWriter publicFinal(Type type, String name) throws IOException { - return field(PUBLIC_FINAL, type, name); - } - - @Override - public JavaWriter publicFinal(Type type, String name, String value) throws IOException { - return field(PUBLIC_FINAL, type, name, value); - } - - @Override - public JavaWriter publicStaticFinal(Type type, String name, String value) throws IOException { - return field(PUBLIC_STATIC_FINAL, type, name, value); - } - - @Override - public JavaWriter staticimports(Class... imports) throws IOException { - for (Class cl : imports) { - line(IMPORT_STATIC, cl.getName(), ".*;"); + } + } + return nl(); + } + + @Override + public JavaWriter annotation(Class annotation) throws IOException { + return beginLine().append("@").appendType(annotation).nl(); + } + + @SuppressWarnings("unchecked") + private void annotationConstant(Object value) throws IOException { + if (value.getClass().isArray()) { + append("{"); + boolean first = true; + for (Object o : (Object[]) value) { + if (!first) { + append(", "); } - return this; - } - - @Override - public JavaWriter suppressWarnings(String type) throws IOException { - return line("@SuppressWarnings(\"", type, "\")"); - } - - @Override - public CodeWriter suppressWarnings(String... types) throws IOException { - return annotation(new MultiSuppressWarnings(types)); - } - - private Parameter[] transform(Collection parameters, - Function transformer) { - Parameter[] rv = new Parameter[parameters.size()]; - int i = 0; - for (T value : parameters) { - rv[i++] = transformer.apply(value); + annotationConstant(o); + first = false; + } + append("}"); + } else if (value instanceof Class) { + appendType((Class) value).append(".class"); + } else if (value instanceof Number || value instanceof Boolean) { + append(value.toString()); + } else if (value instanceof Enum) { + Enum enumValue = (Enum) value; + if (classes.contains(enumValue.getClass().getName()) + || packages.contains(enumValue.getClass().getPackage().getName())) { + append(enumValue.name()); + } else { + append(enumValue.getDeclaringClass().getName()) + .append(Symbols.DOT) + .append(enumValue.name()); + } + } else if (value instanceof String) { + String escaped = StringUtils.escapeJava(value.toString()); + append(Symbols.QUOTE).append(escaped.replace("\\/", "/")).append(Symbols.QUOTE); + } else { + throw new IllegalArgumentException("Unsupported annotation value : " + value); + } + } + + private JavaWriter appendType(Class type) throws IOException { + if (classes.contains(type.getName()) || packages.contains(type.getPackage().getName())) { + append(type.getSimpleName()); + } else { + append(type.getName()); + } + return this; + } + + @Override + public JavaWriter beginClass(Type type) throws IOException { + return beginClass(type, null); + } + + @Override + public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException { + packages.add(type.getPackageName()); + beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes)); + if (superClass != null) { + append(EXTENDS).append(superClass.getGenericName(false, packages, classes)); + } + if (interfaces.length > 0) { + append(IMPLEMENTS); + for (int i = 0; i < interfaces.length; i++) { + if (i > 0) { + append(Symbols.COMMA); } - return rv; - } - + append(interfaces[i].getGenericName(false, packages, classes)); + } + } + append(" {").nl().nl(); + goIn(); + types.push(type); + return this; + } + + @Override + public JavaWriter beginConstructor( + Collection parameters, Function transformer) throws IOException { + types.push(types.peek()); + beginLine(PUBLIC, types.peek().getSimpleName()) + .params(parameters, transformer) + .append(" {") + .nl(); + return goIn(); + } + + @Override + public JavaWriter beginConstructor(Parameter... parameters) throws IOException { + types.push(types.peek()); + beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl(); + return goIn(); + } + + @Override + public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException { + packages.add(type.getPackageName()); + beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes)); + if (interfaces.length > 0) { + append(EXTENDS); + for (int i = 0; i < interfaces.length; i++) { + if (i > 0) { + append(Symbols.COMMA); + } + append(interfaces[i].getGenericName(false, packages, classes)); + } + } + append(" {").nl().nl(); + goIn(); + types.push(type); + return this; + } + + private JavaWriter beginMethod( + String modifiers, Type returnType, String methodName, Parameter... args) throws IOException { + types.push(types.peek()); + beginLine( + modifiers, + returnType.getGenericName(true, packages, classes), + Symbols.SPACE, + methodName) + .params(args) + .append(" {") + .nl(); + return goIn(); + } + + @Override + public JavaWriter beginPublicMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException { + return beginMethod(PUBLIC, returnType, methodName, transform(parameters, transformer)); + } + + @Override + public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) + throws IOException { + return beginMethod(PUBLIC, returnType, methodName, args); + } + + @Override + public JavaWriter beginStaticMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException { + return beginMethod(PUBLIC_STATIC, returnType, methodName, transform(parameters, transformer)); + } + + @Override + public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) + throws IOException { + return beginMethod(PUBLIC_STATIC, returnType, methodName, args); + } + + @Override + public JavaWriter end() throws IOException { + types.pop(); + goOut(); + return line("}").nl(); + } + + @Override + public JavaWriter field(Type type, String name) throws IOException { + return line( + type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.SEMICOLON) + .nl(); + } + + private JavaWriter field(String modifier, Type type, String name) throws IOException { + return line( + modifier, + type.getGenericName(true, packages, classes), + Symbols.SPACE, + name, + Symbols.SEMICOLON) + .nl(); + } + + private JavaWriter field(String modifier, Type type, String name, String value) + throws IOException { + return line( + modifier, + type.getGenericName(true, packages, classes), + Symbols.SPACE, + name, + Symbols.ASSIGN, + value, + Symbols.SEMICOLON) + .nl(); + } + + @Override + public String getClassConstant(String className) { + return className + ".class"; + } + + @Override + public String getGenericName(boolean asArgType, Type type) { + return type.getGenericName(asArgType, packages, classes); + } + + @Override + public String getRawName(Type type) { + return type.getRawName(packages, classes); + } + + @Override + public JavaWriter imports(Class... imports) throws IOException { + for (Class cl : imports) { + classes.add(cl.getName()); + line(IMPORT, cl.getName(), Symbols.SEMICOLON); + } + nl(); + return this; + } + + @Override + public JavaWriter imports(Package... imports) throws IOException { + for (Package p : imports) { + packages.add(p.getName()); + line(IMPORT, p.getName(), ".*;"); + } + nl(); + return this; + } + + @Override + public JavaWriter importClasses(String... imports) throws IOException { + for (String cl : imports) { + classes.add(cl); + line(IMPORT, cl, Symbols.SEMICOLON); + } + nl(); + return this; + } + + @Override + public JavaWriter importPackages(String... imports) throws IOException { + for (String p : imports) { + packages.add(p); + line(IMPORT, p, ".*;"); + } + nl(); + return this; + } + + @Override + public JavaWriter javadoc(String... lines) throws IOException { + line("/**"); + for (String line : lines) { + line(" * ", line); + } + return line(" */"); + } + + @Override + public JavaWriter packageDecl(String packageName) throws IOException { + packages.add(packageName); + return line(PACKAGE, packageName, Symbols.SEMICOLON).nl(); + } + + private JavaWriter params(Collection parameters, Function transformer) + throws IOException { + append("("); + boolean first = true; + for (T param : parameters) { + if (!first) { + append(Symbols.COMMA); + } + param(transformer.apply(param)); + first = false; + } + append(")"); + return this; + } + + private JavaWriter params(Parameter... params) throws IOException { + append("("); + for (int i = 0; i < params.length; i++) { + if (i > 0) { + append(Symbols.COMMA); + } + param(params[i]); + } + append(")"); + return this; + } + + private JavaWriter param(Parameter parameter) throws IOException { + append(parameter.getType().getGenericName(true, packages, classes)); + append(" "); + append(parameter.getName()); + return this; + } + + @Override + public JavaWriter privateField(Type type, String name) throws IOException { + return field(PRIVATE, type, name); + } + + @Override + public JavaWriter privateFinal(Type type, String name) throws IOException { + return field(PRIVATE_FINAL, type, name); + } + + @Override + public JavaWriter privateFinal(Type type, String name, String value) throws IOException { + return field(PRIVATE_FINAL, type, name, value); + } + + @Override + public JavaWriter privateStaticFinal(Type type, String name, String value) throws IOException { + return field(PRIVATE_STATIC_FINAL, type, name, value); + } + + @Override + public JavaWriter protectedField(Type type, String name) throws IOException { + return field(PROTECTED, type, name); + } + + @Override + public JavaWriter protectedFinal(Type type, String name) throws IOException { + return field(PROTECTED_FINAL, type, name); + } + + @Override + public JavaWriter protectedFinal(Type type, String name, String value) throws IOException { + return field(PROTECTED_FINAL, type, name, value); + } + + @Override + public JavaWriter publicField(Type type, String name) throws IOException { + return field(PUBLIC, type, name); + } + + @Override + public JavaWriter publicField(Type type, String name, String value) throws IOException { + return field(PUBLIC, type, name, value); + } + + @Override + public JavaWriter publicFinal(Type type, String name) throws IOException { + return field(PUBLIC_FINAL, type, name); + } + + @Override + public JavaWriter publicFinal(Type type, String name, String value) throws IOException { + return field(PUBLIC_FINAL, type, name, value); + } + + @Override + public JavaWriter publicStaticFinal(Type type, String name, String value) throws IOException { + return field(PUBLIC_STATIC_FINAL, type, name, value); + } + + @Override + public JavaWriter staticimports(Class... imports) throws IOException { + for (Class cl : imports) { + line(IMPORT_STATIC, cl.getName(), ".*;"); + } + return this; + } + + @Override + public JavaWriter suppressWarnings(String type) throws IOException { + return line("@SuppressWarnings(\"", type, "\")"); + } + + @Override + public CodeWriter suppressWarnings(String... types) throws IOException { + return annotation(new MultiSuppressWarnings(types)); + } + + private Parameter[] transform(Collection parameters, Function transformer) { + Parameter[] rv = new Parameter[parameters.size()]; + int i = 0; + for (T value : parameters) { + rv[i++] = transformer.apply(value); + } + return rv; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/LocationAndKind.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/LocationAndKind.java index 1aef4714c1..fb03401326 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/LocationAndKind.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/LocationAndKind.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -18,41 +18,39 @@ /** * LocationAndKind defines a pair of Location and Kind - * + * * @author tiwe - * */ public class LocationAndKind { - private final Kind kind; + private final Kind kind; - private final Location location; + private final Location location; - public LocationAndKind(Location location, Kind kind) { - this.location = location; - this.kind = kind; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } else if (obj instanceof LocationAndKind) { - LocationAndKind other = (LocationAndKind) obj; - return location.equals(other.location) && kind.equals(other.kind); - } else { - return false; - } - } + public LocationAndKind(Location location, Kind kind) { + this.location = location; + this.kind = kind; + } - @Override - public int hashCode() { - return kind.hashCode() * 31 + location.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof LocationAndKind) { + LocationAndKind other = (LocationAndKind) obj; + return location.equals(other.location) && kind.equals(other.kind); + } else { + return false; } + } - @Override - public String toString() { - return kind.toString() + "@" + location.toString(); - } + @Override + public int hashCode() { + return kind.hashCode() * 31 + location.hashCode(); + } + @Override + public String toString() { + return kind.toString() + "@" + location.toString(); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemClassLoader.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemClassLoader.java index 90bcd12410..c33876cd13 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemClassLoader.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemClassLoader.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -22,105 +22,103 @@ import java.util.Enumeration; import java.util.List; import java.util.Map; - import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardLocation; /** * MemClassLoader is a mmemory based implementation of the ClassLoader interface - * + * * @author tiwe - * */ public final class MemClassLoader extends ClassLoader { - private static final LocationAndKind CLASS_KEY = new LocationAndKind( - StandardLocation.CLASS_OUTPUT, Kind.CLASS); + private static final LocationAndKind CLASS_KEY = + new LocationAndKind(StandardLocation.CLASS_OUTPUT, Kind.CLASS); - private static final LocationAndKind OTHER_KEY = new LocationAndKind( - StandardLocation.CLASS_OUTPUT, Kind.OTHER); + private static final LocationAndKind OTHER_KEY = + new LocationAndKind(StandardLocation.CLASS_OUTPUT, Kind.OTHER); - private static final LocationAndKind SOURCE_KEY = new LocationAndKind( - StandardLocation.CLASS_OUTPUT, Kind.SOURCE); + private static final LocationAndKind SOURCE_KEY = + new LocationAndKind(StandardLocation.CLASS_OUTPUT, Kind.SOURCE); - private final Map> memFileSystem; + private final Map> memFileSystem; - public MemClassLoader(ClassLoader parent, - Map> ramFileSystem) { - super(parent); - this.memFileSystem = ramFileSystem; - } + public MemClassLoader( + ClassLoader parent, Map> ramFileSystem) { + super(parent); + this.memFileSystem = ramFileSystem; + } - @Override - protected Class findClass(String name) throws ClassNotFoundException { - JavaFileObject jfo = memFileSystem.get(CLASS_KEY).get(name); - if (jfo != null) { - byte[] bytes = ((MemJavaFileObject) jfo).getByteArray(); - return defineClass(name, bytes, 0, bytes.length); - } else { - return super.findClass(name); - } + @Override + protected Class findClass(String name) throws ClassNotFoundException { + JavaFileObject jfo = memFileSystem.get(CLASS_KEY).get(name); + if (jfo != null) { + byte[] bytes = ((MemJavaFileObject) jfo).getByteArray(); + return defineClass(name, bytes, 0, bytes.length); + } else { + return super.findClass(name); } + } - @Override - protected URL findResource(String name) { - URL retValue = super.findResource(name); - if (retValue != null) { - return retValue; - } else { - JavaFileObject jfo = getFileObject(name); - if (jfo != null) { - try { - return jfo.toUri().toURL(); - } catch (MalformedURLException ex) { - return null; - } - } else { - return null; - } + @Override + protected URL findResource(String name) { + URL retValue = super.findResource(name); + if (retValue != null) { + return retValue; + } else { + JavaFileObject jfo = getFileObject(name); + if (jfo != null) { + try { + return jfo.toUri().toURL(); + } catch (MalformedURLException ex) { + return null; } + } else { + return null; + } } + } - private JavaFileObject getFileObject(String n) { - LocationAndKind key; - String name; - if (n.endsWith(Kind.CLASS.extension)) { - name = n.replace('.', '/') + Kind.CLASS.extension; - key = CLASS_KEY; - } else if (n.endsWith(Kind.SOURCE.extension)) { - name = n.replace('.', '/') + Kind.SOURCE.extension; - key = SOURCE_KEY; - } else { - name = n; - key = OTHER_KEY; - } - if (memFileSystem.containsKey(key)) { - return memFileSystem.get(key).get(name); - } else { - return null; - } + private JavaFileObject getFileObject(String n) { + LocationAndKind key; + String name; + if (n.endsWith(Kind.CLASS.extension)) { + name = n.replace('.', '/') + Kind.CLASS.extension; + key = CLASS_KEY; + } else if (n.endsWith(Kind.SOURCE.extension)) { + name = n.replace('.', '/') + Kind.SOURCE.extension; + key = SOURCE_KEY; + } else { + name = n; + key = OTHER_KEY; + } + if (memFileSystem.containsKey(key)) { + return memFileSystem.get(key).get(name); + } else { + return null; } + } - @Override - public InputStream getResourceAsStream(String name) { - JavaFileObject jfo = getFileObject(name); - if (jfo != null) { - byte[] bytes = ((MemJavaFileObject) jfo).getByteArray(); - return new ByteArrayInputStream(bytes); - } else { - return null; - } + @Override + public InputStream getResourceAsStream(String name) { + JavaFileObject jfo = getFileObject(name); + if (jfo != null) { + byte[] bytes = ((MemJavaFileObject) jfo).getByteArray(); + return new ByteArrayInputStream(bytes); + } else { + return null; } + } - @Override - public Enumeration getResources(String name) throws IOException { - List retValue; - retValue = Collections.list(super.getResources(name)); - JavaFileObject jfo = getFileObject(name); - if (jfo != null) { - retValue.add(jfo.toUri().toURL()); - } - return Collections.enumeration(retValue); + @Override + public Enumeration getResources(String name) throws IOException { + List retValue; + retValue = Collections.list(super.getResources(name)); + JavaFileObject jfo = getFileObject(name); + if (jfo != null) { + retValue.add(jfo.toUri().toURL()); } + return Collections.enumeration(retValue); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileManager.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileManager.java index ab34d13768..d7c51b9a40 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileManager.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileManager.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -19,148 +19,149 @@ import java.util.List; import java.util.Map; import java.util.Set; - import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; +import javax.tools.JavaFileObject.Kind; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; -import javax.tools.JavaFileObject.Kind; /** - * MemFileManager is a memory based implementation of the JavaFileManager - * interface - * + * MemFileManager is a memory based implementation of the JavaFileManager interface + * * @author tiwe - * */ public class MemFileManager extends ForwardingJavaFileManager { - private final ClassLoader classLoader; - - private final Map> ramFileSystem; - - private final String urlPrefix; - - public MemFileManager(ClassLoader parent, StandardJavaFileManager sjfm) { - super(sjfm); - ramFileSystem = new HashMap>(); - Map classLoaderContent = new HashMap(); - ramFileSystem.put(new LocationAndKind(StandardLocation.CLASS_OUTPUT, Kind.CLASS), - classLoaderContent); - classLoader = new MemClassLoader(parent, ramFileSystem); - urlPrefix = MemFileSystemRegistry.DEFAULT.getUrlPrefix(this); - } - - @Override - public ClassLoader getClassLoader(JavaFileManager.Location location) { - return classLoader; + private final ClassLoader classLoader; + + private final Map> ramFileSystem; + + private final String urlPrefix; + + public MemFileManager(ClassLoader parent, StandardJavaFileManager sjfm) { + super(sjfm); + ramFileSystem = new HashMap>(); + Map classLoaderContent = new HashMap(); + ramFileSystem.put( + new LocationAndKind(StandardLocation.CLASS_OUTPUT, Kind.CLASS), classLoaderContent); + classLoader = new MemClassLoader(parent, ramFileSystem); + urlPrefix = MemFileSystemRegistry.DEFAULT.getUrlPrefix(this); + } + + @Override + public ClassLoader getClassLoader(JavaFileManager.Location location) { + return classLoader; + } + + @Override + public FileObject getFileForInput( + JavaFileManager.Location location, String packageName, String relativeName) + throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public FileObject getFileForOutput( + JavaFileManager.Location location, + String packageName, + String relativeName, + FileObject sibling) + throws IOException { + String name = null; + if ("".equals(packageName)) { + name = relativeName; + } else { + name = packageName.replace('.', '/') + "/" + relativeName; } - - @Override - public FileObject getFileForInput(JavaFileManager.Location location, String packageName, - String relativeName) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public FileObject getFileForOutput(JavaFileManager.Location location, String packageName, - String relativeName, FileObject sibling) throws IOException { - String name = null; - if ("".equals(packageName)) { - name = relativeName; - } else { - name = packageName.replace('.', '/') + "/" + relativeName; - } - LocationAndKind key = new LocationAndKind(location, Kind.OTHER); - if (ramFileSystem.containsKey(key)) { - JavaFileObject jfo = ramFileSystem.get(key).get(name); - if (jfo != null) { - return jfo; - } - } - JavaFileObject jfo = new MemJavaFileObject(urlPrefix, name, Kind.OTHER); - register(key, jfo); + LocationAndKind key = new LocationAndKind(location, Kind.OTHER); + if (ramFileSystem.containsKey(key)) { + JavaFileObject jfo = ramFileSystem.get(key).get(name); + if (jfo != null) { return jfo; + } } - - @Override - public JavaFileObject getJavaFileForOutput(Location location, String name, Kind kind, - FileObject sibling) throws IOException { - JavaFileObject javaFileObject = null; - LocationAndKind key = new LocationAndKind(location, kind); - - if (ramFileSystem.containsKey(key)) { - javaFileObject = ramFileSystem.get(key).get(name); - if (javaFileObject != null) { - return javaFileObject; - } - } - if (kind == Kind.SOURCE) { - javaFileObject = new MemSourceFileObject(name); - } else { - javaFileObject = new MemJavaFileObject(urlPrefix, name, kind); - } - register(key, javaFileObject); + JavaFileObject jfo = new MemJavaFileObject(urlPrefix, name, Kind.OTHER); + register(key, jfo); + return jfo; + } + + @Override + public JavaFileObject getJavaFileForOutput( + Location location, String name, Kind kind, FileObject sibling) throws IOException { + JavaFileObject javaFileObject = null; + LocationAndKind key = new LocationAndKind(location, kind); + + if (ramFileSystem.containsKey(key)) { + javaFileObject = ramFileSystem.get(key).get(name); + if (javaFileObject != null) { return javaFileObject; + } } - - @Override - public String inferBinaryName(Location loc, JavaFileObject javaFileObject) { - String result; - if (loc == StandardLocation.CLASS_PATH && javaFileObject instanceof MemJavaFileObject) { - result = javaFileObject.getName(); - } else { - result = super.inferBinaryName(loc, javaFileObject); - } - return result; + if (kind == Kind.SOURCE) { + javaFileObject = new MemSourceFileObject(name); + } else { + javaFileObject = new MemJavaFileObject(urlPrefix, name, kind); } - - @Override - public boolean isSameFile(FileObject a, FileObject b) { - return a.equals(b); + register(key, javaFileObject); + return javaFileObject; + } + + @Override + public String inferBinaryName(Location loc, JavaFileObject javaFileObject) { + String result; + if (loc == StandardLocation.CLASS_PATH && javaFileObject instanceof MemJavaFileObject) { + result = javaFileObject.getName(); + } else { + result = super.inferBinaryName(loc, javaFileObject); } + return result; + } - @Override - public Iterable list(Location location, String pkg, Set kinds, - boolean recurse) throws IOException { + @Override + public boolean isSameFile(FileObject a, FileObject b) { + return a.equals(b); + } - List result = new ArrayList(); - for (JavaFileObject f : super.list(location, pkg, kinds, recurse)) { - result.add(f); - } - if (location == StandardLocation.CLASS_PATH) { - location = StandardLocation.CLASS_OUTPUT; - } + @Override + public Iterable list( + Location location, String pkg, Set kinds, boolean recurse) throws IOException { - for (Kind kind : kinds) { - LocationAndKind key = new LocationAndKind(location, kind); - if (ramFileSystem.containsKey(key)) { - Map locatedFiles = ramFileSystem.get(key); - for (Map.Entry entry : locatedFiles.entrySet()) { - String name = entry.getKey(); - String packageName = ""; - if (name.indexOf('.') > -1) { - packageName = name.substring(0, name.lastIndexOf('.')); - } - if (recurse ? packageName.startsWith(pkg) : packageName.equals(pkg)) { - JavaFileObject candidate = entry.getValue(); - if (kinds.contains(candidate.getKind())) { - result.add(candidate); - } - } - } - } - } - return result; + List result = new ArrayList(); + for (JavaFileObject f : super.list(location, pkg, kinds, recurse)) { + result.add(f); + } + if (location == StandardLocation.CLASS_PATH) { + location = StandardLocation.CLASS_OUTPUT; } - private void register(LocationAndKind key, JavaFileObject javaFileObject) { - if (!ramFileSystem.containsKey(key)) { - ramFileSystem.put(key, new HashMap()); + for (Kind kind : kinds) { + LocationAndKind key = new LocationAndKind(location, kind); + if (ramFileSystem.containsKey(key)) { + Map locatedFiles = ramFileSystem.get(key); + for (Map.Entry entry : locatedFiles.entrySet()) { + String name = entry.getKey(); + String packageName = ""; + if (name.indexOf('.') > -1) { + packageName = name.substring(0, name.lastIndexOf('.')); + } + if (recurse ? packageName.startsWith(pkg) : packageName.equals(pkg)) { + JavaFileObject candidate = entry.getValue(); + if (kinds.contains(candidate.getKind())) { + result.add(candidate); + } + } } - ramFileSystem.get(key).put(javaFileObject.getName(), javaFileObject); + } } + return result; + } + private void register(LocationAndKind key, JavaFileObject javaFileObject) { + if (!ramFileSystem.containsKey(key)) { + ramFileSystem.put(key, new HashMap()); + } + ramFileSystem.get(key).put(javaFileObject.getName(), javaFileObject); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileSystemRegistry.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileSystemRegistry.java index 85e4f1dc1b..293ec4f71c 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileSystemRegistry.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemFileSystemRegistry.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -17,52 +17,51 @@ import java.net.URL; import java.util.Map; import java.util.WeakHashMap; - import javax.tools.JavaFileManager; /** * @author tiwe - * */ public final class MemFileSystemRegistry { - public static final MemFileSystemRegistry DEFAULT = new MemFileSystemRegistry(); + public static final MemFileSystemRegistry DEFAULT = new MemFileSystemRegistry(); - private final Map jfm2prefix = new WeakHashMap(); + private final Map jfm2prefix = + new WeakHashMap(); - private Map> prefix2jfm = new WeakHashMap>(); + private Map> prefix2jfm = + new WeakHashMap>(); - private final String protocolName; + private final String protocolName; - private int sequence = 0; + private int sequence = 0; - private MemFileSystemRegistry() { - String pkgName = MemFileSystemRegistry.class.getPackage().getName(); - protocolName = pkgName.substring(pkgName.lastIndexOf('.') + 1); - String pkgs = System.getProperty("java.protocol.handler.pkgs"); - String parentPackage = pkgName.substring(0, pkgName.lastIndexOf('.')); - pkgs = pkgs == null ? parentPackage : pkgs + "|" + parentPackage; - System.setProperty("java.protocol.handler.pkgs", pkgs); - } + private MemFileSystemRegistry() { + String pkgName = MemFileSystemRegistry.class.getPackage().getName(); + protocolName = pkgName.substring(pkgName.lastIndexOf('.') + 1); + String pkgs = System.getProperty("java.protocol.handler.pkgs"); + String parentPackage = pkgName.substring(0, pkgName.lastIndexOf('.')); + pkgs = pkgs == null ? parentPackage : pkgs + "|" + parentPackage; + System.setProperty("java.protocol.handler.pkgs", pkgs); + } - public JavaFileManager getFileSystem(URL url) { - String prefix = url.getProtocol() + "://" + url.getHost() + "/"; - if (prefix2jfm.containsKey(prefix)) { - return prefix2jfm.get(prefix).get(); - } else { - return null; - } + public JavaFileManager getFileSystem(URL url) { + String prefix = url.getProtocol() + "://" + url.getHost() + "/"; + if (prefix2jfm.containsKey(prefix)) { + return prefix2jfm.get(prefix).get(); + } else { + return null; } + } - public String getUrlPrefix(JavaFileManager jfm) { - if (jfm2prefix.containsKey(jfm)) { - return jfm2prefix.get(jfm); - } else { - String result = protocolName + "://jfm" + (sequence++) + "/"; - jfm2prefix.put(jfm, result); - prefix2jfm.put(result, new WeakReference(jfm)); - return result; - } + public String getUrlPrefix(JavaFileManager jfm) { + if (jfm2prefix.containsKey(jfm)) { + return jfm2prefix.get(jfm); + } else { + String result = protocolName + "://jfm" + (sequence++) + "/"; + jfm2prefix.put(jfm, result); + prefix2jfm.put(result, new WeakReference(jfm)); + return result; } - + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemJavaFileObject.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemJavaFileObject.java index f762e4c99f..57531ee950 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemJavaFileObject.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemJavaFileObject.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -21,57 +21,54 @@ import java.io.OutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; - import javax.tools.SimpleJavaFileObject; /** * MemJavaFileObject defines an in memory compiled Java file - * + * * @author tiwe - * */ public class MemJavaFileObject extends SimpleJavaFileObject { - private ByteArrayOutputStream baos; + private ByteArrayOutputStream baos; - private final String name; + private final String name; - public MemJavaFileObject(String urlPrefix, String name, Kind kind) { - super(URI.create(urlPrefix + name + kind.extension), kind); - this.name = name; - } + public MemJavaFileObject(String urlPrefix, String name, Kind kind) { + super(URI.create(urlPrefix + name + kind.extension), kind); + this.name = name; + } - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - if (baos == null) { - throw new FileNotFoundException(name); - } - return new String(baos.toByteArray(), StandardCharsets.UTF_8); + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { + if (baos == null) { + throw new FileNotFoundException(name); } + return new String(baos.toByteArray(), StandardCharsets.UTF_8); + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - public byte[] getByteArray() { - return baos.toByteArray(); - } + public byte[] getByteArray() { + return baos.toByteArray(); + } - @Override - public InputStream openInputStream() throws IOException { - if (baos == null) { - throw new FileNotFoundException(name); - } - return new ByteArrayInputStream(baos.toByteArray()); + @Override + public InputStream openInputStream() throws IOException { + if (baos == null) { + throw new FileNotFoundException(name); } + return new ByteArrayInputStream(baos.toByteArray()); + } - @Override - public OutputStream openOutputStream() throws IOException { - if (baos == null) { - baos = new ByteArrayOutputStream(); - } - return baos; + @Override + public OutputStream openOutputStream() throws IOException { + if (baos == null) { + baos = new ByteArrayOutputStream(); } - + return baos; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemSourceFileObject.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemSourceFileObject.java index 931b3e341e..74abfa879a 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemSourceFileObject.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MemSourceFileObject.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -16,60 +16,56 @@ import java.io.IOException; import java.io.Writer; import java.net.URI; - import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; /** * MemSourceFileObject defines a in-memory Java source file object - * + * * @author tiwe - * */ public class MemSourceFileObject extends SimpleJavaFileObject { - private static URI toUri(String fqname) { - return URI.create("file:///" + fqname.replace(".", "/") + ".java"); - } + private static URI toUri(String fqname) { + return URI.create("file:///" + fqname.replace(".", "/") + ".java"); + } - private final StringBuilder contents; + private final StringBuilder contents; - public MemSourceFileObject(String fullName) { - super(toUri(fullName), JavaFileObject.Kind.SOURCE); - contents = new StringBuilder(1000); - } + public MemSourceFileObject(String fullName) { + super(toUri(fullName), JavaFileObject.Kind.SOURCE); + contents = new StringBuilder(1000); + } - public MemSourceFileObject(String fullName, String content) { - this(fullName); - contents.append(content); - } + public MemSourceFileObject(String fullName, String content) { + this(fullName); + contents.append(content); + } - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return contents; - } + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return contents; + } - @Override - public Writer openWriter() { - return new Writer() { - @Override - public Writer append(CharSequence csq) throws IOException { - contents.append(csq); - return this; - } + @Override + public Writer openWriter() { + return new Writer() { + @Override + public Writer append(CharSequence csq) throws IOException { + contents.append(csq); + return this; + } - @Override - public void close() { - } + @Override + public void close() {} - @Override - public void flush() { - } + @Override + public void flush() {} - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - contents.append(cbuf, off, len); - } - }; - } + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + contents.append(cbuf, off, len); + } + }; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MethodEvaluator.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MethodEvaluator.java index 6109b67668..56c728c44d 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MethodEvaluator.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MethodEvaluator.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -19,42 +19,41 @@ /** * @author tiwe - * * @param */ public final class MethodEvaluator implements Evaluator { - private final Method method; + private final Method method; - private final Class projectionType; - - private final Object[] args; + private final Class projectionType; - MethodEvaluator(Method method, Map constants, Class projectionType) { - this.method = method; - this.projectionType = projectionType; - this.args = new Object[method.getParameterTypes().length]; - int i = args.length - constants.size(); - for (Object value : constants.values()) { - args[i++] = value; - } - } + private final Object[] args; - @SuppressWarnings("unchecked") - @Override - public T evaluate(Object... args) { - try { - System.arraycopy(args, 0, this.args, 0, args.length); - return (T) method.invoke(null, this.args); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException(e); - } + MethodEvaluator(Method method, Map constants, Class projectionType) { + this.method = method; + this.projectionType = projectionType; + this.args = new Object[method.getParameterTypes().length]; + int i = args.length - constants.size(); + for (Object value : constants.values()) { + args[i++] = value; } + } - @Override - public Class getType() { - return projectionType; + @SuppressWarnings("unchecked") + @Override + public T evaluate(Object... args) { + try { + System.arraycopy(args, 0, this.args, 0, args.length); + return (T) method.invoke(null, this.args); + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(e); } -} \ No newline at end of file + } + + @Override + public Class getType() { + return projectionType; + } +} diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MultiSuppressWarnings.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MultiSuppressWarnings.java index 6014cd4803..37407278cc 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MultiSuppressWarnings.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MultiSuppressWarnings.java @@ -21,20 +21,20 @@ @SuppressWarnings("AnnotationAsSuperInterface") // Internal helper class class MultiSuppressWarnings implements SuppressWarnings { - private final String[] values; + private final String[] values; - MultiSuppressWarnings(String... values) { - this.values = Arrays.copyOf(values, values.length); - } + MultiSuppressWarnings(String... values) { + this.values = Arrays.copyOf(values, values.length); + } - @Override - @SuppressWarnings("ReturnOfCollectionOrArrayField") - public String[] value() { - return values; - } + @Override + @SuppressWarnings("ReturnOfCollectionOrArrayField") + public String[] value() { + return values; + } - @Override - public Class annotationType() { - return SuppressWarnings.class; - } + @Override + public Class annotationType() { + return SuppressWarnings.class; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ScalaWriter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ScalaWriter.java index 75509a599d..04c0f4cab3 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ScalaWriter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/ScalaWriter.java @@ -1,6 +1,6 @@ /* * Copyright 2011, Mysema Ltd - * + * * 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 @@ -18,6 +18,10 @@ import static com.querydsl.codegen.utils.Symbols.DOT; import static com.querydsl.codegen.utils.Symbols.QUOTE; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.Type; +import com.querydsl.codegen.utils.model.Types; +import com.querydsl.codegen.utils.support.ScalaSyntaxUtils; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; @@ -28,590 +32,598 @@ import java.util.Set; import java.util.function.Function; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.Type; -import com.querydsl.codegen.utils.model.Types; -import com.querydsl.codegen.utils.support.ScalaSyntaxUtils; - /** * @author tiwe - * */ public class ScalaWriter extends AbstractCodeWriter { - private static final Set PRIMITIVE_TYPES = new HashSet(Arrays.asList("boolean", - "byte", "char", "int", "long", "short", "double", "float")); - - private static final String DEF = "def "; - - private static final String OVERRIDE_DEF = "override " + DEF; - - private static final String EXTENDS = " extends "; - - private static final String WITH = " with "; - - private static final String IMPORT = "import "; - - private static final String IMPORT_STATIC = "import "; - - private static final String PACKAGE = "package "; - - private static final String PRIVATE = "private "; - - private static final String PRIVATE_VAL = "private val "; - - private static final String PROTECTED = "protected "; + private static final Set PRIMITIVE_TYPES = + new HashSet( + Arrays.asList("boolean", "byte", "char", "int", "long", "short", "double", "float")); - private static final String PROTECTED_VAL = "protected val "; + private static final String DEF = "def "; - private static final String PUBLIC = "public "; + private static final String OVERRIDE_DEF = "override " + DEF; - private static final String PUBLIC_CLASS = "class "; + private static final String EXTENDS = " extends "; - private static final String PUBLIC_OBJECT = "object "; + private static final String WITH = " with "; - private static final String CASE_CLASS = "case class "; + private static final String IMPORT = "import "; - private static final String VAR = "var "; + private static final String IMPORT_STATIC = "import "; - private static final String VAL = "val "; + private static final String PACKAGE = "package "; - private static final String THIS = "this"; + private static final String PRIVATE = "private "; - private static final String TRAIT = "trait "; - - private final Set classes = new HashSet(); - - private final Set packages = new HashSet(); - - private Type type; - - private final boolean compact; - - public ScalaWriter(Appendable appendable) { - this(appendable, false); - } - - public ScalaWriter(Appendable appendable, boolean compact) { - super(appendable, 2); - this.classes.add("java.lang.String"); - this.classes.add("java.lang.Object"); - this.classes.add("java.lang.Integer"); - this.classes.add("java.lang.Comparable"); - this.compact = compact; - } - - @Override - public ScalaWriter annotation(Annotation annotation) throws IOException { - beginLine().append("@").appendType(annotation.annotationType()); - Method[] methods = annotation.annotationType().getDeclaredMethods(); - if (methods.length == 1 && methods[0].getName().equals("value")) { - try { - Object value = methods[0].invoke(annotation); - append("("); - annotationConstant(value); - append(")"); - } catch (IllegalArgumentException e) { - throw new CodegenException(e); - } catch (IllegalAccessException e) { - throw new CodegenException(e); - } catch (InvocationTargetException e) { - throw new CodegenException(e); - } - } else { - boolean first = true; - for (Method method : methods) { - try { - Object value = method.invoke(annotation); - if (value == null - || value.equals(method.getDefaultValue()) - || (value.getClass().isArray() && Arrays.equals((Object[]) value, - (Object[]) method.getDefaultValue()))) { - continue; - } else if (!first) { - append(COMMA); - } else { - append("("); - } - append(escape(method.getName())).append("="); - annotationConstant(value); - } catch (IllegalArgumentException e) { - throw new CodegenException(e); - } catch (IllegalAccessException e) { - throw new CodegenException(e); - } catch (InvocationTargetException e) { - throw new CodegenException(e); - } - first = false; - } - if (!first) { - append(")"); - } - } - return nl(); - } - - @Override - public ScalaWriter annotation(Class annotation) throws IOException { - return beginLine().append("@").appendType(annotation).nl(); - } - - @SuppressWarnings("unchecked") - private void annotationConstant(Object value) throws IOException { - if (value.getClass().isArray()) { - append("Array("); - boolean first = true; - for (Object o : (Object[]) value) { - if (!first) { - append(", "); - } - annotationConstant(o); - first = false; - } - append(")"); - } else if (value instanceof Class) { - append("classOf["); - appendType((Class) value); - append("]"); - } else if (value instanceof Number || value instanceof Boolean) { - append(value.toString()); - } else if (value instanceof Enum) { - Enum enumValue = (Enum) value; - if (classes.contains(enumValue.getClass().getName()) - || packages.contains(enumValue.getClass().getPackage().getName())) { - append(enumValue.name()); - } else { - append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name()); - } - } else if (value instanceof String) { - append(QUOTE).append(StringUtils.escapeJava(value.toString())).append(QUOTE); - } else { - throw new IllegalArgumentException("Unsupported annotation value : " + value); - } - } + private static final String PRIVATE_VAL = "private val "; - private ScalaWriter appendType(Class type) throws IOException { - if (type.isPrimitive()) { - append(StringUtils.capitalize(type.getName())); - } else if (type.getPackage() == null || classes.contains(type.getName()) - || packages.contains(type.getPackage().getName())) { - append(type.getSimpleName()); - } else { - append(type.getName()); - } - return this; - } - - public ScalaWriter beginObject(String header) throws IOException { - line(PUBLIC_OBJECT, header, " {"); - goIn(); - return this; - } - - public ScalaWriter beginClass(String header) throws IOException { - line(PUBLIC_CLASS, header, " {"); - goIn(); - return this; - } - - @Override - public ScalaWriter beginClass(Type type) throws IOException { - return beginClass(type, null); - } - - @Override - public ScalaWriter beginClass(Type type, Type superClass, Type... interfaces) - throws IOException { - packages.add(type.getPackageName()); - beginLine(PUBLIC_CLASS, getGenericName(false, type)); - if (superClass != null) { - append(EXTENDS).append(getGenericName(false, superClass)); - } - if (interfaces.length > 0) { - if (superClass == null) { - append(EXTENDS); - append(getGenericName(false, interfaces[0])); - append(WITH); - for (int i = 1; i < interfaces.length; i++) { - if (i > 1) { - append(COMMA); - } - append(getGenericName(false, interfaces[i])); - } - } else { - append(WITH); - for (int i = 0; i < interfaces.length; i++) { - if (i > 0) { - append(COMMA); - } - append(getGenericName(false, interfaces[i])); - } - } - } - append(" {").nl().nl(); - goIn(); - this.type = type; - return this; - } - - @Override - public ScalaWriter beginConstructor(Collection parameters, - Function transformer) throws IOException { - beginLine(DEF, THIS).params(parameters, transformer).append(" {").nl(); - return goIn(); - } - - @Override - public ScalaWriter beginConstructor(Parameter... params) throws IOException { - beginLine(DEF, THIS).params(params).append(" {").nl(); - return goIn(); - } - - @Override - public ScalaWriter beginInterface(Type type, Type... interfaces) throws IOException { - packages.add(type.getPackageName()); - beginLine(TRAIT, getGenericName(false, type)); - if (interfaces.length > 0) { - append(EXTENDS); - append(getGenericName(false, interfaces[0])); - if (interfaces.length > 1) { - append(WITH); - for (int i = 1; i < interfaces.length; i++) { - if (i > 1) { - append(COMMA); - } - append(getGenericName(false, interfaces[i])); - } - } - - } - append(" {").nl().nl(); - goIn(); - this.type = type; - return this; - } - - private ScalaWriter beginMethod(String modifiers, Type returnType, String methodName, - Parameter... args) throws IOException { - if (returnType.equals(Types.VOID)) { - beginLine(modifiers, escape(methodName)).params(args).append(" {").nl(); - } else { - beginLine(modifiers, escape(methodName)).params(args) - .append(": ").append(getGenericName(true, returnType)).append(" = {").nl(); - } - - return goIn(); - } - - @Override - public ScalaWriter beginPublicMethod(Type returnType, String methodName, - Collection parameters, Function transformer) throws IOException { - return beginMethod(DEF, returnType, methodName, transform(parameters, transformer)); - } - - @Override - public ScalaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) - throws IOException { - return beginMethod(DEF, returnType, methodName, args); - } - - public ScalaWriter beginOverridePublicMethod(Type returnType, String methodName, - Collection parameters, Function transformer) - throws IOException { - return beginMethod(OVERRIDE_DEF, returnType, methodName, transform(parameters, transformer)); - } - - public ScalaWriter beginOverridePublicMethod(Type returnType, String methodName, Parameter... args) - throws IOException { - return beginMethod(OVERRIDE_DEF, returnType, methodName, args); - } - - @Override - public ScalaWriter beginStaticMethod(Type returnType, String methodName, - Collection parameters, Function transformer) throws IOException { - return beginMethod(DEF, returnType, methodName, transform(parameters, transformer)); - } + private static final String PROTECTED = "protected "; - @Override - public ScalaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) - throws IOException { - return beginMethod(DEF, returnType, methodName, args); - } + private static final String PROTECTED_VAL = "protected val "; - public ScalaWriter caseClass(String header, Parameter... parameters) throws IOException { - beginLine(CASE_CLASS, header).params(parameters).nl(); - return this; - } + private static final String PUBLIC = "public "; - @Override - public ScalaWriter end() throws IOException { - goOut(); - return line("}").nl(); - } + private static final String PUBLIC_CLASS = "class "; - public ScalaWriter field(Type type, String name) throws IOException { - line(VAR, escape(name), ": ", getGenericName(true, type)); - return compact ? this : nl(); - } + private static final String PUBLIC_OBJECT = "object "; - private ScalaWriter field(String modifier, Type type, String name) throws IOException { - line(modifier, escape(name), ": ", getGenericName(true, type)); - return compact ? this : nl(); - } + private static final String CASE_CLASS = "case class "; - private ScalaWriter field(String modifier, Type type, String name, String value) - throws IOException { - line(modifier, escape(name), ": ", getGenericName(true, type), ASSIGN, value); - return compact ? this : nl(); - } + private static final String VAR = "var "; - @Override - public String getClassConstant(String className) { - return "classOf[" + className + "]"; - } + private static final String VAL = "val "; - @Override - public String getGenericName(boolean asArgType, Type type) { - if (type.getParameters().isEmpty()) { - return getRawName(type); - } else { - StringBuilder builder = new StringBuilder(); - builder.append(getRawName(type)); - builder.append("["); - boolean first = true; - String fullName = type.getFullName(); - for (Type parameter : type.getParameters()) { - if (!first) { - builder.append(", "); - } - if (parameter == null || parameter.getFullName().equals(fullName)) { - builder.append("_"); - } else { - builder.append(getGenericName(false, parameter)); - } - first = false; - } - builder.append("]"); - return builder.toString(); - } - } + private static final String THIS = "this"; - @Override - public String getRawName(Type type) { - String fullName = type.getFullName(); - if (PRIMITIVE_TYPES.contains(fullName)) { - fullName = StringUtils.capitalize(fullName); - } - String packageName = type.getPackageName(); - if (packageName != null && packageName.length() > 0) { - fullName = packageName + "." + fullName.substring(packageName.length() + 1).replace('.', '$'); - } else { - fullName = fullName.replace('.', '$'); - } - String rv = fullName; - if (type.isPrimitive() && packageName.isEmpty()) { - rv = Character.toUpperCase(rv.charAt(0)) + rv.substring(1); - } - if (packages.contains(packageName) || classes.contains(fullName)) { - if (packageName.length() > 0) { - rv = fullName.substring(packageName.length() + 1); - } - } - if (rv.endsWith("[]")) { - rv = rv.substring(0, rv.length() - 2); - if (PRIMITIVE_TYPES.contains(rv)) { - rv = StringUtils.capitalize(rv); - } else if (classes.contains(rv)) { - rv = rv.substring(packageName.length() + 1); - } - return "Array[" + rv + "]"; - } else { - return rv; - } - } + private static final String TRAIT = "trait "; - @Override - public ScalaWriter imports(Class... imports) throws IOException { - for (Class cl : imports) { - classes.add(cl.getName()); - line(IMPORT, cl.getName()); - } - nl(); - return this; - } + private final Set classes = new HashSet(); - @Override - public ScalaWriter imports(Package... imports) throws IOException { - for (Package p : imports) { - packages.add(p.getName()); - line(IMPORT, p.getName(), "._"); - } - nl(); - return this; - } + private final Set packages = new HashSet(); - @Override - public ScalaWriter importClasses(String... imports) throws IOException { - for (String cl : imports) { - classes.add(cl); - line(IMPORT, cl); - } - nl(); - return this; - } + private Type type; - @Override - public ScalaWriter importPackages(String... imports) throws IOException { - for (String p : imports) { - packages.add(p); - line(IMPORT, p, "._"); - } - nl(); - return this; - } + private final boolean compact; - @Override - public ScalaWriter javadoc(String... lines) throws IOException { - line("/**"); - for (String line : lines) { - line(" * ", line); - } - return line(" */"); - } + public ScalaWriter(Appendable appendable) { + this(appendable, false); + } - @Override - public ScalaWriter packageDecl(String packageName) throws IOException { - packages.add(packageName); - return line(PACKAGE, packageName).nl(); - } + public ScalaWriter(Appendable appendable, boolean compact) { + super(appendable, 2); + this.classes.add("java.lang.String"); + this.classes.add("java.lang.Object"); + this.classes.add("java.lang.Integer"); + this.classes.add("java.lang.Comparable"); + this.compact = compact; + } - private ScalaWriter params(Collection parameters, Function transformer) - throws IOException { + @Override + public ScalaWriter annotation(Annotation annotation) throws IOException { + beginLine().append("@").appendType(annotation.annotationType()); + Method[] methods = annotation.annotationType().getDeclaredMethods(); + if (methods.length == 1 && methods[0].getName().equals("value")) { + try { + Object value = methods[0].invoke(annotation); append("("); - boolean first = true; - for (T param : parameters) { - if (!first) { - append(COMMA); - } - param(transformer.apply(param)); - first = false; - } + annotationConstant(value); append(")"); - return this; - } - - private ScalaWriter params(Parameter... params) throws IOException { - append("("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - append(COMMA); - } - param(params[i]); + } catch (IllegalArgumentException e) { + throw new CodegenException(e); + } catch (IllegalAccessException e) { + throw new CodegenException(e); + } catch (InvocationTargetException e) { + throw new CodegenException(e); + } + } else { + boolean first = true; + for (Method method : methods) { + try { + Object value = method.invoke(annotation); + if (value == null + || value.equals(method.getDefaultValue()) + || (value.getClass().isArray() + && Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue()))) { + continue; + } else if (!first) { + append(COMMA); + } else { + append("("); + } + append(escape(method.getName())).append("="); + annotationConstant(value); + } catch (IllegalArgumentException e) { + throw new CodegenException(e); + } catch (IllegalAccessException e) { + throw new CodegenException(e); + } catch (InvocationTargetException e) { + throw new CodegenException(e); } + first = false; + } + if (!first) { append(")"); - return this; - } - - private ScalaWriter param(Parameter parameter) throws IOException { - append(escape(parameter.getName())); - append(": "); - append(getGenericName(true, parameter.getType())); - return this; - } - - @Override - public ScalaWriter privateField(Type type, String name) throws IOException { - return field(PRIVATE, type, name); - } - - @Override - public ScalaWriter privateFinal(Type type, String name) throws IOException { - return field(PRIVATE_VAL, type, name); - } - - @Override - public ScalaWriter privateFinal(Type type, String name, String value) throws IOException { - return field(PRIVATE_VAL, type, name, value); - } - - @Override - public ScalaWriter privateStaticFinal(Type type, String name, String value) throws IOException { - return field(PRIVATE_VAL, type, name, value); - } - - @Override - public ScalaWriter protectedField(Type type, String name) throws IOException { - return field(PROTECTED, type, name); - } - - @Override - public ScalaWriter protectedFinal(Type type, String name) throws IOException { - return field(PROTECTED_VAL, type, name); - } - - @Override - public ScalaWriter protectedFinal(Type type, String name, String value) throws IOException { - return field(PROTECTED_VAL, type, name, value); - } - - @Override - public ScalaWriter publicField(Type type, String name) throws IOException { - return field(VAR, type, name); - } - - @Override - public ScalaWriter publicField(Type type, String name, String value) throws IOException { - return field(VAR, type, name, value); - } - - @Override - public ScalaWriter publicFinal(Type type, String name) throws IOException { - return field(VAL, type, name); - } - - @Override - public ScalaWriter publicFinal(Type type, String name, String value) throws IOException { - return field(VAL, type, name, value); - } - - @Override - public ScalaWriter publicStaticFinal(Type type, String name, String value) throws IOException { - return field(VAL, type, name, value); - } - - @Override - public ScalaWriter staticimports(Class... imports) throws IOException { - for (Class cl : imports) { - line(IMPORT_STATIC, cl.getName(), "._;"); + } + } + return nl(); + } + + @Override + public ScalaWriter annotation(Class annotation) throws IOException { + return beginLine().append("@").appendType(annotation).nl(); + } + + @SuppressWarnings("unchecked") + private void annotationConstant(Object value) throws IOException { + if (value.getClass().isArray()) { + append("Array("); + boolean first = true; + for (Object o : (Object[]) value) { + if (!first) { + append(", "); } - return this; - } - - @Override - public ScalaWriter suppressWarnings(String type) throws IOException { - return line("@SuppressWarnings(\"", type, "\")"); - } - - @Override - public CodeWriter suppressWarnings(String... types) throws IOException { - return annotation(new MultiSuppressWarnings(types)); - } - - private Parameter[] transform(Collection parameters, - Function transformer) { - Parameter[] rv = new Parameter[parameters.size()]; - int i = 0; - for (T value : parameters) { - rv[i++] = transformer.apply(value); + annotationConstant(o); + first = false; + } + append(")"); + } else if (value instanceof Class) { + append("classOf["); + appendType((Class) value); + append("]"); + } else if (value instanceof Number || value instanceof Boolean) { + append(value.toString()); + } else if (value instanceof Enum) { + Enum enumValue = (Enum) value; + if (classes.contains(enumValue.getClass().getName()) + || packages.contains(enumValue.getClass().getPackage().getName())) { + append(enumValue.name()); + } else { + append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name()); + } + } else if (value instanceof String) { + append(QUOTE).append(StringUtils.escapeJava(value.toString())).append(QUOTE); + } else { + throw new IllegalArgumentException("Unsupported annotation value : " + value); + } + } + + private ScalaWriter appendType(Class type) throws IOException { + if (type.isPrimitive()) { + append(StringUtils.capitalize(type.getName())); + } else if (type.getPackage() == null + || classes.contains(type.getName()) + || packages.contains(type.getPackage().getName())) { + append(type.getSimpleName()); + } else { + append(type.getName()); + } + return this; + } + + public ScalaWriter beginObject(String header) throws IOException { + line(PUBLIC_OBJECT, header, " {"); + goIn(); + return this; + } + + public ScalaWriter beginClass(String header) throws IOException { + line(PUBLIC_CLASS, header, " {"); + goIn(); + return this; + } + + @Override + public ScalaWriter beginClass(Type type) throws IOException { + return beginClass(type, null); + } + + @Override + public ScalaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException { + packages.add(type.getPackageName()); + beginLine(PUBLIC_CLASS, getGenericName(false, type)); + if (superClass != null) { + append(EXTENDS).append(getGenericName(false, superClass)); + } + if (interfaces.length > 0) { + if (superClass == null) { + append(EXTENDS); + append(getGenericName(false, interfaces[0])); + append(WITH); + for (int i = 1; i < interfaces.length; i++) { + if (i > 1) { + append(COMMA); + } + append(getGenericName(false, interfaces[i])); } - return rv; - } - - private String escape(String token) { - if (ScalaSyntaxUtils.isReserved(token)) { - return "`" + token + "`"; + } else { + append(WITH); + for (int i = 0; i < interfaces.length; i++) { + if (i > 0) { + append(COMMA); + } + append(getGenericName(false, interfaces[i])); + } + } + } + append(" {").nl().nl(); + goIn(); + this.type = type; + return this; + } + + @Override + public ScalaWriter beginConstructor( + Collection parameters, Function transformer) throws IOException { + beginLine(DEF, THIS).params(parameters, transformer).append(" {").nl(); + return goIn(); + } + + @Override + public ScalaWriter beginConstructor(Parameter... params) throws IOException { + beginLine(DEF, THIS).params(params).append(" {").nl(); + return goIn(); + } + + @Override + public ScalaWriter beginInterface(Type type, Type... interfaces) throws IOException { + packages.add(type.getPackageName()); + beginLine(TRAIT, getGenericName(false, type)); + if (interfaces.length > 0) { + append(EXTENDS); + append(getGenericName(false, interfaces[0])); + if (interfaces.length > 1) { + append(WITH); + for (int i = 1; i < interfaces.length; i++) { + if (i > 1) { + append(COMMA); + } + append(getGenericName(false, interfaces[i])); + } + } + } + append(" {").nl().nl(); + goIn(); + this.type = type; + return this; + } + + private ScalaWriter beginMethod( + String modifiers, Type returnType, String methodName, Parameter... args) throws IOException { + if (returnType.equals(Types.VOID)) { + beginLine(modifiers, escape(methodName)).params(args).append(" {").nl(); + } else { + beginLine(modifiers, escape(methodName)) + .params(args) + .append(": ") + .append(getGenericName(true, returnType)) + .append(" = {") + .nl(); + } + + return goIn(); + } + + @Override + public ScalaWriter beginPublicMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException { + return beginMethod(DEF, returnType, methodName, transform(parameters, transformer)); + } + + @Override + public ScalaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) + throws IOException { + return beginMethod(DEF, returnType, methodName, args); + } + + public ScalaWriter beginOverridePublicMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException { + return beginMethod(OVERRIDE_DEF, returnType, methodName, transform(parameters, transformer)); + } + + public ScalaWriter beginOverridePublicMethod( + Type returnType, String methodName, Parameter... args) throws IOException { + return beginMethod(OVERRIDE_DEF, returnType, methodName, args); + } + + @Override + public ScalaWriter beginStaticMethod( + Type returnType, + String methodName, + Collection parameters, + Function transformer) + throws IOException { + return beginMethod(DEF, returnType, methodName, transform(parameters, transformer)); + } + + @Override + public ScalaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) + throws IOException { + return beginMethod(DEF, returnType, methodName, args); + } + + public ScalaWriter caseClass(String header, Parameter... parameters) throws IOException { + beginLine(CASE_CLASS, header).params(parameters).nl(); + return this; + } + + @Override + public ScalaWriter end() throws IOException { + goOut(); + return line("}").nl(); + } + + public ScalaWriter field(Type type, String name) throws IOException { + line(VAR, escape(name), ": ", getGenericName(true, type)); + return compact ? this : nl(); + } + + private ScalaWriter field(String modifier, Type type, String name) throws IOException { + line(modifier, escape(name), ": ", getGenericName(true, type)); + return compact ? this : nl(); + } + + private ScalaWriter field(String modifier, Type type, String name, String value) + throws IOException { + line(modifier, escape(name), ": ", getGenericName(true, type), ASSIGN, value); + return compact ? this : nl(); + } + + @Override + public String getClassConstant(String className) { + return "classOf[" + className + "]"; + } + + @Override + public String getGenericName(boolean asArgType, Type type) { + if (type.getParameters().isEmpty()) { + return getRawName(type); + } else { + StringBuilder builder = new StringBuilder(); + builder.append(getRawName(type)); + builder.append("["); + boolean first = true; + String fullName = type.getFullName(); + for (Type parameter : type.getParameters()) { + if (!first) { + builder.append(", "); + } + if (parameter == null || parameter.getFullName().equals(fullName)) { + builder.append("_"); } else { - return token; + builder.append(getGenericName(false, parameter)); } - } + first = false; + } + builder.append("]"); + return builder.toString(); + } + } + + @Override + public String getRawName(Type type) { + String fullName = type.getFullName(); + if (PRIMITIVE_TYPES.contains(fullName)) { + fullName = StringUtils.capitalize(fullName); + } + String packageName = type.getPackageName(); + if (packageName != null && packageName.length() > 0) { + fullName = packageName + "." + fullName.substring(packageName.length() + 1).replace('.', '$'); + } else { + fullName = fullName.replace('.', '$'); + } + String rv = fullName; + if (type.isPrimitive() && packageName.isEmpty()) { + rv = Character.toUpperCase(rv.charAt(0)) + rv.substring(1); + } + if (packages.contains(packageName) || classes.contains(fullName)) { + if (packageName.length() > 0) { + rv = fullName.substring(packageName.length() + 1); + } + } + if (rv.endsWith("[]")) { + rv = rv.substring(0, rv.length() - 2); + if (PRIMITIVE_TYPES.contains(rv)) { + rv = StringUtils.capitalize(rv); + } else if (classes.contains(rv)) { + rv = rv.substring(packageName.length() + 1); + } + return "Array[" + rv + "]"; + } else { + return rv; + } + } + + @Override + public ScalaWriter imports(Class... imports) throws IOException { + for (Class cl : imports) { + classes.add(cl.getName()); + line(IMPORT, cl.getName()); + } + nl(); + return this; + } + + @Override + public ScalaWriter imports(Package... imports) throws IOException { + for (Package p : imports) { + packages.add(p.getName()); + line(IMPORT, p.getName(), "._"); + } + nl(); + return this; + } + + @Override + public ScalaWriter importClasses(String... imports) throws IOException { + for (String cl : imports) { + classes.add(cl); + line(IMPORT, cl); + } + nl(); + return this; + } + + @Override + public ScalaWriter importPackages(String... imports) throws IOException { + for (String p : imports) { + packages.add(p); + line(IMPORT, p, "._"); + } + nl(); + return this; + } + + @Override + public ScalaWriter javadoc(String... lines) throws IOException { + line("/**"); + for (String line : lines) { + line(" * ", line); + } + return line(" */"); + } + + @Override + public ScalaWriter packageDecl(String packageName) throws IOException { + packages.add(packageName); + return line(PACKAGE, packageName).nl(); + } + + private ScalaWriter params(Collection parameters, Function transformer) + throws IOException { + append("("); + boolean first = true; + for (T param : parameters) { + if (!first) { + append(COMMA); + } + param(transformer.apply(param)); + first = false; + } + append(")"); + return this; + } + + private ScalaWriter params(Parameter... params) throws IOException { + append("("); + for (int i = 0; i < params.length; i++) { + if (i > 0) { + append(COMMA); + } + param(params[i]); + } + append(")"); + return this; + } + + private ScalaWriter param(Parameter parameter) throws IOException { + append(escape(parameter.getName())); + append(": "); + append(getGenericName(true, parameter.getType())); + return this; + } + + @Override + public ScalaWriter privateField(Type type, String name) throws IOException { + return field(PRIVATE, type, name); + } + + @Override + public ScalaWriter privateFinal(Type type, String name) throws IOException { + return field(PRIVATE_VAL, type, name); + } + + @Override + public ScalaWriter privateFinal(Type type, String name, String value) throws IOException { + return field(PRIVATE_VAL, type, name, value); + } + + @Override + public ScalaWriter privateStaticFinal(Type type, String name, String value) throws IOException { + return field(PRIVATE_VAL, type, name, value); + } + + @Override + public ScalaWriter protectedField(Type type, String name) throws IOException { + return field(PROTECTED, type, name); + } + + @Override + public ScalaWriter protectedFinal(Type type, String name) throws IOException { + return field(PROTECTED_VAL, type, name); + } + + @Override + public ScalaWriter protectedFinal(Type type, String name, String value) throws IOException { + return field(PROTECTED_VAL, type, name, value); + } + + @Override + public ScalaWriter publicField(Type type, String name) throws IOException { + return field(VAR, type, name); + } + + @Override + public ScalaWriter publicField(Type type, String name, String value) throws IOException { + return field(VAR, type, name, value); + } + + @Override + public ScalaWriter publicFinal(Type type, String name) throws IOException { + return field(VAL, type, name); + } + + @Override + public ScalaWriter publicFinal(Type type, String name, String value) throws IOException { + return field(VAL, type, name, value); + } + + @Override + public ScalaWriter publicStaticFinal(Type type, String name, String value) throws IOException { + return field(VAL, type, name, value); + } + + @Override + public ScalaWriter staticimports(Class... imports) throws IOException { + for (Class cl : imports) { + line(IMPORT_STATIC, cl.getName(), "._;"); + } + return this; + } + + @Override + public ScalaWriter suppressWarnings(String type) throws IOException { + return line("@SuppressWarnings(\"", type, "\")"); + } + + @Override + public CodeWriter suppressWarnings(String... types) throws IOException { + return annotation(new MultiSuppressWarnings(types)); + } + + private Parameter[] transform(Collection parameters, Function transformer) { + Parameter[] rv = new Parameter[parameters.size()]; + int i = 0; + for (T value : parameters) { + rv[i++] = transformer.apply(value); + } + return rv; + } + + private String escape(String token) { + if (ScalaSyntaxUtils.isReserved(token)) { + return "`" + token + "`"; + } else { + return token; + } + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/SimpleCompiler.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/SimpleCompiler.java index 3f4725a364..3be5c558a0 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/SimpleCompiler.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/SimpleCompiler.java @@ -14,9 +14,6 @@ package com.querydsl.codegen.utils; import io.github.classgraph.ClassGraph; - -import javax.lang.model.SourceVersion; -import javax.tools.*; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; @@ -27,94 +24,98 @@ import java.util.List; import java.util.Locale; import java.util.Set; +import javax.lang.model.SourceVersion; +import javax.tools.*; /** - * SimpleCompiler provides a convenience wrapper of the JavaCompiler interface - * with automatic classpath generation + * SimpleCompiler provides a convenience wrapper of the JavaCompiler interface with automatic + * classpath generation * * @author tiwe - * */ public class SimpleCompiler implements JavaCompiler { - protected static boolean isSureFireBooter(URLClassLoader cl) { - for (URL url : cl.getURLs()) { - if (url.getPath().contains("surefirebooter")) { - return true; - } - } - - return false; + protected static boolean isSureFireBooter(URLClassLoader cl) { + for (URL url : cl.getURLs()) { + if (url.getPath().contains("surefirebooter")) { + return true; + } } - public static String getClassPath(ClassLoader cl) { - return new ClassGraph().overrideClassLoaders(cl).getClasspath(); - } + return false; + } - private final ClassLoader classLoader; + public static String getClassPath(ClassLoader cl) { + return new ClassGraph().overrideClassLoaders(cl).getClasspath(); + } - private String classPath; + private final ClassLoader classLoader; - private final JavaCompiler compiler; + private String classPath; - public SimpleCompiler() { - this(ToolProvider.getSystemJavaCompiler(), Thread.currentThread().getContextClassLoader()); - } + private final JavaCompiler compiler; - public SimpleCompiler(JavaCompiler compiler, ClassLoader classLoader) { - this.compiler = compiler; - this.classLoader = classLoader; - } - - private String getClasspath() { - if (classPath == null) { - classPath = getClassPath(classLoader); - } - return classPath; - } - - @Override - public Set getSourceVersions() { - return compiler.getSourceVersions(); - } + public SimpleCompiler() { + this(ToolProvider.getSystemJavaCompiler(), Thread.currentThread().getContextClassLoader()); + } - @Override - public StandardJavaFileManager getStandardFileManager( - DiagnosticListener diagnosticListener, Locale locale, - Charset charset) { - return compiler.getStandardFileManager(diagnosticListener, locale, charset); - } + public SimpleCompiler(JavaCompiler compiler, ClassLoader classLoader) { + this.compiler = compiler; + this.classLoader = classLoader; + } - @Override - public CompilationTask getTask(Writer out, JavaFileManager fileManager, - DiagnosticListener diagnosticListener, - Iterable options, Iterable classes, - Iterable compilationUnits) { - return compiler.getTask(out, fileManager, diagnosticListener, options, classes, - compilationUnits); + private String getClasspath() { + if (classPath == null) { + classPath = getClassPath(classLoader); } - - @Override - public int isSupportedOption(String option) { - return compiler.isSupportedOption(option); + return classPath; + } + + @Override + public Set getSourceVersions() { + return compiler.getSourceVersions(); + } + + @Override + public StandardJavaFileManager getStandardFileManager( + DiagnosticListener diagnosticListener, + Locale locale, + Charset charset) { + return compiler.getStandardFileManager(diagnosticListener, locale, charset); + } + + @Override + public CompilationTask getTask( + Writer out, + JavaFileManager fileManager, + DiagnosticListener diagnosticListener, + Iterable options, + Iterable classes, + Iterable compilationUnits) { + return compiler.getTask( + out, fileManager, diagnosticListener, options, classes, compilationUnits); + } + + @Override + public int isSupportedOption(String option) { + return compiler.isSupportedOption(option); + } + + @Override + public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { + for (String a : arguments) { + if (a.equals("-classpath")) { + return compiler.run(in, out, err, arguments); + } } - @Override - public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { - for (String a : arguments) { - if (a.equals("-classpath")) { - return compiler.run(in, out, err, arguments); - } - } - - // no classpath given - List args = new ArrayList(arguments.length + 2); - args.add("-classpath"); - args.add(getClasspath()); - for (String arg : arguments) { - args.add(arg); - } - return compiler.run(in, out, err, args.toArray(new String[args.size()])); + // no classpath given + List args = new ArrayList(arguments.length + 2); + args.add("-classpath"); + args.add(getClasspath()); + for (String arg : arguments) { + args.add(arg); } - + return compiler.run(in, out, err, args.toArray(new String[args.size()])); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/StringUtils.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/StringUtils.java index 8a1c476369..80e8671abb 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/StringUtils.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/StringUtils.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -16,30 +16,29 @@ import java.util.Arrays; public final class StringUtils { - - public static String capitalize(String str) { - return str.substring(0, 1).toUpperCase() + str.substring(1); - } - - public static String uncapitalize(String str) { - return str.substring(0, 1).toLowerCase() + str.substring(1); - } - public static String escapeJava(String str) { - str = str.replace("\\", "\\\\"); - str = str.replace("\"", "\\\""); - str = str.replace("\r", "\\\r"); - str = str.replace("\t", "\\\t"); - str = str.replace("\n", "\\\n"); - return str; - } + public static String capitalize(String str) { + return str.substring(0, 1).toUpperCase() + str.substring(1); + } - public static String repeat(char value, int times) { - char[] chars = new char[times]; - Arrays.fill(chars, value); - return new String(chars); - } - - private StringUtils() { } + public static String uncapitalize(String str) { + return str.substring(0, 1).toLowerCase() + str.substring(1); + } + public static String escapeJava(String str) { + str = str.replace("\\", "\\\\"); + str = str.replace("\"", "\\\""); + str = str.replace("\r", "\\\r"); + str = str.replace("\t", "\\\t"); + str = str.replace("\n", "\\\n"); + return str; + } + + public static String repeat(char value, int times) { + char[] chars = new char[times]; + Arrays.fill(chars, value); + return new String(chars); + } + + private StringUtils() {} } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Symbols.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Symbols.java index 61b08bc363..39fd4a5465 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Symbols.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/Symbols.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -15,44 +15,42 @@ /** * Defines general String constants - * + * * @author tiwe - * */ public final class Symbols { - public static final String ASSIGN = " = "; + public static final String ASSIGN = " = "; - public static final String COMMA = ", "; + public static final String COMMA = ", "; - public static final String DOT = "."; + public static final String DOT = "."; - public static final String DOT_CLASS = ".class"; + public static final String DOT_CLASS = ".class"; - public static final String EMPTY = ""; + public static final String EMPTY = ""; - public static final String NEW = "new "; + public static final String NEW = "new "; - public static final String NEWLINE = "\n"; + public static final String NEWLINE = "\n"; - public static final String QUOTE = "\""; + public static final String QUOTE = "\""; - public static final String RETURN = "return "; + public static final String RETURN = "return "; - public static final String SEMICOLON = ";"; + public static final String SEMICOLON = ";"; - public static final String SERIAL = "serial"; + public static final String SERIAL = "serial"; - public static final String SPACE = " "; + public static final String SPACE = " "; - public static final String STAR = "*"; + public static final String STAR = "*"; - public static final String SUPER = "super"; + public static final String SUPER = "super"; - public static final String THIS = "this"; + public static final String THIS = "this"; - public static final String UNCHECKED = "unchecked"; + public static final String UNCHECKED = "unchecked"; - private Symbols() { - } + private Symbols() {} } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/ClassType.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/ClassType.java index d582ceef16..07a578174c 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/ClassType.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/ClassType.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -13,185 +13,181 @@ */ package com.querydsl.codegen.utils.model; +import com.querydsl.codegen.utils.support.ClassUtils; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; -import com.querydsl.codegen.utils.support.ClassUtils; - /** * @author tiwe - * */ public class ClassType implements Type { - private final TypeCategory category; - - private final Class javaClass; - - private final String className; - - private final List parameters; - - private Type arrayType, componentType, enclosingType; - - public ClassType(Class javaClass, Type... parameters) { - this(TypeCategory.SIMPLE, javaClass, Arrays.asList(parameters)); - } - - public ClassType(TypeCategory category, Class clazz, Type... parameters) { - this(category, clazz, Arrays.asList(parameters)); - } - - public ClassType(TypeCategory category, Class clazz, List parameters) { - this.category = category; - this.javaClass = clazz; - this.parameters = parameters; - this.className = ClassUtils.getFullName(javaClass); - } - - - @Override - public Type as(TypeCategory c) { - if (category == c) { - return this; - } else { - return new ClassType(c, javaClass); - } - } - - @Override - public Type asArrayType() { - if (arrayType == null) { - String fullName = ClassUtils.getFullName(javaClass) + "[]"; - String simpleName = javaClass.getSimpleName() + "[]"; - arrayType = new SimpleType(TypeCategory.ARRAY, fullName, getPackageName(), simpleName, - false, false); - } - return arrayType; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Type) { - Type t = (Type) o; - return t.getFullName().equals(className) && t.getParameters().equals(parameters); - } else { - return false; - } - } - - public TypeCategory getCategory() { - return category; - } - - @Override - public Type getComponentType() { - Class clazz = javaClass.getComponentType(); - if (clazz != null && componentType == null) { - componentType = new ClassType(TypeCategory.SIMPLE, clazz); - } - return componentType; - } - - @Override - public Type getEnclosingType() { - if (enclosingType == null) { - Class enclosingClass = javaClass.getEnclosingClass(); - if (enclosingClass != null) { - enclosingType = new ClassType(enclosingClass); - } + private final TypeCategory category; + + private final Class javaClass; + + private final String className; + + private final List parameters; + + private Type arrayType, componentType, enclosingType; + + public ClassType(Class javaClass, Type... parameters) { + this(TypeCategory.SIMPLE, javaClass, Arrays.asList(parameters)); + } + + public ClassType(TypeCategory category, Class clazz, Type... parameters) { + this(category, clazz, Arrays.asList(parameters)); + } + + public ClassType(TypeCategory category, Class clazz, List parameters) { + this.category = category; + this.javaClass = clazz; + this.parameters = parameters; + this.className = ClassUtils.getFullName(javaClass); + } + + @Override + public Type as(TypeCategory c) { + if (category == c) { + return this; + } else { + return new ClassType(c, javaClass); + } + } + + @Override + public Type asArrayType() { + if (arrayType == null) { + String fullName = ClassUtils.getFullName(javaClass) + "[]"; + String simpleName = javaClass.getSimpleName() + "[]"; + arrayType = + new SimpleType(TypeCategory.ARRAY, fullName, getPackageName(), simpleName, false, false); + } + return arrayType; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Type) { + Type t = (Type) o; + return t.getFullName().equals(className) && t.getParameters().equals(parameters); + } else { + return false; + } + } + + public TypeCategory getCategory() { + return category; + } + + @Override + public Type getComponentType() { + Class clazz = javaClass.getComponentType(); + if (clazz != null && componentType == null) { + componentType = new ClassType(TypeCategory.SIMPLE, clazz); + } + return componentType; + } + + @Override + public Type getEnclosingType() { + if (enclosingType == null) { + Class enclosingClass = javaClass.getEnclosingClass(); + if (enclosingClass != null) { + enclosingType = new ClassType(enclosingClass); + } + } + return enclosingType; + } + + @Override + public String getFullName() { + return className; + } + + @Override + public String getGenericName(boolean asArgType) { + return getGenericName( + asArgType, Collections.singleton("java.lang"), Collections.emptySet()); + } + + @Override + public String getGenericName(boolean asArgType, Set packages, Set classes) { + if (parameters.isEmpty()) { + return ClassUtils.getName(javaClass, packages, classes); + } else { + StringBuilder builder = new StringBuilder(); + builder.append(ClassUtils.getName(javaClass, packages, classes)); + builder.append("<"); + boolean first = true; + for (Type parameter : parameters) { + if (!first) { + builder.append(", "); } - return enclosingType; - } - - @Override - public String getFullName() { - return className; - } - - @Override - public String getGenericName(boolean asArgType) { - return getGenericName(asArgType, Collections.singleton("java.lang"), - Collections. emptySet()); - } - - @Override - public String getGenericName(boolean asArgType, Set packages, Set classes) { - if (parameters.isEmpty()) { - return ClassUtils.getName(javaClass, packages, classes); + if (parameter == null || parameter.getFullName().equals(getFullName())) { + builder.append("?"); } else { - StringBuilder builder = new StringBuilder(); - builder.append(ClassUtils.getName(javaClass, packages, classes)); - builder.append("<"); - boolean first = true; - for (Type parameter : parameters) { - if (!first) { - builder.append(", "); - } - if (parameter == null || parameter.getFullName().equals(getFullName())) { - builder.append("?"); - } else { - builder.append(parameter.getGenericName(false, packages, classes)); - } - first = false; - } - builder.append(">"); - return builder.toString(); + builder.append(parameter.getGenericName(false, packages, classes)); } - } - - public Class getJavaClass() { - return javaClass; - } - - @Override - public String getPackageName() { - return ClassUtils.getPackageName(javaClass); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public String getRawName(Set packages, Set classes) { - return ClassUtils.getName(javaClass, packages, classes); - } - - @Override - public String getSimpleName() { - return javaClass.getSimpleName(); - } - - @Override - public int hashCode() { - return className.hashCode(); - } - - @Override - public boolean isFinal() { - return Modifier.isFinal(javaClass.getModifiers()); - } - - @Override - public boolean isPrimitive() { - return javaClass.isPrimitive(); - } - - @Override - public boolean isMember() { - return javaClass.getEnclosingClass() != null; - } - - @Override - public String toString() { - return getGenericName(true); - } - + first = false; + } + builder.append(">"); + return builder.toString(); + } + } + + public Class getJavaClass() { + return javaClass; + } + + @Override + public String getPackageName() { + return ClassUtils.getPackageName(javaClass); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public String getRawName(Set packages, Set classes) { + return ClassUtils.getName(javaClass, packages, classes); + } + + @Override + public String getSimpleName() { + return javaClass.getSimpleName(); + } + + @Override + public int hashCode() { + return className.hashCode(); + } + + @Override + public boolean isFinal() { + return Modifier.isFinal(javaClass.getModifiers()); + } + + @Override + public boolean isPrimitive() { + return javaClass.isPrimitive(); + } + + @Override + public boolean isMember() { + return javaClass.getEnclosingClass() != null; + } + + @Override + public String toString() { + return getGenericName(true); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Constructor.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Constructor.java index 6afc52bad7..df87332bd4 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Constructor.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Constructor.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -17,34 +17,32 @@ /** * @author tiwe - * */ public final class Constructor { - private final Collection parameters; + private final Collection parameters; - public Constructor(Collection params) { - parameters = params; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Constructor) { - return ((Constructor) o).parameters.equals(parameters); - } else { - return false; - } - } + public Constructor(Collection params) { + parameters = params; + } - public Collection getParameters() { - return parameters; + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Constructor) { + return ((Constructor) o).parameters.equals(parameters); + } else { + return false; } + } - @Override - public int hashCode() { - return parameters.hashCode(); - } + public Collection getParameters() { + return parameters; + } + @Override + public int hashCode() { + return parameters.hashCode(); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Parameter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Parameter.java index 241ed73b3f..3bc3168598 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Parameter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Parameter.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -15,47 +15,47 @@ /** * Parameter represents a parameter in a Constructor - * + * * @author tiwe */ public final class Parameter { - private final String name; + private final String name; - private final Type type; + private final Type type; - public Parameter(String name, Type type) { - this.name = name; - this.type = type; - } + public Parameter(String name, Type type) { + this.name = name; + this.type = type; + } - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Parameter) { - Parameter t = (Parameter) o; - return type.equals(t.type) && name.equals(t.name); - } else { - return false; - } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Parameter) { + Parameter t = (Parameter) o; + return type.equals(t.type) && name.equals(t.name); + } else { + return false; } + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Type getType() { - return type; - } + public Type getType() { + return type; + } - @Override - public int hashCode() { - return type.hashCode(); - } + @Override + public int hashCode() { + return type.hashCode(); + } - @Override - public String toString() { - return type + " " + name; - } + @Override + public String toString() { + return type + " " + name; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/SimpleType.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/SimpleType.java index bec61531b5..38d48e9a4b 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/SimpleType.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/SimpleType.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -26,247 +26,285 @@ */ public class SimpleType implements Type { - private static final Map> PRIMITIVES = new HashMap>(); - - static { - for (Class cl : Arrays.>asList(byte.class, int.class, long.class, short.class, - float.class, double.class, boolean.class, char.class)) { - PRIMITIVES.put(cl.getName(), cl); - } + private static final Map> PRIMITIVES = new HashMap>(); + + static { + for (Class cl : + Arrays.>asList( + byte.class, + int.class, + long.class, + short.class, + float.class, + double.class, + boolean.class, + char.class)) { + PRIMITIVES.put(cl.getName(), cl); } - - private final TypeCategory category; - - private final String fullName, outerClassName, packageName, simpleName, localName; - - private final List parameters; - - private final boolean primitiveClass, finalClass, memberClass; - - private Type arrayType, componentType, enclosingType; - - private transient Class javaClass; - - public SimpleType(String fullName, String packageName, String simpleName, Type... parameters) { - this(TypeCategory.SIMPLE, fullName, packageName, simpleName, false, false, Arrays - .asList(parameters)); + } + + private final TypeCategory category; + + private final String fullName, outerClassName, packageName, simpleName, localName; + + private final List parameters; + + private final boolean primitiveClass, finalClass, memberClass; + private Type arrayType, componentType, enclosingType; + + private transient Class javaClass; + + public SimpleType(String fullName, String packageName, String simpleName, Type... parameters) { + this( + TypeCategory.SIMPLE, + fullName, + packageName, + simpleName, + false, + false, + Arrays.asList(parameters)); + } + + public SimpleType(String simpleName) { + this(TypeCategory.SIMPLE, simpleName, "", simpleName, false, false); + } + + public SimpleType(Type type, List parameters) { + this( + type.getCategory(), + type.getFullName(), + type.getPackageName(), + type.getSimpleName(), + type.isPrimitive(), + type.isFinal(), + parameters); + } + + public SimpleType(Type type, Type... parameters) { + this( + type.getCategory(), + type.getFullName(), + type.getPackageName(), + type.getSimpleName(), + type.isPrimitive(), + type.isFinal(), + Arrays.asList(parameters)); + } + + public SimpleType( + TypeCategory category, + String fullName, + String packageName, + String simpleName, + boolean primitiveClass, + boolean finalClass, + List parameters) { + this.category = category; + this.fullName = fullName; + this.packageName = packageName; + this.simpleName = simpleName; + if (packageName.length() > 0) { + this.localName = fullName.substring(packageName.length() + 1); + } else { + this.localName = fullName; } - - public SimpleType(String simpleName) { - this(TypeCategory.SIMPLE, simpleName, "", simpleName, false, false); + if (localName.contains(".")) { + this.outerClassName = fullName.substring(0, fullName.lastIndexOf('.')); + } else { + this.outerClassName = fullName; } - - public SimpleType(Type type, List parameters) { - this(type.getCategory(), type.getFullName(), type.getPackageName(), type.getSimpleName(), - type.isPrimitive(), type.isFinal(), parameters); + this.primitiveClass = primitiveClass; + this.finalClass = finalClass; + this.parameters = parameters; + this.memberClass = localName.contains("."); + } + + public SimpleType( + TypeCategory typeCategory, + String fullName, + String packageName, + String simpleName, + boolean p, + boolean f, + Type... parameters) { + this(typeCategory, fullName, packageName, simpleName, p, f, Arrays.asList(parameters)); + } + + @Override + public Type as(TypeCategory c) { + if (category != c) { + return new SimpleType( + c, fullName, packageName, simpleName, primitiveClass, finalClass, parameters); + } else { + return this; } - - public SimpleType(Type type, Type... parameters) { - this(type.getCategory(), type.getFullName(), type.getPackageName(), type.getSimpleName(), - type.isPrimitive(), type.isFinal(), Arrays.asList(parameters)); + } + + @Override + public Type asArrayType() { + if (arrayType == null) { + String newFullName = getFullName() + "[]"; + String newSimpleName = getSimpleName() + "[]"; + arrayType = + new SimpleType( + TypeCategory.ARRAY, newFullName, getPackageName(), newSimpleName, false, false); } - - public SimpleType(TypeCategory category, String fullName, String packageName, - String simpleName, boolean primitiveClass, boolean finalClass, List parameters) { - this.category = category; - this.fullName = fullName; - this.packageName = packageName; - this.simpleName = simpleName; - if (packageName.length() > 0) { - this.localName = fullName.substring(packageName.length() + 1); - } else { - this.localName = fullName; - } - if (localName.contains(".")) { - this.outerClassName = fullName.substring(0, fullName.lastIndexOf('.')); - } else { - this.outerClassName = fullName; - } - this.primitiveClass = primitiveClass; - this.finalClass = finalClass; - this.parameters = parameters; - this.memberClass = localName.contains("."); + return arrayType; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Type) { + Type t = (Type) o; + return t.getFullName().equals(fullName) && t.getParameters().equals(parameters); + } else { + return false; } - - public SimpleType(TypeCategory typeCategory, String fullName, String packageName, - String simpleName, boolean p, boolean f, Type... parameters) { - this(typeCategory, fullName, packageName, simpleName, p, f, Arrays.asList(parameters)); + } + + public TypeCategory getCategory() { + return category; + } + + @Override + public Type getComponentType() { + if (fullName.endsWith("[]")) { + if (componentType == null) { + String newFullName = fullName.substring(0, fullName.length() - 2); + String newSimpleName = simpleName.substring(0, simpleName.length() - 2); + componentType = + new SimpleType( + TypeCategory.SIMPLE, newFullName, getPackageName(), newSimpleName, false, false); + } + return componentType; + } else { + return null; } - - @Override - public Type as(TypeCategory c) { - if (category != c) { - return new SimpleType(c, fullName, packageName, simpleName, primitiveClass, finalClass, - parameters); - } else { - return this; - } - } - - @Override - public Type asArrayType() { - if (arrayType == null) { - String newFullName = getFullName() + "[]"; - String newSimpleName = getSimpleName() + "[]"; - arrayType = new SimpleType(TypeCategory.ARRAY, newFullName, getPackageName(), - newSimpleName, false, false); - } - return arrayType; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Type) { - Type t = (Type) o; - return t.getFullName().equals(fullName) && t.getParameters().equals(parameters); - } else { - return false; - } - } - - public TypeCategory getCategory() { - return category; - } - - @Override - public Type getComponentType() { - if (fullName.endsWith("[]")) { - if (componentType == null) { - String newFullName = fullName.substring(0, fullName.length() - 2); - String newSimpleName = simpleName.substring(0, simpleName.length() - 2); - componentType = new SimpleType(TypeCategory.SIMPLE, newFullName, getPackageName(), - newSimpleName, false, false); - } - return componentType; - } else { - return null; - } + } + + @Override + public Type getEnclosingType() { + if (enclosingType == null && memberClass) { + String newLocalName = localName.substring(0, localName.lastIndexOf('.')); + String newSimpleName = newLocalName.substring(newLocalName.lastIndexOf('.') + 1); + enclosingType = new SimpleType(outerClassName, packageName, newSimpleName); } - - @Override - public Type getEnclosingType() { - if (enclosingType == null && memberClass) { - String newLocalName = localName.substring(0, localName.lastIndexOf('.')); - String newSimpleName = newLocalName.substring(newLocalName.lastIndexOf('.') + 1); - enclosingType = new SimpleType(outerClassName, packageName, newSimpleName); + return enclosingType; + } + + @Override + public String getFullName() { + return fullName; + } + + @Override + public String getGenericName(boolean asArgType) { + return getGenericName( + asArgType, Collections.singleton("java.lang"), Collections.emptySet()); + } + + @Override + public String getGenericName(boolean asArgType, Set packages, Set classes) { + if (parameters.isEmpty()) { + return getRawName(packages, classes); + } else { + StringBuilder builder = new StringBuilder(); + builder.append(getRawName(packages, classes)); + builder.append("<"); + boolean first = true; + for (Type parameter : parameters) { + if (!first) { + builder.append(", "); } - return enclosingType; - } - - @Override - public String getFullName() { - return fullName; - } - - @Override - public String getGenericName(boolean asArgType) { - return getGenericName(asArgType, Collections.singleton("java.lang"), - Collections. emptySet()); - } - - @Override - public String getGenericName(boolean asArgType, Set packages, Set classes) { - if (parameters.isEmpty()) { - return getRawName(packages, classes); + if (parameter == null || parameter.getFullName().equals(fullName)) { + builder.append("?"); } else { - StringBuilder builder = new StringBuilder(); - builder.append(getRawName(packages, classes)); - builder.append("<"); - boolean first = true; - for (Type parameter : parameters) { - if (!first) { - builder.append(", "); - } - if (parameter == null || parameter.getFullName().equals(fullName)) { - builder.append("?"); - } else { - builder.append(parameter.getGenericName(false, packages, classes)); - } - first = false; - } - builder.append(">"); - return builder.toString(); - } - } - - @Override - public Class getJavaClass() { - if (javaClass == null) { - String className; - if (packageName.length() > 0) { - className = packageName + "." + localName.replace('.', '$'); - } else { - className = localName.replace('.', '$'); - } - try { - if (className.endsWith("[]")) { - Class component = getComponentType().getJavaClass(); - javaClass = Array.newInstance(component, 0).getClass(); - } else if (PRIMITIVES.containsKey(className)) { - javaClass = PRIMITIVES.get(className); - } else { - javaClass = Class.forName(className); - } - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + builder.append(parameter.getGenericName(false, packages, classes)); } - return javaClass; + first = false; + } + builder.append(">"); + return builder.toString(); } - - @Override - public String getPackageName() { - return packageName; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public String getRawName(Set packages, Set classes) { - if (classes.contains(fullName)) { - return simpleName; - } else if (classes.contains(outerClassName)) { - return fullName.substring(outerClassName.lastIndexOf('.') + 1); - } else if (packages.contains(packageName)) { - return localName; + } + + @Override + public Class getJavaClass() { + if (javaClass == null) { + String className; + if (packageName.length() > 0) { + className = packageName + "." + localName.replace('.', '$'); + } else { + className = localName.replace('.', '$'); + } + try { + if (className.endsWith("[]")) { + Class component = getComponentType().getJavaClass(); + javaClass = Array.newInstance(component, 0).getClass(); + } else if (PRIMITIVES.containsKey(className)) { + javaClass = PRIMITIVES.get(className); } else { - return fullName; + javaClass = Class.forName(className); } + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } } - - @Override - public String getSimpleName() { - return simpleName; - } - - @Override - public int hashCode() { - return fullName.hashCode(); - } - - @Override - public boolean isFinal() { - return finalClass; - } - - @Override - public boolean isPrimitive() { - return primitiveClass; - } - - @Override - public boolean isMember() { - return memberClass; + return javaClass; + } + + @Override + public String getPackageName() { + return packageName; + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public String getRawName(Set packages, Set classes) { + if (classes.contains(fullName)) { + return simpleName; + } else if (classes.contains(outerClassName)) { + return fullName.substring(outerClassName.lastIndexOf('.') + 1); + } else if (packages.contains(packageName)) { + return localName; + } else { + return fullName; } - - @Override - public String toString() { - return getGenericName(true); - } - + } + + @Override + public String getSimpleName() { + return simpleName; + } + + @Override + public int hashCode() { + return fullName.hashCode(); + } + + @Override + public boolean isFinal() { + return finalClass; + } + + @Override + public boolean isPrimitive() { + return primitiveClass; + } + + @Override + public boolean isMember() { + return memberClass; + } + + @Override + public String toString() { + return getGenericName(true); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Type.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Type.java index 568d6b373f..6006f1e73e 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Type.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Type.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -21,36 +21,35 @@ */ public interface Type { - Type as(TypeCategory category); + Type as(TypeCategory category); - Type asArrayType(); + Type asArrayType(); - Type getComponentType(); + Type getComponentType(); - Type getEnclosingType(); + Type getEnclosingType(); - TypeCategory getCategory(); + TypeCategory getCategory(); - String getFullName(); + String getFullName(); - String getGenericName(boolean asArgType); + String getGenericName(boolean asArgType); - String getGenericName(boolean asArgType, Set packages, Set classes); + String getGenericName(boolean asArgType, Set packages, Set classes); - Class getJavaClass(); + Class getJavaClass(); - String getPackageName(); + String getPackageName(); - List getParameters(); + List getParameters(); - String getRawName(Set packages, Set classes); + String getRawName(Set packages, Set classes); - String getSimpleName(); + String getSimpleName(); - boolean isFinal(); + boolean isFinal(); - boolean isPrimitive(); + boolean isPrimitive(); - boolean isMember(); - -} \ No newline at end of file + boolean isMember(); +} diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeAdapter.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeAdapter.java index 158359b5e6..b61925eff9 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeAdapter.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeAdapter.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -18,115 +18,113 @@ /** * TypeAdapter is a basic adapter implementation for the Type interface - * + * * @author tiwe - * */ public class TypeAdapter implements Type { - protected final Type type; - - public TypeAdapter(Type type) { - this.type = type; - } - - @Override - public Type as(TypeCategory category) { - return type.as(category); - } - - @Override - public Type asArrayType() { - return type.asArrayType(); - } - - @Override - public Type getComponentType() { - return type.getComponentType(); - } - - @Override - public Type getEnclosingType() { - return type.getEnclosingType(); - } - - @Override - public boolean equals(Object o) { - return type.equals(o); - } - - @Override - public TypeCategory getCategory() { - return type.getCategory(); - } - - @Override - public String getFullName() { - return type.getFullName(); - } - - @Override - public String getGenericName(boolean asArgType) { - return type.getGenericName(asArgType); - } - - @Override - public String getGenericName(boolean asArgType, Set packages, Set classes) { - return type.getGenericName(asArgType, packages, classes); - } - - @Override - public Class getJavaClass() { - return type.getJavaClass(); - } - - @Override - public String getPackageName() { - return type.getPackageName(); - } - - @Override - public List getParameters() { - return type.getParameters(); - } - - @Override - public String getRawName(Set packages, Set classes) { - return type.getRawName(packages, classes); - } - - @Override - public String getSimpleName() { - return type.getSimpleName(); - } - - protected Type getType() { - return type; - } - - @Override - public int hashCode() { - return type.hashCode(); - } - - @Override - public boolean isFinal() { - return type.isFinal(); - } - - @Override - public boolean isPrimitive() { - return type.isPrimitive(); - } - - @Override - public boolean isMember() { - return type.isMember(); - } - - @Override - public String toString() { - return type.toString(); - } - + protected final Type type; + + public TypeAdapter(Type type) { + this.type = type; + } + + @Override + public Type as(TypeCategory category) { + return type.as(category); + } + + @Override + public Type asArrayType() { + return type.asArrayType(); + } + + @Override + public Type getComponentType() { + return type.getComponentType(); + } + + @Override + public Type getEnclosingType() { + return type.getEnclosingType(); + } + + @Override + public boolean equals(Object o) { + return type.equals(o); + } + + @Override + public TypeCategory getCategory() { + return type.getCategory(); + } + + @Override + public String getFullName() { + return type.getFullName(); + } + + @Override + public String getGenericName(boolean asArgType) { + return type.getGenericName(asArgType); + } + + @Override + public String getGenericName(boolean asArgType, Set packages, Set classes) { + return type.getGenericName(asArgType, packages, classes); + } + + @Override + public Class getJavaClass() { + return type.getJavaClass(); + } + + @Override + public String getPackageName() { + return type.getPackageName(); + } + + @Override + public List getParameters() { + return type.getParameters(); + } + + @Override + public String getRawName(Set packages, Set classes) { + return type.getRawName(packages, classes); + } + + @Override + public String getSimpleName() { + return type.getSimpleName(); + } + + protected Type getType() { + return type; + } + + @Override + public int hashCode() { + return type.hashCode(); + } + + @Override + public boolean isFinal() { + return type.isFinal(); + } + + @Override + public boolean isPrimitive() { + return type.isPrimitive(); + } + + @Override + public boolean isMember() { + return type.isMember(); + } + + @Override + public String toString() { + return type.toString(); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeCategory.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeCategory.java index 80e31cf29c..06d0ae3e06 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeCategory.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeCategory.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -18,130 +18,108 @@ /** * TypeCategory defines the expression type used for a Field - * + * * @author tiwe - * */ public enum TypeCategory { - /** - * - */ - SIMPLE(null), - /** - * - */ - MAP(null), - /** - * - */ - COLLECTION(null), - /** - * - */ - LIST(COLLECTION), - /** - * - */ - SET(COLLECTION), - /** - * - */ - ARRAY(null), - /** - * - */ - COMPARABLE(SIMPLE), - /** - * - */ - BOOLEAN(COMPARABLE, Boolean.class.getName()), - /** - * - */ - DATE(COMPARABLE, java.sql.Date.class.getName(), "org.joda.time.LocalDate", - "java.time.LocalDate"), - /** - * - */ - DATETIME(COMPARABLE, java.util.Calendar.class.getName(), java.util.Date.class.getName(), - java.sql.Timestamp.class.getName(), "org.joda.time.LocalDateTime", - "org.joda.time.Instant", "org.joda.time.DateTime", "org.joda.time.DateMidnight", - "java.time.Instant", "java.time.LocalDateTime", "java.time.OffsetDateTime", "java.time.ZonedDateTime"), - /** - * - */ - ENUM(COMPARABLE), - /** - * - */ - CUSTOM(null), + /** */ + SIMPLE(null), + /** */ + MAP(null), + /** */ + COLLECTION(null), + /** */ + LIST(COLLECTION), + /** */ + SET(COLLECTION), + /** */ + ARRAY(null), + /** */ + COMPARABLE(SIMPLE), + /** */ + BOOLEAN(COMPARABLE, Boolean.class.getName()), + /** */ + DATE(COMPARABLE, java.sql.Date.class.getName(), "org.joda.time.LocalDate", "java.time.LocalDate"), + /** */ + DATETIME( + COMPARABLE, + java.util.Calendar.class.getName(), + java.util.Date.class.getName(), + java.sql.Timestamp.class.getName(), + "org.joda.time.LocalDateTime", + "org.joda.time.Instant", + "org.joda.time.DateTime", + "org.joda.time.DateMidnight", + "java.time.Instant", + "java.time.LocalDateTime", + "java.time.OffsetDateTime", + "java.time.ZonedDateTime"), + /** */ + ENUM(COMPARABLE), + /** */ + CUSTOM(null), - /** - * - */ - ENTITY(null), + /** */ + ENTITY(null), - /** - * - */ - NUMERIC(COMPARABLE), - /** - * - */ - STRING(COMPARABLE, String.class.getName()), - /** - * - */ - TIME(COMPARABLE, java.sql.Time.class.getName(), "org.joda.time.LocalTime", - "java.time.LocalTime", "java.time.OffsetTime"); + /** */ + NUMERIC(COMPARABLE), + /** */ + STRING(COMPARABLE, String.class.getName()), + /** */ + TIME( + COMPARABLE, + java.sql.Time.class.getName(), + "org.joda.time.LocalTime", + "java.time.LocalTime", + "java.time.OffsetTime"); - private final TypeCategory superType; + private final TypeCategory superType; - private final Set types; + private final Set types; - TypeCategory(TypeCategory superType, String... types) { - this.superType = superType; - this.types = new HashSet(types.length); - for (String type : types) { - this.types.add(type); - } + TypeCategory(TypeCategory superType, String... types) { + this.superType = superType; + this.types = new HashSet(types.length); + for (String type : types) { + this.types.add(type); } + } - public TypeCategory getSuperType() { - return superType; - } + public TypeCategory getSuperType() { + return superType; + } - public boolean supports(Class cl) { - return supports(cl.getName()); - } + public boolean supports(Class cl) { + return supports(cl.getName()); + } - public boolean supports(String className) { - return types.contains(className); - } + public boolean supports(String className) { + return types.contains(className); + } - /** - * transitive and reflexive subCategoryOf check - * - * @param ancestor - * @return - */ - public boolean isSubCategoryOf(TypeCategory ancestor) { - if (this == ancestor) { - return true; - } else if (superType == null) { - return false; - } else { - return superType == ancestor || superType.isSubCategoryOf(ancestor); - } + /** + * transitive and reflexive subCategoryOf check + * + * @param ancestor + * @return + */ + public boolean isSubCategoryOf(TypeCategory ancestor) { + if (this == ancestor) { + return true; + } else if (superType == null) { + return false; + } else { + return superType == ancestor || superType.isSubCategoryOf(ancestor); } + } - public static TypeCategory get(String className) { - for (TypeCategory category : values()) { - if (category.supports(className)) { - return category; - } - } - return SIMPLE; + public static TypeCategory get(String className) { + for (TypeCategory category : values()) { + if (category.supports(className)) { + return category; + } } - + return SIMPLE; + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeExtends.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeExtends.java index c0bd393255..86ec69a5bf 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeExtends.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeExtends.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -19,56 +19,54 @@ /** * @author tiwe - * */ public class TypeExtends extends TypeAdapter { - private final String varName; + private final String varName; - public TypeExtends(String varName, Type type) { - super(type); - this.varName = varName; - } + public TypeExtends(String varName, Type type) { + super(type); + this.varName = varName; + } - public TypeExtends(Type type) { - super(type); - varName = null; - } + public TypeExtends(Type type) { + super(type); + varName = null; + } - @Override - public String getGenericName(boolean asArgType) { - return getGenericName(asArgType, Collections. emptySet(), - Collections. emptySet()); - } + @Override + public String getGenericName(boolean asArgType) { + return getGenericName( + asArgType, Collections.emptySet(), Collections.emptySet()); + } - @Override - public String getGenericName(boolean asArgType, Set packages, Set classes) { - if (!asArgType) { - if (Types.OBJECT.equals(type)) { - return "?"; - } else { - String genericName = super.getGenericName(true, packages, classes); - return genericName == null || genericName.isEmpty() ? "?" : "? extends " + genericName; - } - } else { - return super.getGenericName(asArgType, packages, classes); - } + @Override + public String getGenericName(boolean asArgType, Set packages, Set classes) { + if (!asArgType) { + if (Types.OBJECT.equals(type)) { + return "?"; + } else { + String genericName = super.getGenericName(true, packages, classes); + return genericName == null || genericName.isEmpty() ? "?" : "? extends " + genericName; + } + } else { + return super.getGenericName(asArgType, packages, classes); } + } - public String getVarName() { - return varName; - } + public String getVarName() { + return varName; + } - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof TypeExtends) { - return Objects.equals(((TypeExtends) o).varName, varName) - && ((TypeExtends) o).type.equals(type); - } else { - return false; - } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof TypeExtends) { + return Objects.equals(((TypeExtends) o).varName, varName) + && ((TypeExtends) o).type.equals(type); + } else { + return false; } - + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeSuper.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeSuper.java index 71a1cd7587..0890c16189 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeSuper.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/TypeSuper.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -19,61 +19,60 @@ /** * TypeSuper is a Type for type variables and wildcard types - * + * * @author tiwe - * */ public class TypeSuper extends TypeAdapter { - private final Type superType; + private final Type superType; - private final String varName; + private final String varName; - public TypeSuper(String varName, Type type) { - super(Types.OBJECT); - this.superType = type; - this.varName = varName; - } + public TypeSuper(String varName, Type type) { + super(Types.OBJECT); + this.superType = type; + this.varName = varName; + } - public TypeSuper(Type type) { - super(Types.OBJECT); - this.superType = type; - this.varName = null; - } + public TypeSuper(Type type) { + super(Types.OBJECT); + this.superType = type; + this.varName = null; + } - @Override - public String getGenericName(boolean asArgType) { - return getGenericName(asArgType, Collections. emptySet(), - Collections. emptySet()); - } + @Override + public String getGenericName(boolean asArgType) { + return getGenericName( + asArgType, Collections.emptySet(), Collections.emptySet()); + } - @Override - public String getGenericName(boolean asArgType, Set packages, Set classes) { - if (!asArgType) { - if (superType instanceof TypeExtends) { - return "?"; - } else { - return "? super " + superType.getGenericName(true, packages, classes); - } - - } else { - return super.getGenericName(asArgType, packages, classes); - } - } + @Override + public String getGenericName(boolean asArgType, Set packages, Set classes) { + if (!asArgType) { + if (superType instanceof TypeExtends) { + return "?"; + } else { + return "? super " + superType.getGenericName(true, packages, classes); + } - public String getVarName() { - return varName; + } else { + return super.getGenericName(asArgType, packages, classes); } + } + + public String getVarName() { + return varName; + } - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof TypeSuper) { - return Objects.equals(((TypeSuper) o).varName, varName) - && ((TypeSuper) o).superType.equals(superType); - } else { - return false; - } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof TypeSuper) { + return Objects.equals(((TypeSuper) o).varName, varName) + && ((TypeSuper) o).superType.equals(superType); + } else { + return false; } + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Types.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Types.java index c0870ef9d4..623448c04f 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Types.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/model/Types.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -26,94 +26,100 @@ /** * @author tiwe - * */ public final class Types { - - public static final Map PRIMITIVES; - - public static final ClassType OBJECT = new ClassType(TypeCategory.SIMPLE, Object.class); - public static final ClassType OBJECTS = new ClassType(TypeCategory.ARRAY, Object[].class); + public static final Map PRIMITIVES; - public static final ClassType BIG_DECIMAL = new ClassType(TypeCategory.NUMERIC, BigDecimal.class); + public static final ClassType OBJECT = new ClassType(TypeCategory.SIMPLE, Object.class); - public static final ClassType BIG_INTEGER = new ClassType(TypeCategory.NUMERIC, BigInteger.class); + public static final ClassType OBJECTS = new ClassType(TypeCategory.ARRAY, Object[].class); - public static final ClassType BOOLEAN = new ClassType(TypeCategory.BOOLEAN, Boolean.class); + public static final ClassType BIG_DECIMAL = new ClassType(TypeCategory.NUMERIC, BigDecimal.class); - public static final ClassType BOOLEAN_P = new ClassType(TypeCategory.BOOLEAN, boolean.class); + public static final ClassType BIG_INTEGER = new ClassType(TypeCategory.NUMERIC, BigInteger.class); - public static final ClassType BYTE = new ClassType(TypeCategory.NUMERIC, Byte.class); + public static final ClassType BOOLEAN = new ClassType(TypeCategory.BOOLEAN, Boolean.class); - public static final ClassType BYTE_P = new ClassType(TypeCategory.NUMERIC, byte.class); + public static final ClassType BOOLEAN_P = new ClassType(TypeCategory.BOOLEAN, boolean.class); - public static final ClassType CHARACTER = new ClassType(TypeCategory.COMPARABLE, Character.class); + public static final ClassType BYTE = new ClassType(TypeCategory.NUMERIC, Byte.class); - public static final ClassType CHAR = new ClassType(TypeCategory.COMPARABLE, char.class); + public static final ClassType BYTE_P = new ClassType(TypeCategory.NUMERIC, byte.class); - public static final ClassType COLLECTION = new ClassType(TypeCategory.COLLECTION, Collection.class, OBJECT); + public static final ClassType CHARACTER = new ClassType(TypeCategory.COMPARABLE, Character.class); - public static final ClassType DOUBLE = new ClassType(TypeCategory.NUMERIC, Double.class); + public static final ClassType CHAR = new ClassType(TypeCategory.COMPARABLE, char.class); - public static final ClassType DOUBLE_P = new ClassType(TypeCategory.NUMERIC, double.class); + public static final ClassType COLLECTION = + new ClassType(TypeCategory.COLLECTION, Collection.class, OBJECT); - public static final ClassType FLOAT = new ClassType(TypeCategory.NUMERIC, Float.class); + public static final ClassType DOUBLE = new ClassType(TypeCategory.NUMERIC, Double.class); - public static final ClassType FLOAT_P = new ClassType(TypeCategory.NUMERIC, float.class); + public static final ClassType DOUBLE_P = new ClassType(TypeCategory.NUMERIC, double.class); - public static final ClassType INTEGER = new ClassType(TypeCategory.NUMERIC, Integer.class); + public static final ClassType FLOAT = new ClassType(TypeCategory.NUMERIC, Float.class); - public static final ClassType INT = new ClassType(TypeCategory.NUMERIC, int.class); + public static final ClassType FLOAT_P = new ClassType(TypeCategory.NUMERIC, float.class); - public static final ClassType ITERABLE = new ClassType(TypeCategory.SIMPLE, Iterable.class, OBJECT); + public static final ClassType INTEGER = new ClassType(TypeCategory.NUMERIC, Integer.class); - public static final ClassType LIST = new ClassType(TypeCategory.LIST, List.class, OBJECT); + public static final ClassType INT = new ClassType(TypeCategory.NUMERIC, int.class); - public static final ClassType LOCALE = new ClassType(TypeCategory.SIMPLE, Locale.class); + public static final ClassType ITERABLE = + new ClassType(TypeCategory.SIMPLE, Iterable.class, OBJECT); - public static final ClassType LONG = new ClassType(TypeCategory.NUMERIC, Long.class); + public static final ClassType LIST = new ClassType(TypeCategory.LIST, List.class, OBJECT); - public static final ClassType LONG_P = new ClassType(TypeCategory.NUMERIC, long.class); + public static final ClassType LOCALE = new ClassType(TypeCategory.SIMPLE, Locale.class); - public static final ClassType MAP = new ClassType(TypeCategory.MAP, Map.class, OBJECT, OBJECT); + public static final ClassType LONG = new ClassType(TypeCategory.NUMERIC, Long.class); - public static final ClassType SET = new ClassType(TypeCategory.SET, Set.class, OBJECT); + public static final ClassType LONG_P = new ClassType(TypeCategory.NUMERIC, long.class); - public static final ClassType SHORT = new ClassType(TypeCategory.NUMERIC, Short.class); + public static final ClassType MAP = new ClassType(TypeCategory.MAP, Map.class, OBJECT, OBJECT); - public static final ClassType SHORT_P = new ClassType(TypeCategory.NUMERIC, short.class); + public static final ClassType SET = new ClassType(TypeCategory.SET, Set.class, OBJECT); - public static final ClassType STRING = new ClassType(TypeCategory.STRING, String.class); + public static final ClassType SHORT = new ClassType(TypeCategory.NUMERIC, Short.class); - public static final ClassType URI = new ClassType(TypeCategory.COMPARABLE, URI.class); + public static final ClassType SHORT_P = new ClassType(TypeCategory.NUMERIC, short.class); - public static final ClassType VOID = new ClassType(TypeCategory.SIMPLE, void.class); + public static final ClassType STRING = new ClassType(TypeCategory.STRING, String.class); - public static final SimpleType DATE_TIME = new SimpleType(TypeCategory.DATETIME, - "org.joda.time.DateTime", "org.joda.time", "DateTime", false, false); + public static final ClassType URI = new ClassType(TypeCategory.COMPARABLE, URI.class); - public static final SimpleType LOCAL_DATE = new SimpleType(TypeCategory.DATE, - "org.joda.time.LocalDate", "org.joda.time", "LocalDate", false, false); + public static final ClassType VOID = new ClassType(TypeCategory.SIMPLE, void.class); - public static final SimpleType LOCAL_TIME = new SimpleType(TypeCategory.TIME, - "org.joda.time.LocalTime", "org.joda.time", "LocalTime", false, false); + public static final SimpleType DATE_TIME = + new SimpleType( + TypeCategory.DATETIME, + "org.joda.time.DateTime", + "org.joda.time", + "DateTime", + false, + false); - static { - Map primitives = new HashMap(); - primitives.put(BOOLEAN, BOOLEAN_P); - primitives.put(BYTE, BYTE_P); - primitives.put(CHARACTER, CHAR); - primitives.put(DOUBLE, DOUBLE_P); - primitives.put(FLOAT, FLOAT_P); - primitives.put(INTEGER, INT); - primitives.put(LONG, LONG_P); - primitives.put(SHORT, SHORT_P); - PRIMITIVES = Collections.unmodifiableMap(primitives); - } + public static final SimpleType LOCAL_DATE = + new SimpleType( + TypeCategory.DATE, "org.joda.time.LocalDate", "org.joda.time", "LocalDate", false, false); - - private Types() { - } + public static final SimpleType LOCAL_TIME = + new SimpleType( + TypeCategory.TIME, "org.joda.time.LocalTime", "org.joda.time", "LocalTime", false, false); + static { + Map primitives = new HashMap(); + primitives.put(BOOLEAN, BOOLEAN_P); + primitives.put(BYTE, BYTE_P); + primitives.put(CHARACTER, CHAR); + primitives.put(DOUBLE, DOUBLE_P); + primitives.put(FLOAT, FLOAT_P); + primitives.put(INTEGER, INT); + primitives.put(LONG, LONG_P); + primitives.put(SHORT, SHORT_P); + PRIMITIVES = Collections.unmodifiableMap(primitives); + } + + private Types() {} } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ClassUtils.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ClassUtils.java index ad2b8592bb..4bd7cf9f43 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ClassUtils.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ClassUtils.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -18,81 +18,78 @@ /** * @author tiwe - * */ public final class ClassUtils { - private static final Set JAVA_LANG = Collections.singleton("java.lang"); - - public static String getName(Class cl) { - return getName(cl, JAVA_LANG, Collections. emptySet()); - } + private static final Set JAVA_LANG = Collections.singleton("java.lang"); + + public static String getName(Class cl) { + return getName(cl, JAVA_LANG, Collections.emptySet()); + } - public static String getFullName(Class cl) { - if (cl.isArray()) { - return getFullName(cl.getComponentType()) + "[]"; - } - final String name = cl.getName(); - if (name.indexOf('$') > 0) { - return getFullName(cl.getDeclaringClass()) + "." + cl.getSimpleName(); - } - return name; + public static String getFullName(Class cl) { + if (cl.isArray()) { + return getFullName(cl.getComponentType()) + "[]"; } + final String name = cl.getName(); + if (name.indexOf('$') > 0) { + return getFullName(cl.getDeclaringClass()) + "." + cl.getSimpleName(); + } + return name; + } - public static String getPackageName(Class cl) { - while (cl.isArray()) { - cl = cl.getComponentType(); - } - final String name = cl.getName(); - final int i = name.lastIndexOf('.'); - if (i > 0) { - return name.substring(0, i); - } else { - return ""; - } + public static String getPackageName(Class cl) { + while (cl.isArray()) { + cl = cl.getComponentType(); } - - public static String getName(Class cl, Set packages, Set classes) { - if (cl.isArray()) { - return getName(cl.getComponentType(), packages, classes) + "[]"; - } - final String canonicalName = cl.getName().replace('$', '.'); - final int i = cl.getName().lastIndexOf('.'); - if (classes.contains(canonicalName)) { - return cl.getSimpleName(); - } else if (cl.getEnclosingClass() != null) { - return getName(cl.getEnclosingClass(), packages, classes) + "." + cl.getSimpleName(); - } else if (i == -1) { - return canonicalName; - } else if (packages.contains(canonicalName.substring(0, i))) { - return canonicalName.substring(i + 1); - } else { - return canonicalName; - } + final String name = cl.getName(); + final int i = name.lastIndexOf('.'); + if (i > 0) { + return name.substring(0, i); + } else { + return ""; } + } - public static Class normalize(Class clazz) { - if (List.class.isAssignableFrom(clazz)) { - return List.class; - } else if (Set.class.isAssignableFrom(clazz)) { - return Set.class; - } else if (Collection.class.isAssignableFrom(clazz)) { - return Collection.class; - } else if (Map.class.isAssignableFrom(clazz)) { - return Map.class; - // check for CGLIB generated classes - } else if (clazz.getName().contains("$$")) { - Class zuper = clazz.getSuperclass(); - if (zuper != null && !Object.class.equals(zuper)) { - return zuper; - } - } else if (!Modifier.isPublic(clazz.getModifiers())) { - return normalize(clazz.getSuperclass()); - } - return clazz; + public static String getName(Class cl, Set packages, Set classes) { + if (cl.isArray()) { + return getName(cl.getComponentType(), packages, classes) + "[]"; + } + final String canonicalName = cl.getName().replace('$', '.'); + final int i = cl.getName().lastIndexOf('.'); + if (classes.contains(canonicalName)) { + return cl.getSimpleName(); + } else if (cl.getEnclosingClass() != null) { + return getName(cl.getEnclosingClass(), packages, classes) + "." + cl.getSimpleName(); + } else if (i == -1) { + return canonicalName; + } else if (packages.contains(canonicalName.substring(0, i))) { + return canonicalName.substring(i + 1); + } else { + return canonicalName; } + } - private ClassUtils() { + public static Class normalize(Class clazz) { + if (List.class.isAssignableFrom(clazz)) { + return List.class; + } else if (Set.class.isAssignableFrom(clazz)) { + return Set.class; + } else if (Collection.class.isAssignableFrom(clazz)) { + return Collection.class; + } else if (Map.class.isAssignableFrom(clazz)) { + return Map.class; + // check for CGLIB generated classes + } else if (clazz.getName().contains("$$")) { + Class zuper = clazz.getSuperclass(); + if (zuper != null && !Object.class.equals(zuper)) { + return zuper; + } + } else if (!Modifier.isPublic(clazz.getModifiers())) { + return normalize(clazz.getSuperclass()); } + return clazz; + } + private ClassUtils() {} } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ScalaSyntaxUtils.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ScalaSyntaxUtils.java index 1d7a6f058e..36950e40ce 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ScalaSyntaxUtils.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/ScalaSyntaxUtils.java @@ -1,6 +1,6 @@ /* * Copyright 2010, Mysema Ltd - * + * * 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 @@ -19,20 +19,65 @@ /** * @author tiwe - * */ public final class ScalaSyntaxUtils { - private ScalaSyntaxUtils() { } + private ScalaSyntaxUtils() {} - private static final Set reserved = new HashSet(Arrays.asList("abstract", "do", - "finally", "import", "object", "return", "trait", "var", "_", ":", "case", "else", - "for", "lazy", "override", "sealed", "try", "while", "=", "=>", "<-", "catch", - "extends", "forSome", "match", "package", "super", "true", "with", "<:", "class", - "false", "if", "new", "private", "this", "type", "yield", "<%", ">:", "def", "final", - "implicit", "null", "protected", "throw", "val", "#", "@")); + private static final Set reserved = + new HashSet( + Arrays.asList( + "abstract", + "do", + "finally", + "import", + "object", + "return", + "trait", + "var", + "_", + ":", + "case", + "else", + "for", + "lazy", + "override", + "sealed", + "try", + "while", + "=", + "=>", + "<-", + "catch", + "extends", + "forSome", + "match", + "package", + "super", + "true", + "with", + "<:", + "class", + "false", + "if", + "new", + "private", + "this", + "type", + "yield", + "<%", + ">:", + "def", + "final", + "implicit", + "null", + "protected", + "throw", + "val", + "#", + "@")); - public static boolean isReserved(String token) { - return reserved.contains(token); - } + public static boolean isReserved(String token) { + return reserved.contains(token); + } } diff --git a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/package-info.java b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/package-info.java index 3b18ad601e..f22bce7845 100644 --- a/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/package-info.java +++ b/querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/support/package-info.java @@ -5,4 +5,3 @@ */ package com.querydsl.codegen.utils.support; - diff --git a/querydsl-codegen-utils/src/test/java/NestedTest.java b/querydsl-codegen-utils/src/test/java/NestedTest.java index 75b7c36a6b..ed2ffc4ac6 100644 --- a/querydsl-codegen-utils/src/test/java/NestedTest.java +++ b/querydsl-codegen-utils/src/test/java/NestedTest.java @@ -1,25 +1,21 @@ import static org.junit.Assert.assertEquals; -import org.junit.Test; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.support.ClassUtils; +import org.junit.Test; public class NestedTest { - public static class Inner { - - } - - @Test - public void ClassUtils_getName() { - String name = ClassUtils.getName(NestedTest.Inner.class); - assertEquals("NestedTest.Inner", name); - } + public static class Inner {} - @Test - public void ClassType_getName() { - assertEquals("NestedTest.Inner", new ClassType(NestedTest.Inner.class).getFullName()); - } + @Test + public void ClassUtils_getName() { + String name = ClassUtils.getName(NestedTest.Inner.class); + assertEquals("NestedTest.Inner", name); + } + @Test + public void ClassType_getName() { + assertEquals("NestedTest.Inner", new ClassType(NestedTest.Inner.class).getFullName()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation.java index 7218a81313..b404de94f2 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation.java @@ -11,14 +11,13 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target({ TYPE }) +@Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Annotation { - boolean prop1() default false; + boolean prop1() default false; - boolean prop2(); - - Class clazz(); + boolean prop2(); + Class clazz(); } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2.java index 49bb20c371..8c37116bf4 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2.java @@ -1,6 +1,4 @@ -/** - * - */ +/** */ package com.querydsl.codegen.utils; import static java.lang.annotation.ElementType.TYPE; @@ -9,10 +7,9 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target({ TYPE }) +@Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Annotation2 { - String value(); - -} \ No newline at end of file + String value(); +} diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2Impl.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2Impl.java index 52b9ac0396..1b2a036f6a 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2Impl.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation2Impl.java @@ -5,20 +5,19 @@ @SuppressWarnings("all") public class Annotation2Impl implements Annotation2 { - private final String value; + private final String value; - public Annotation2Impl(String value) { - this.value = value; - } + public Annotation2Impl(String value) { + this.value = value; + } - @Override - public String value() { - return value; - } - - @Override - public Class annotationType() { - return Annotation2.class; - } + @Override + public String value() { + return value; + } + @Override + public Class annotationType() { + return Annotation2.class; + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation3.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation3.java index 4981b1c1ce..c07aa58aa0 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation3.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Annotation3.java @@ -12,10 +12,9 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target({ TYPE }) +@Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Annotation3 { - ElementType type(); - + ElementType type(); } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/AnnotationTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/AnnotationTest.java index 8d29b0e25d..a652dfef30 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/AnnotationTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/AnnotationTest.java @@ -11,7 +11,6 @@ import java.io.IOException; import java.io.StringWriter; import java.lang.annotation.ElementType; - import org.junit.Test; @Annotation(prop2 = false, clazz = AnnotationTest.class) @@ -19,61 +18,65 @@ @Annotation3(type = ElementType.ANNOTATION_TYPE) public class AnnotationTest { - private StringWriter w = new StringWriter(); - private CodeWriter writer = new JavaWriter(w); - - @Test - public void ClassAnnotation() throws IOException { - writer.annotation(getClass().getAnnotation(Annotation.class)); - String option1 = "@com.querydsl.codegen.utils.Annotation(clazz=com.querydsl.codegen.utils.AnnotationTest.class, prop2=false)"; - String option2 = "@com.querydsl.codegen.utils.Annotation(prop2=false, clazz=com.querydsl.codegen.utils.AnnotationTest.class)"; - String serialized = w.toString().trim(); - assertTrue(serialized.equals(option1) || serialized.equals(option2)); - } + private StringWriter w = new StringWriter(); + private CodeWriter writer = new JavaWriter(w); - @Test - public void ClassAnnotation2() throws IOException { - writer.annotation(getClass().getAnnotation(Annotation2.class)); - assertEquals("@com.querydsl.codegen.utils.Annotation2(\"Hello\")", w.toString().trim()); - } + @Test + public void ClassAnnotation() throws IOException { + writer.annotation(getClass().getAnnotation(Annotation.class)); + String option1 = + "@com.querydsl.codegen.utils.Annotation(clazz=com.querydsl.codegen.utils.AnnotationTest.class," + + " prop2=false)"; + String option2 = + "@com.querydsl.codegen.utils.Annotation(prop2=false," + + " clazz=com.querydsl.codegen.utils.AnnotationTest.class)"; + String serialized = w.toString().trim(); + assertTrue(serialized.equals(option1) || serialized.equals(option2)); + } - @Test - public void ClassAnnotation3() throws IOException { - writer.annotation(getClass().getAnnotation(Annotation3.class)); - assertEquals( - "@com.querydsl.codegen.utils.Annotation3(type=java.lang.annotation.ElementType.ANNOTATION_TYPE)", - w.toString().trim()); - } + @Test + public void ClassAnnotation2() throws IOException { + writer.annotation(getClass().getAnnotation(Annotation2.class)); + assertEquals("@com.querydsl.codegen.utils.Annotation2(\"Hello\")", w.toString().trim()); + } - @Test - public void MethodAnnotation() throws IOException, SecurityException, NoSuchMethodException { - writer.annotation(getClass().getMethod("MethodAnnotation").getAnnotation(Test.class)); - assertEquals("@org.junit.Test", w.toString().trim()); - } + @Test + public void ClassAnnotation3() throws IOException { + writer.annotation(getClass().getAnnotation(Annotation3.class)); + assertEquals( + "@com.querydsl.codegen.utils.Annotation3(type=java.lang.annotation.ElementType.ANNOTATION_TYPE)", + w.toString().trim()); + } - @Test - public void Min() throws IOException { - writer.annotation(new MinImpl(10)); - assertEquals("@javax.validation.constraints.Min(value=10)", w.toString().trim()); - } + @Test + public void MethodAnnotation() throws IOException, SecurityException, NoSuchMethodException { + writer.annotation(getClass().getMethod("MethodAnnotation").getAnnotation(Test.class)); + assertEquals("@org.junit.Test", w.toString().trim()); + } - @Test - public void Max() throws IOException { - writer.annotation(new MaxImpl(10)); - assertEquals("@javax.validation.constraints.Max(value=10)", w.toString().trim()); - } + @Test + public void Min() throws IOException { + writer.annotation(new MinImpl(10)); + assertEquals("@javax.validation.constraints.Min(value=10)", w.toString().trim()); + } - @Test - public void NotNull() throws IOException { - writer.annotation(new NotNullImpl()); - assertEquals("@javax.validation.constraints.NotNull", w.toString().trim()); - } + @Test + public void Max() throws IOException { + writer.annotation(new MaxImpl(10)); + assertEquals("@javax.validation.constraints.Max(value=10)", w.toString().trim()); + } - @Test - public void Uri_Value() throws IOException { - writer.annotation(new Annotation2Impl("http://www.example.com#")); - assertEquals("@com.querydsl.codegen.utils.Annotation2(\"http://www.example.com#\")", w.toString() - .trim()); - } + @Test + public void NotNull() throws IOException { + writer.annotation(new NotNullImpl()); + assertEquals("@javax.validation.constraints.NotNull", w.toString().trim()); + } + @Test + public void Uri_Value() throws IOException { + writer.annotation(new Annotation2Impl("http://www.example.com#")); + assertEquals( + "@com.querydsl.codegen.utils.Annotation2(\"http://www.example.com#\")", + w.toString().trim()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ComplexEvaluationTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ComplexEvaluationTest.java index 6fadc442d9..77550c0d48 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ComplexEvaluationTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ComplexEvaluationTest.java @@ -7,207 +7,248 @@ import static org.junit.Assert.*; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.codegen.utils.model.Types; -import org.junit.Test; - import com.querydsl.codegen.utils.support.Cat; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; public class ComplexEvaluationTest { - private EvaluatorFactory factory = new ECJEvaluatorFactory(getClass().getClassLoader()); - - @Test - @SuppressWarnings("unchecked") - public void Complex() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.STRING); - StringBuilder source = new StringBuilder(); - source.append("java.util.List rv = new java.util.ArrayList();\n"); - source.append("for (String a : a_){\n"); - source.append(" for (String b : b_){\n"); - source.append(" if (a.equals(b)){\n"); - source.append(" rv.add(a);\n"); - source.append(" }\n"); - source.append(" }\n"); - source.append("}\n"); - source.append("return rv;"); - - @SuppressWarnings("rawtypes") // cannot specify further than List.class - Evaluator evaluator = factory.createEvaluator(source.toString(), resultType, - new String[] { "a_", "b_" }, new Type[] { resultType, resultType }, new Class[] { - List.class, List.class }, Collections. emptyMap()); - - List a = Arrays.asList("1", "2", "3", "4"); - List b = Arrays.asList("2", "4", "6", "8"); - - assertEquals(Arrays.asList("2", "4"), evaluator.evaluate(a, b)); - } - - @Test - @SuppressWarnings("unchecked") - public void ComplexClassLoading() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.OBJECTS); - StringBuilder source = new StringBuilder(); - source.append("java.util.List rv = new java.util.ArrayList();\n"); - source.append("for (com.querydsl.codegen.utils.support.Cat cat : (java.util.List)cat_){\n"); - source.append("for (com.querydsl.codegen.utils.support.Cat otherCat : (java.util.List)otherCat_){\n"); - source.append("rv.add(new Object[]{cat,otherCat});\n"); - source.append("}\n"); - source.append("}\n"); - source.append("return rv;\n"); - - Cat fuzzy = new Cat("fuzzy"); - Cat spot = new Cat("spot"); - Cat mittens = new Cat("mittens"); - Cat sparkles = new Cat("sparkles"); - - List a = Arrays.asList(fuzzy, spot); - List b = Arrays.asList(mittens, sparkles); - - ClassType argType = new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class)); - @SuppressWarnings("rawtypes") // cannot specify further than List.class - Evaluator evaluator = factory.createEvaluator(source.toString(), resultType, - new String[] { "cat_", "otherCat_" }, new Type[] { argType, argType }, new Class[] { - List.class, List.class }, Collections. emptyMap()); - - Object[][] expResults = { {fuzzy, mittens}, {fuzzy, sparkles}, {spot, mittens}, {spot, sparkles} }; - List result = evaluator.evaluate(a, b); - assertEquals(expResults.length, result.size()); - - for (int i = 0; i < expResults.length; i++) { - assertEquals(expResults[i].length, result.get(i).length); - for (int j = 0; j < expResults[i].length; j++) { - assertEquals(expResults[i][j], result.get(i)[j]); - } - } - } - - @Test(expected = CodegenException.class) - @SuppressWarnings("unchecked") - public void ComplexClassLoadingFailure() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.STRING); - StringBuilder source = new StringBuilder(); - source.append("java.util.List rv = (java.util.List) new java.util.ArrayList();\n"); - source.append("for (String a : a_){\n"); - source.append(" for (String b : b_){\n"); - source.append(" if (a.equals(b)){\n"); - source.append(" rv.add(a);\n"); - source.append(" }\n"); - source.append(" }\n"); - source.append("}\n"); - source.append("return rv;"); - - @SuppressWarnings("rawtypes") // cannot specify further than List.class - Evaluator evaluator = factory.createEvaluator(source.toString(), resultType, - new String[] { "a_", "b_" }, new Type[] { resultType, resultType }, new Class[] { - List.class, List.class }, Collections. emptyMap()); - - List a = Arrays.asList("1", "2", "3", "4"); - List b = Arrays.asList("2", "4", "6", "8"); - - assertEquals(Arrays.asList("2", "4"), evaluator.evaluate(a, b)); - } - - @Test - @SuppressWarnings("unchecked") - public void ComplexPrimitiveType() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.BOOLEAN); - StringBuilder source = new StringBuilder(); - source.append("java.util.List rv = new java.util.ArrayList();\n"); - source.append("for (boolean a : a_){\n"); - source.append(" for (boolean b : b_){\n"); - source.append(" if (a == b){\n"); - source.append(" rv.add(a);\n"); - source.append(" }\n"); - source.append(" }\n"); - source.append("}\n"); - source.append("return rv;"); - - @SuppressWarnings("rawtypes") // cannot specify further than List.class - Evaluator evaluator = factory.createEvaluator(source.toString(), resultType, - new String[] { "a_", "b_" }, new Type[] { resultType, resultType }, new Class[] { - List.class, List.class }, Collections. emptyMap()); - - List a = Arrays.asList(true, true, true); - List b = Arrays.asList(false, false, true); - - assertEquals(Arrays.asList(true, true, true), evaluator.evaluate(a, b)); - } - - @Test - @SuppressWarnings("unchecked") - public void ComplexEmbeddedClass() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.BOOLEAN); - StringBuilder source = new StringBuilder(); - source.append("java.util.List rv = new java.util.ArrayList();\n"); - source.append("for (boolean a : a_){\n"); - source.append(" for (boolean b : b_){\n"); - source.append(" if (a == b && new TestEmbedded().DO_RETURN()){\n"); - source.append(" rv.add(a);\n"); - source.append(" }\n"); - source.append(" }\n"); - source.append("}\n"); - source.append("return rv;} private static class TestEmbedded { public TestEmbedded() {} public boolean DO_RETURN() { return true; } "); - - @SuppressWarnings("rawtypes") // cannot specify further than List.class - Evaluator evaluator = factory.createEvaluator(source.toString(), resultType, - new String[] { "a_", "b_" }, new Type[] { resultType, resultType }, new Class[] { - List.class, List.class }, Collections. emptyMap()); - - List a = Arrays.asList(true, true, true); - List b = Arrays.asList(false, false, true); - - assertEquals(Arrays.asList(true, true, true), evaluator.evaluate(a, b)); - } - - public static final class SuperCat extends Cat { - private SuperCat(String name) { - super(name); - } + private EvaluatorFactory factory = new ECJEvaluatorFactory(getClass().getClassLoader()); + + @Test + @SuppressWarnings("unchecked") + public void Complex() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.STRING); + StringBuilder source = new StringBuilder(); + source.append("java.util.List rv = new java.util.ArrayList();\n"); + source.append("for (String a : a_){\n"); + source.append(" for (String b : b_){\n"); + source.append(" if (a.equals(b)){\n"); + source.append(" rv.add(a);\n"); + source.append(" }\n"); + source.append(" }\n"); + source.append("}\n"); + source.append("return rv;"); + + @SuppressWarnings("rawtypes") // cannot specify further than List.class + Evaluator evaluator = + factory.createEvaluator( + source.toString(), + resultType, + new String[] {"a_", "b_"}, + new Type[] {resultType, resultType}, + new Class[] {List.class, List.class}, + Collections.emptyMap()); + + List a = Arrays.asList("1", "2", "3", "4"); + List b = Arrays.asList("2", "4", "6", "8"); + + assertEquals(Arrays.asList("2", "4"), evaluator.evaluate(a, b)); + } + + @Test + @SuppressWarnings("unchecked") + public void ComplexClassLoading() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.OBJECTS); + StringBuilder source = new StringBuilder(); + source.append("java.util.List rv = new java.util.ArrayList();\n"); + source.append( + "for (com.querydsl.codegen.utils.support.Cat cat :" + + " (java.util.List)cat_){\n"); + source.append( + "for (com.querydsl.codegen.utils.support.Cat otherCat :" + + " (java.util.List)otherCat_){\n"); + source.append("rv.add(new Object[]{cat,otherCat});\n"); + source.append("}\n"); + source.append("}\n"); + source.append("return rv;\n"); + + Cat fuzzy = new Cat("fuzzy"); + Cat spot = new Cat("spot"); + Cat mittens = new Cat("mittens"); + Cat sparkles = new Cat("sparkles"); + + List a = Arrays.asList(fuzzy, spot); + List b = Arrays.asList(mittens, sparkles); + + ClassType argType = new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class)); + @SuppressWarnings("rawtypes") // cannot specify further than List.class + Evaluator evaluator = + factory.createEvaluator( + source.toString(), + resultType, + new String[] {"cat_", "otherCat_"}, + new Type[] {argType, argType}, + new Class[] {List.class, List.class}, + Collections.emptyMap()); + + Object[][] expResults = { + {fuzzy, mittens}, {fuzzy, sparkles}, {spot, mittens}, {spot, sparkles} + }; + List result = evaluator.evaluate(a, b); + assertEquals(expResults.length, result.size()); + + for (int i = 0; i < expResults.length; i++) { + assertEquals(expResults[i].length, result.get(i).length); + for (int j = 0; j < expResults[i].length; j++) { + assertEquals(expResults[i][j], result.get(i)[j]); + } } - - @Test - public void ComplexDifferentConstants() { - ClassType resultType = new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class)); - String source = new StringBuilder() - .append("java.util.List rv = new java.util.ArrayList();\n") - .append("for (com.querydsl.codegen.utils.support.Cat cat : (java.util.List)cat_){\n") - .append("if (cat.equals(a1)) {\n") - .append("rv.add(cat);\n") - .append("}\n") - .append("}\n") - .append("return rv;\n") - .toString(); - - List cats = Arrays.asList(new Cat("fuzzy"), new Cat("spot")); - String[] names = new String[] { "cat_" }; - Type[] types = new Type[] { new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class)) }; - Class[] classes = new Class[] { List.class }; - - // first pass + } + + @Test(expected = CodegenException.class) + @SuppressWarnings("unchecked") + public void ComplexClassLoadingFailure() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.STRING); + StringBuilder source = new StringBuilder(); + source.append( + "java.util.List rv = (java.util.List) new" + + " java.util.ArrayList();\n"); + source.append("for (String a : a_){\n"); + source.append(" for (String b : b_){\n"); + source.append(" if (a.equals(b)){\n"); + source.append(" rv.add(a);\n"); + source.append(" }\n"); + source.append(" }\n"); + source.append("}\n"); + source.append("return rv;"); + + @SuppressWarnings("rawtypes") // cannot specify further than List.class + Evaluator evaluator = + factory.createEvaluator( + source.toString(), + resultType, + new String[] {"a_", "b_"}, + new Type[] {resultType, resultType}, + new Class[] {List.class, List.class}, + Collections.emptyMap()); + + List a = Arrays.asList("1", "2", "3", "4"); + List b = Arrays.asList("2", "4", "6", "8"); + + assertEquals(Arrays.asList("2", "4"), evaluator.evaluate(a, b)); + } + + @Test + @SuppressWarnings("unchecked") + public void ComplexPrimitiveType() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.BOOLEAN); + StringBuilder source = new StringBuilder(); + source.append("java.util.List rv = new java.util.ArrayList();\n"); + source.append("for (boolean a : a_){\n"); + source.append(" for (boolean b : b_){\n"); + source.append(" if (a == b){\n"); + source.append(" rv.add(a);\n"); + source.append(" }\n"); + source.append(" }\n"); + source.append("}\n"); + source.append("return rv;"); + + @SuppressWarnings("rawtypes") // cannot specify further than List.class + Evaluator evaluator = factory.createEvaluator( - source, - resultType, - names, - types, - classes, - Collections.singletonMap("a1", (Object) new SuperCat("superMittens")) - ).evaluate(cats); - - // second pass + source.toString(), + resultType, + new String[] {"a_", "b_"}, + new Type[] {resultType, resultType}, + new Class[] {List.class, List.class}, + Collections.emptyMap()); + + List a = Arrays.asList(true, true, true); + List b = Arrays.asList(false, false, true); + + assertEquals(Arrays.asList(true, true, true), evaluator.evaluate(a, b)); + } + + @Test + @SuppressWarnings("unchecked") + public void ComplexEmbeddedClass() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, Types.BOOLEAN); + StringBuilder source = new StringBuilder(); + source.append("java.util.List rv = new java.util.ArrayList();\n"); + source.append("for (boolean a : a_){\n"); + source.append(" for (boolean b : b_){\n"); + source.append(" if (a == b && new TestEmbedded().DO_RETURN()){\n"); + source.append(" rv.add(a);\n"); + source.append(" }\n"); + source.append(" }\n"); + source.append("}\n"); + source.append( + "return rv;} private static class TestEmbedded { public TestEmbedded() {} public boolean" + + " DO_RETURN() { return true; } "); + + @SuppressWarnings("rawtypes") // cannot specify further than List.class + Evaluator evaluator = factory.createEvaluator( - source, - resultType, - names, - types, - classes, - Collections.singletonMap("a1", (Object) new Cat("normalMittens")) - ).evaluate(cats); + source.toString(), + resultType, + new String[] {"a_", "b_"}, + new Type[] {resultType, resultType}, + new Class[] {List.class, List.class}, + Collections.emptyMap()); + + List a = Arrays.asList(true, true, true); + List b = Arrays.asList(false, false, true); + + assertEquals(Arrays.asList(true, true, true), evaluator.evaluate(a, b)); + } + + public static final class SuperCat extends Cat { + private SuperCat(String name) { + super(name); } + } + + @Test + public void ComplexDifferentConstants() { + ClassType resultType = new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class)); + String source = + new StringBuilder() + .append( + "java.util.List rv = new" + + " java.util.ArrayList();\n") + .append( + "for (com.querydsl.codegen.utils.support.Cat cat :" + + " (java.util.List)cat_){\n") + .append("if (cat.equals(a1)) {\n") + .append("rv.add(cat);\n") + .append("}\n") + .append("}\n") + .append("return rv;\n") + .toString(); + + List cats = Arrays.asList(new Cat("fuzzy"), new Cat("spot")); + String[] names = new String[] {"cat_"}; + Type[] types = + new Type[] {new ClassType(TypeCategory.LIST, List.class, new ClassType(Cat.class))}; + Class[] classes = new Class[] {List.class}; + + // first pass + factory + .createEvaluator( + source, + resultType, + names, + types, + classes, + Collections.singletonMap("a1", (Object) new SuperCat("superMittens"))) + .evaluate(cats); + + // second pass + factory + .createEvaluator( + source, + resultType, + names, + types, + classes, + Collections.singletonMap("a1", (Object) new Cat("normalMittens"))) + .evaluate(cats); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ECJEvaluatorFactoryTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ECJEvaluatorFactoryTest.java index 9d9c3633ed..2c6088e071 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ECJEvaluatorFactoryTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ECJEvaluatorFactoryTest.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. - * + * */ package com.querydsl.codegen.utils; @@ -13,111 +13,140 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ECJEvaluatorFactoryTest { - public static class TestEntity { - - private final String name; + public static class TestEntity { - public TestEntity(String name) { - this.name = name; - } - - public String getName() { - return name; - } + private final String name; + public TestEntity(String name) { + this.name = name; } - private EvaluatorFactory factory; - - private List names = Arrays.asList("a", "b"); - - private List> ints = Arrays.> asList(int.class, int.class); - - private List> strings = Arrays.> asList(String.class, String.class); - - private List> string_int = Arrays.> asList(String.class, int.class); - - @Before - public void setUp() throws IOException { - factory = new ECJEvaluatorFactory(getClass().getClassLoader()); + public String getName() { + return name; } + } - @Test - public void Simple() { - for (String expr : Arrays.asList("a.equals(b)", "a.startsWith(b)", "a.equalsIgnoreCase(b)")) { - long start = System.currentTimeMillis(); - evaluate(expr, boolean.class, names, strings, Arrays.asList("a", "b"), - Collections. emptyMap()); - long duration = System.currentTimeMillis() - start; - System.err.println(expr + " took " + duration + "ms\n"); - } - - for (String expr : Arrays.asList("a != b", "a < b", "a > b", "a <= b", "a >= b")) { - long start = System.currentTimeMillis(); - evaluate(expr, boolean.class, names, ints, Arrays.asList(0, 1), - Collections. emptyMap()); - long duration = System.currentTimeMillis() - start; - System.err.println(expr + " took " + duration + "ms\n"); - } - } + private EvaluatorFactory factory; - @Test - public void Results() { - // String + String - test("a + b", String.class, names, strings, Arrays.asList("Hello ", "World"), "Hello World"); + private List names = Arrays.asList("a", "b"); - // String + int - test("a.substring(b)", String.class, names, string_int, - Arrays. asList("Hello World", 6), "World"); + private List> ints = Arrays.>asList(int.class, int.class); - // int + int - test("a + b", int.class, names, ints, Arrays.asList(1, 2), 3); - } + private List> strings = Arrays.>asList(String.class, String.class); - @Test - public void WithConstants() { - Map constants = new HashMap(); - constants.put("x", "Hello World"); - List> types = Arrays.> asList(String.class); - List names = Arrays.asList("a"); - assertEquals( - Boolean.TRUE, - evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello World"), - constants)); - assertEquals( - Boolean.FALSE, - evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello"), - constants)); - } + private List> string_int = Arrays.>asList(String.class, int.class); - @Test - public void CustomType() { - test("a.getName()", String.class, Collections.singletonList("a"), - Collections.> singletonList(TestEntity.class), - Arrays.asList(new TestEntity("Hello World")), "Hello World"); - } + @Before + public void setUp() throws IOException { + factory = new ECJEvaluatorFactory(getClass().getClassLoader()); + } - private void test(String source, Class projectionType, List names, - List> types, List args, Object expectedResult) { - Assert.assertEquals( - expectedResult, - evaluate(source, projectionType, names, types, args, - Collections. emptyMap())); + @Test + public void Simple() { + for (String expr : Arrays.asList("a.equals(b)", "a.startsWith(b)", "a.equalsIgnoreCase(b)")) { + long start = System.currentTimeMillis(); + evaluate( + expr, + boolean.class, + names, + strings, + Arrays.asList("a", "b"), + Collections.emptyMap()); + long duration = System.currentTimeMillis() - start; + System.err.println(expr + " took " + duration + "ms\n"); } - private Object evaluate(String source, Class projectionType, List names, - List> types, List args, Map constants) { - Evaluator evaluator = factory.createEvaluator("return " + source + ";", projectionType, - names.toArray(new String[names.size()]), types.toArray(new Class[types.size()]), - constants); - return evaluator.evaluate(args.toArray()); + for (String expr : Arrays.asList("a != b", "a < b", "a > b", "a <= b", "a >= b")) { + long start = System.currentTimeMillis(); + evaluate( + expr, + boolean.class, + names, + ints, + Arrays.asList(0, 1), + Collections.emptyMap()); + long duration = System.currentTimeMillis() - start; + System.err.println(expr + " took " + duration + "ms\n"); } - + } + + @Test + public void Results() { + // String + String + test("a + b", String.class, names, strings, Arrays.asList("Hello ", "World"), "Hello World"); + + // String + int + test( + "a.substring(b)", + String.class, + names, + string_int, + Arrays.asList("Hello World", 6), + "World"); + + // int + int + test("a + b", int.class, names, ints, Arrays.asList(1, 2), 3); + } + + @Test + public void WithConstants() { + Map constants = new HashMap(); + constants.put("x", "Hello World"); + List> types = Arrays.>asList(String.class); + List names = Arrays.asList("a"); + assertEquals( + Boolean.TRUE, + evaluate( + "a.equals(x)", boolean.class, names, types, Arrays.asList("Hello World"), constants)); + assertEquals( + Boolean.FALSE, + evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello"), constants)); + } + + @Test + public void CustomType() { + test( + "a.getName()", + String.class, + Collections.singletonList("a"), + Collections.>singletonList(TestEntity.class), + Arrays.asList(new TestEntity("Hello World")), + "Hello World"); + } + + private void test( + String source, + Class projectionType, + List names, + List> types, + List args, + Object expectedResult) { + Assert.assertEquals( + expectedResult, + evaluate( + source, projectionType, names, types, args, Collections.emptyMap())); + } + + private Object evaluate( + String source, + Class projectionType, + List names, + List> types, + List args, + Map constants) { + Evaluator evaluator = + factory.createEvaluator( + "return " + source + ";", + projectionType, + names.toArray(new String[names.size()]), + types.toArray(new Class[types.size()]), + constants); + return evaluator.evaluate(args.toArray()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Entity.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Entity.java index 829a3f2ef2..835c1d0a5e 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Entity.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/Entity.java @@ -1,10 +1,8 @@ /* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. - * + * */ package com.querydsl.codegen.utils; -public @interface Entity { - -} +public @interface Entity {} diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/InnerClassesTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/InnerClassesTest.java index c58d44d045..76055312de 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/InnerClassesTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/InnerClassesTest.java @@ -2,51 +2,52 @@ import static org.junit.Assert.*; -import java.io.IOException; -import java.io.StringWriter; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.SimpleType; -import org.junit.Test; - import com.querydsl.codegen.utils.model.Type; +import java.io.IOException; +import java.io.StringWriter; +import org.junit.Test; public class InnerClassesTest { - public static class Entity { - - } - - @Test - public void DirectParameter() throws IOException { - Type entityType = new ClassType(Entity.class); - Type type = new SimpleType("com.querydsl.codegen.utils.gen.QEntity", "com.querydsl.codegen.utils.gen", - "QEntity", entityType); - - StringWriter str = new StringWriter(); - JavaWriter writer = new JavaWriter(str); - writer.beginClass(type); - writer.end(); - - System.err.println(str.toString()); - } - - @Test - public void Java() { - StringWriter str = new StringWriter(); - JavaWriter writer = new JavaWriter(str); - - assertEquals("com.querydsl.codegen.utils.InnerClassesTest.Entity", - writer.getRawName(new ClassType(Entity.class))); - } - - @Test - public void Scala() { - StringWriter str = new StringWriter(); - ScalaWriter writer = new ScalaWriter(str); - - assertEquals("com.querydsl.codegen.utils.InnerClassesTest$Entity", - writer.getRawName(new ClassType(Entity.class))); - } - + public static class Entity {} + + @Test + public void DirectParameter() throws IOException { + Type entityType = new ClassType(Entity.class); + Type type = + new SimpleType( + "com.querydsl.codegen.utils.gen.QEntity", + "com.querydsl.codegen.utils.gen", + "QEntity", + entityType); + + StringWriter str = new StringWriter(); + JavaWriter writer = new JavaWriter(str); + writer.beginClass(type); + writer.end(); + + System.err.println(str.toString()); + } + + @Test + public void Java() { + StringWriter str = new StringWriter(); + JavaWriter writer = new JavaWriter(str); + + assertEquals( + "com.querydsl.codegen.utils.InnerClassesTest.Entity", + writer.getRawName(new ClassType(Entity.class))); + } + + @Test + public void Scala() { + StringWriter str = new StringWriter(); + ScalaWriter writer = new ScalaWriter(str); + + assertEquals( + "com.querydsl.codegen.utils.InnerClassesTest$Entity", + writer.getRawName(new ClassType(Entity.class))); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JDKEvaluatorFactoryTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JDKEvaluatorFactoryTest.java index 3ddc1f3cd1..4b1fd6a0f4 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JDKEvaluatorFactoryTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JDKEvaluatorFactoryTest.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. - * + * */ package com.querydsl.codegen.utils; @@ -14,111 +14,140 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class JDKEvaluatorFactoryTest { - public static class TestEntity { - - private final String name; + public static class TestEntity { - public TestEntity(String name) { - this.name = name; - } - - public String getName() { - return name; - } + private final String name; + public TestEntity(String name) { + this.name = name; } - private EvaluatorFactory factory; - - private List names = Arrays.asList("a", "b"); - - private List> ints = Arrays.> asList(int.class, int.class); - - private List> strings = Arrays.> asList(String.class, String.class); - - private List> string_int = Arrays.> asList(String.class, int.class); - - @Before - public void setUp() throws IOException { - factory = new JDKEvaluatorFactory((URLClassLoader) getClass().getClassLoader()); + public String getName() { + return name; } + } - @Test - public void Simple() { - for (String expr : Arrays.asList("a.equals(b)", "a.startsWith(b)", "a.equalsIgnoreCase(b)")) { - long start = System.currentTimeMillis(); - evaluate(expr, boolean.class, names, strings, Arrays.asList("a", "b"), - Collections. emptyMap()); - long duration = System.currentTimeMillis() - start; - System.err.println(expr + " took " + duration + "ms\n"); - } - - for (String expr : Arrays.asList("a != b", "a < b", "a > b", "a <= b", "a >= b")) { - long start = System.currentTimeMillis(); - evaluate(expr, boolean.class, names, ints, Arrays.asList(0, 1), - Collections. emptyMap()); - long duration = System.currentTimeMillis() - start; - System.err.println(expr + " took " + duration + "ms\n"); - } - } + private EvaluatorFactory factory; - @Test - public void Results() { - // String + String - test("a + b", String.class, names, strings, Arrays.asList("Hello ", "World"), "Hello World"); + private List names = Arrays.asList("a", "b"); - // String + int - test("a.substring(b)", String.class, names, string_int, - Arrays. asList("Hello World", 6), "World"); + private List> ints = Arrays.>asList(int.class, int.class); - // int + int - test("a + b", int.class, names, ints, Arrays.asList(1, 2), 3); - } + private List> strings = Arrays.>asList(String.class, String.class); - @Test - public void WithConstants() { - Map constants = new HashMap(); - constants.put("x", "Hello World"); - List> types = Arrays.> asList(String.class); - List names = Arrays.asList("a"); - assertEquals( - Boolean.TRUE, - evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello World"), - constants)); - assertEquals( - Boolean.FALSE, - evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello"), - constants)); - } + private List> string_int = Arrays.>asList(String.class, int.class); - @Test - public void CustomType() { - test("a.getName()", String.class, Collections.singletonList("a"), - Collections.> singletonList(TestEntity.class), - Arrays.asList(new TestEntity("Hello World")), "Hello World"); - } + @Before + public void setUp() throws IOException { + factory = new JDKEvaluatorFactory((URLClassLoader) getClass().getClassLoader()); + } - private void test(String source, Class projectionType, List names, - List> types, List args, Object expectedResult) { - Assert.assertEquals( - expectedResult, - evaluate(source, projectionType, names, types, args, - Collections. emptyMap())); + @Test + public void Simple() { + for (String expr : Arrays.asList("a.equals(b)", "a.startsWith(b)", "a.equalsIgnoreCase(b)")) { + long start = System.currentTimeMillis(); + evaluate( + expr, + boolean.class, + names, + strings, + Arrays.asList("a", "b"), + Collections.emptyMap()); + long duration = System.currentTimeMillis() - start; + System.err.println(expr + " took " + duration + "ms\n"); } - private Object evaluate(String source, Class projectionType, List names, - List> types, List args, Map constants) { - Evaluator evaluator = factory.createEvaluator("return " + source + ";", projectionType, - names.toArray(new String[names.size()]), types.toArray(new Class[types.size()]), - constants); - return evaluator.evaluate(args.toArray()); + for (String expr : Arrays.asList("a != b", "a < b", "a > b", "a <= b", "a >= b")) { + long start = System.currentTimeMillis(); + evaluate( + expr, + boolean.class, + names, + ints, + Arrays.asList(0, 1), + Collections.emptyMap()); + long duration = System.currentTimeMillis() - start; + System.err.println(expr + " took " + duration + "ms\n"); } - + } + + @Test + public void Results() { + // String + String + test("a + b", String.class, names, strings, Arrays.asList("Hello ", "World"), "Hello World"); + + // String + int + test( + "a.substring(b)", + String.class, + names, + string_int, + Arrays.asList("Hello World", 6), + "World"); + + // int + int + test("a + b", int.class, names, ints, Arrays.asList(1, 2), 3); + } + + @Test + public void WithConstants() { + Map constants = new HashMap(); + constants.put("x", "Hello World"); + List> types = Arrays.>asList(String.class); + List names = Arrays.asList("a"); + assertEquals( + Boolean.TRUE, + evaluate( + "a.equals(x)", boolean.class, names, types, Arrays.asList("Hello World"), constants)); + assertEquals( + Boolean.FALSE, + evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello"), constants)); + } + + @Test + public void CustomType() { + test( + "a.getName()", + String.class, + Collections.singletonList("a"), + Collections.>singletonList(TestEntity.class), + Arrays.asList(new TestEntity("Hello World")), + "Hello World"); + } + + private void test( + String source, + Class projectionType, + List names, + List> types, + List args, + Object expectedResult) { + Assert.assertEquals( + expectedResult, + evaluate( + source, projectionType, names, types, args, Collections.emptyMap())); + } + + private Object evaluate( + String source, + Class projectionType, + List names, + List> types, + List args, + Map constants) { + Evaluator evaluator = + factory.createEvaluator( + "return " + source + ";", + projectionType, + names.toArray(new String[names.size()]), + types.toArray(new Class[types.size()]), + constants); + return evaluator.evaluate(args.toArray()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JavaWriterTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JavaWriterTest.java index 98f321e42f..c20590c9e6 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JavaWriterTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/JavaWriterTest.java @@ -8,6 +8,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.SimpleType; +import com.querydsl.codegen.utils.model.Type; +import com.querydsl.codegen.utils.model.TypeCategory; +import com.querydsl.codegen.utils.model.Types; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -20,336 +26,343 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.function.Function; - -import com.querydsl.codegen.utils.model.ClassType; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.SimpleType; -import com.querydsl.codegen.utils.model.Type; -import com.querydsl.codegen.utils.model.TypeCategory; -import com.querydsl.codegen.utils.model.Types; import org.junit.Before; import org.junit.Test; public class JavaWriterTest { - private static final Function transformer = new Function() { + private static final Function transformer = + new Function() { @Override public Parameter apply(Parameter input) { - return input; + return input; } - }; - - private StringWriter w; - - private CodeWriter writer; - - private Type testType, testType2, testSuperType, testInterface1, testInterface2; - - private static void match(String resource, String text) throws IOException { - // TODO : try to compile ? - final InputStream resourceAsStream = JavaWriterTest.class.getResourceAsStream(resource); - StringBuilder textBuilder = new StringBuilder(); - try (Reader reader = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))) { - int c = 0; - while ((c = reader.read()) != -1) { - textBuilder.append((char) c); - } - } - String expected = textBuilder.toString().replace("\r\n", System.lineSeparator()).trim(); - String actual = text.trim(); - assertEquals(expected, actual); - } - - @Before - public void setUp() { - w = new StringWriter(); - writer = new JavaWriter(w); - testType = new ClassType(JavaWriterTest.class); - testType2 = new SimpleType("com.querydsl.codegen.utils.Test", "com.querydsl.codegen.utils", "Test"); - testSuperType = new SimpleType("com.querydsl.codegen.utils.Superclass", "com.querydsl.codegen.utils", - "Superclass"); - testInterface1 = new SimpleType("com.querydsl.codegen.utils.TestInterface1", "com.querydsl.codegen.utils", - "TestInterface1"); - testInterface2 = new SimpleType("com.querydsl.codegen.utils.TestInterface2", "com.querydsl.codegen.utils", - "TestInterface2"); - } - - @Test - public void Arrays() throws IOException { - writer.beginClass(new SimpleType("Main")); - writer.field(Types.STRING.asArrayType(), "stringArray"); - writer.beginPublicMethod(Types.VOID, "main", - new Parameter("args", Types.STRING.asArrayType())); - writer.line("//"); - writer.end(); - writer.beginPublicMethod(Types.VOID, "main2", new Parameter("args", new ClassType( - TypeCategory.ARRAY, String[].class))); - writer.line("//"); - writer.end(); - writer.end(); - - System.out.println(w); - assertTrue(w.toString().contains("String[] stringArray;")); - assertTrue(w.toString().contains("public void main(String[] args) {")); - assertTrue(w.toString().contains("public void main2(String[] args) {")); - } - - @Test - public void Primitive_Arrays() { - ClassType byteArray = new ClassType(byte[].class); - assertEquals("byte[]", writer.getRawName(byteArray)); - } - - @Test - public void Basic() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.beginClass(testType); - writer.annotation(Test.class); - writer.beginPublicMethod(Types.VOID, "test"); - writer.line("// TODO"); - writer.end(); - writer.end(); - - match("/testBasic", w.toString()); - } - - @Test - public void Extends() throws IOException { - writer.beginClass(testType2, testSuperType); - writer.end(); - - match("/testExtends", w.toString()); - } - - @Test - public void Implements() throws IOException { - writer.beginClass(testType2, null, testInterface1, testInterface2); - writer.end(); - - match("/testImplements", w.toString()); - } + }; - @Test - public void Interface() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.beginInterface(testType); - writer.end(); + private StringWriter w; - match("/testInterface", w.toString()); - } + private CodeWriter writer; - @Test - public void Interface2() throws IOException { - writer.beginInterface(testType2, testInterface1); - writer.end(); + private Type testType, testType2, testSuperType, testInterface1, testInterface2; - match("/testInterface2", w.toString()); + private static void match(String resource, String text) throws IOException { + // TODO : try to compile ? + final InputStream resourceAsStream = JavaWriterTest.class.getResourceAsStream(resource); + StringBuilder textBuilder = new StringBuilder(); + try (Reader reader = + new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))) { + int c = 0; + while ((c = reader.read()) != -1) { + textBuilder.append((char) c); + } } - - @Test - public void Interface3() throws IOException { - writer.beginInterface(testType, testType2, testInterface1, testInterface2); - writer.end(); - - assertTrue(w.toString().contains( + String expected = textBuilder.toString().replace("\r\n", System.lineSeparator()).trim(); + String actual = text.trim(); + assertEquals(expected, actual); + } + + @Before + public void setUp() { + w = new StringWriter(); + writer = new JavaWriter(w); + testType = new ClassType(JavaWriterTest.class); + testType2 = + new SimpleType("com.querydsl.codegen.utils.Test", "com.querydsl.codegen.utils", "Test"); + testSuperType = + new SimpleType( + "com.querydsl.codegen.utils.Superclass", "com.querydsl.codegen.utils", "Superclass"); + testInterface1 = + new SimpleType( + "com.querydsl.codegen.utils.TestInterface1", + "com.querydsl.codegen.utils", + "TestInterface1"); + testInterface2 = + new SimpleType( + "com.querydsl.codegen.utils.TestInterface2", + "com.querydsl.codegen.utils", + "TestInterface2"); + } + + @Test + public void Arrays() throws IOException { + writer.beginClass(new SimpleType("Main")); + writer.field(Types.STRING.asArrayType(), "stringArray"); + writer.beginPublicMethod(Types.VOID, "main", new Parameter("args", Types.STRING.asArrayType())); + writer.line("//"); + writer.end(); + writer.beginPublicMethod( + Types.VOID, + "main2", + new Parameter("args", new ClassType(TypeCategory.ARRAY, String[].class))); + writer.line("//"); + writer.end(); + writer.end(); + + System.out.println(w); + assertTrue(w.toString().contains("String[] stringArray;")); + assertTrue(w.toString().contains("public void main(String[] args) {")); + assertTrue(w.toString().contains("public void main2(String[] args) {")); + } + + @Test + public void Primitive_Arrays() { + ClassType byteArray = new ClassType(byte[].class); + assertEquals("byte[]", writer.getRawName(byteArray)); + } + + @Test + public void Basic() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.beginClass(testType); + writer.annotation(Test.class); + writer.beginPublicMethod(Types.VOID, "test"); + writer.line("// TODO"); + writer.end(); + writer.end(); + + match("/testBasic", w.toString()); + } + + @Test + public void Extends() throws IOException { + writer.beginClass(testType2, testSuperType); + writer.end(); + + match("/testExtends", w.toString()); + } + + @Test + public void Implements() throws IOException { + writer.beginClass(testType2, null, testInterface1, testInterface2); + writer.end(); + + match("/testImplements", w.toString()); + } + + @Test + public void Interface() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.beginInterface(testType); + writer.end(); + + match("/testInterface", w.toString()); + } + + @Test + public void Interface2() throws IOException { + writer.beginInterface(testType2, testInterface1); + writer.end(); + + match("/testInterface2", w.toString()); + } + + @Test + public void Interface3() throws IOException { + writer.beginInterface(testType, testType2, testInterface1, testInterface2); + writer.end(); + + assertTrue( + w.toString() + .contains( "public interface JavaWriterTest extends Test, TestInterface1, TestInterface2 {")); - } - - @Test - public void Javadoc() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.javadoc("JavaWriterTest is a test class"); - writer.beginClass(testType); - writer.end(); - - match("/testJavadoc", w.toString()); - } - - @Test - public void Annotations() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class); - writer.annotation(Entity.class); - writer.beginClass(testType); - writer.annotation(Test.class); - writer.beginPublicMethod(Types.VOID, "test"); - writer.end(); - writer.end(); - - match("/testAnnotations", w.toString()); - } - - @Test - public void Annotations2() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class.getPackage(), StringWriter.class.getPackage()); - writer.annotation(Entity.class); - writer.beginClass(testType); - writer.annotation(new Test() { - @Override - public Class expected() { - // TODO Auto-generated method stub - return null; - } - - @Override - public long timeout() { - - return 0; - } - - @Override - public Class annotationType() { - return Test.class; - } + } + + @Test + public void Javadoc() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.javadoc("JavaWriterTest is a test class"); + writer.beginClass(testType); + writer.end(); + + match("/testJavadoc", w.toString()); + } + + @Test + public void Annotations() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class); + writer.annotation(Entity.class); + writer.beginClass(testType); + writer.annotation(Test.class); + writer.beginPublicMethod(Types.VOID, "test"); + writer.end(); + writer.end(); + + match("/testAnnotations", w.toString()); + } + + @Test + public void Annotations2() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class.getPackage(), StringWriter.class.getPackage()); + writer.annotation(Entity.class); + writer.beginClass(testType); + writer.annotation( + new Test() { + @Override + public Class expected() { + // TODO Auto-generated method stub + return null; + } + + @Override + public long timeout() { + + return 0; + } + + @Override + public Class annotationType() { + return Test.class; + } }); - writer.beginPublicMethod(Types.VOID, "test"); - writer.end(); - writer.end(); - - match("/testAnnotations2", w.toString()); - } - - @Test - public void Annotation_With_ArrayMethod() throws IOException { - Target annotation = new Target() { - @Override - public ElementType[] value() { - return new ElementType[] { ElementType.FIELD, ElementType.METHOD }; - } - - @Override - public Class annotationType() { - return Target.class; - } + writer.beginPublicMethod(Types.VOID, "test"); + writer.end(); + writer.end(); + + match("/testAnnotations2", w.toString()); + } + + @Test + public void Annotation_With_ArrayMethod() throws IOException { + Target annotation = + new Target() { + @Override + public ElementType[] value() { + return new ElementType[] {ElementType.FIELD, ElementType.METHOD}; + } + + @Override + public Class annotationType() { + return Target.class; + } }; - writer.imports(Target.class.getPackage()); - writer.annotation(annotation); - assertTrue(w.toString().contains("@Target({FIELD, METHOD})")); - } + writer.imports(Target.class.getPackage()); + writer.annotation(annotation); + assertTrue(w.toString().contains("@Target({FIELD, METHOD})")); + } - @Test - public void ClassConstants() { - assertEquals("SomeClass.class", writer.getClassConstant("SomeClass")); - } + @Test + public void ClassConstants() { + assertEquals("SomeClass.class", writer.getClassConstant("SomeClass")); + } - @Test - public void Fields() throws IOException { - writer.beginClass(testType); - // private - writer.privateField(Types.STRING, "privateField"); - writer.privateStaticFinal(Types.STRING, "privateStaticFinal", "\"val\""); - // protected - writer.protectedField(Types.STRING, "protectedField"); - // field - writer.field(Types.STRING, "field"); - // public - writer.publicField(Types.STRING, "publicField"); - writer.publicStaticFinal(Types.STRING, "publicStaticFinal", "\"val\""); - writer.publicFinal(Types.STRING, "publicFinalField"); - writer.publicFinal(Types.STRING, "publicFinalField2", "\"val\""); - - writer.end(); - - match("/testFields", w.toString()); - } + @Test + public void Fields() throws IOException { + writer.beginClass(testType); + // private + writer.privateField(Types.STRING, "privateField"); + writer.privateStaticFinal(Types.STRING, "privateStaticFinal", "\"val\""); + // protected + writer.protectedField(Types.STRING, "protectedField"); + // field + writer.field(Types.STRING, "field"); + // public + writer.publicField(Types.STRING, "publicField"); + writer.publicStaticFinal(Types.STRING, "publicStaticFinal", "\"val\""); + writer.publicFinal(Types.STRING, "publicFinalField"); + writer.publicFinal(Types.STRING, "publicFinalField2", "\"val\""); - @Test - public void Methods() throws IOException { - writer.beginClass(testType); - // private + writer.end(); - // protected + match("/testFields", w.toString()); + } - // method + @Test + public void Methods() throws IOException { + writer.beginClass(testType); + // private - // public - writer.beginPublicMethod(Types.STRING, "publicMethod", - Arrays.asList(new Parameter("a", Types.STRING)), transformer); - writer.line("return null;"); - writer.end(); + // protected - writer.beginStaticMethod(Types.STRING, "staticMethod", - Arrays.asList(new Parameter("a", Types.STRING)), transformer); - writer.line("return null;"); - writer.end(); + // method - writer.end(); + // public + writer.beginPublicMethod( + Types.STRING, "publicMethod", Arrays.asList(new Parameter("a", Types.STRING)), transformer); + writer.line("return null;"); + writer.end(); - match("/testMethods", w.toString()); - } + writer.beginStaticMethod( + Types.STRING, "staticMethod", Arrays.asList(new Parameter("a", Types.STRING)), transformer); + writer.line("return null;"); + writer.end(); - @Test - public void Constructors() throws IOException { - writer.beginClass(testType); + writer.end(); - writer.beginConstructor( - Arrays.asList(new Parameter("a", Types.STRING), new Parameter("b", Types.STRING)), - transformer); - writer.end(); + match("/testMethods", w.toString()); + } - writer.beginConstructor(new Parameter("a", Types.STRING)); - writer.end(); + @Test + public void Constructors() throws IOException { + writer.beginClass(testType); - writer.end(); + writer.beginConstructor( + Arrays.asList(new Parameter("a", Types.STRING), new Parameter("b", Types.STRING)), + transformer); + writer.end(); - match("/testConstructors", w.toString()); + writer.beginConstructor(new Parameter("a", Types.STRING)); + writer.end(); - } + writer.end(); - @Test - public void Inner_Classes() throws IOException { - writer.beginClass(testType); + match("/testConstructors", w.toString()); + } - writer.beginClass(testType2); - writer.end(); + @Test + public void Inner_Classes() throws IOException { + writer.beginClass(testType); - writer.beginConstructor(new Parameter("a", Types.STRING)); - writer.end(); + writer.beginClass(testType2); + writer.end(); - writer.end(); + writer.beginConstructor(new Parameter("a", Types.STRING)); + writer.end(); - match("/testInnerClasses", w.toString()); - } + writer.end(); - @Test - public void Imports() throws IOException { - writer.staticimports(Arrays.class); + match("/testInnerClasses", w.toString()); + } - match("/testImports", w.toString()); - } + @Test + public void Imports() throws IOException { + writer.staticimports(Arrays.class); - @Test - public void Imports2() throws IOException { - writer.importPackages("java.lang.reflect", "java.util"); + match("/testImports", w.toString()); + } - match("/testImports2", w.toString()); - } + @Test + public void Imports2() throws IOException { + writer.importPackages("java.lang.reflect", "java.util"); - @Test - public void Imports3() throws IOException { - writer.importClasses("java.util.Locale"); + match("/testImports2", w.toString()); + } - assertTrue(w.toString().contains("import java.util.Locale;")); - } + @Test + public void Imports3() throws IOException { + writer.importClasses("java.util.Locale"); - @Test - public void SuppressWarnings() throws IOException { - writer.suppressWarnings("unused"); - writer.privateField(Types.STRING, "test"); + assertTrue(w.toString().contains("import java.util.Locale;")); + } - match("/testSuppressWarnings", w.toString()); - } + @Test + public void SuppressWarnings() throws IOException { + writer.suppressWarnings("unused"); + writer.privateField(Types.STRING, "test"); - @Test - public void SuppressWarnings2() throws IOException { - writer.suppressWarnings("all", "unused"); - writer.privateField(Types.STRING, "test"); + match("/testSuppressWarnings", w.toString()); + } - match("/testSuppressWarnings2", w.toString()); - } + @Test + public void SuppressWarnings2() throws IOException { + writer.suppressWarnings("all", "unused"); + writer.privateField(Types.STRING, "test"); + + match("/testSuppressWarnings2", w.toString()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MaxImpl.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MaxImpl.java index fbfcb2fe72..7346181b14 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MaxImpl.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MaxImpl.java @@ -1,46 +1,43 @@ package com.querydsl.codegen.utils; import java.lang.annotation.Annotation; - import javax.validation.Payload; import javax.validation.constraints.*; /** * @author tiwe - * */ @SuppressWarnings("all") public class MaxImpl implements Max { - private final long value; - - public MaxImpl(long value) { - this.value = value; - } + private final long value; - @Override - public Class[] groups() { - return new Class[0]; - } + public MaxImpl(long value) { + this.value = value; + } - @Override - public String message() { - return "{javax.validation.constraints.Max.message}"; - } + @Override + public Class[] groups() { + return new Class[0]; + } - @Override - public Class[] payload() { - return new Class[0]; - } + @Override + public String message() { + return "{javax.validation.constraints.Max.message}"; + } - @Override - public long value() { - return value; - } + @Override + public Class[] payload() { + return new Class[0]; + } - @Override - public Class annotationType() { - return Max.class; - } + @Override + public long value() { + return value; + } + @Override + public Class annotationType() { + return Max.class; + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemJavaFileObjectTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemJavaFileObjectTest.java index afa63c4a62..a84b72bc35 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemJavaFileObjectTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemJavaFileObjectTest.java @@ -9,28 +9,25 @@ import java.io.IOException; import java.io.Writer; - import javax.tools.JavaFileObject.Kind; - import org.junit.Test; public class MemJavaFileObjectTest { - @Test - public void getCharContent() throws IOException { - MemJavaFileObject obj = new MemJavaFileObject("mem", "Test", Kind.SOURCE); - Writer writer = obj.openWriter(); - writer.write("Hello World"); - writer.flush(); - writer.close(); - assertEquals("Hello World", obj.getCharContent(true).toString()); - } - - @Test - public void openInputStream() throws IOException { - MemJavaFileObject obj = new MemJavaFileObject("mem", "Test", Kind.SOURCE); - obj.openWriter().write("test"); - obj.openInputStream().close(); - } - + @Test + public void getCharContent() throws IOException { + MemJavaFileObject obj = new MemJavaFileObject("mem", "Test", Kind.SOURCE); + Writer writer = obj.openWriter(); + writer.write("Hello World"); + writer.flush(); + writer.close(); + assertEquals("Hello World", obj.getCharContent(true).toString()); + } + + @Test + public void openInputStream() throws IOException { + MemJavaFileObject obj = new MemJavaFileObject("mem", "Test", Kind.SOURCE); + obj.openWriter().write("test"); + obj.openInputStream().close(); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemSourceFileObjectTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemSourceFileObjectTest.java index f7feb6adad..0641ca74f8 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemSourceFileObjectTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MemSourceFileObjectTest.java @@ -8,29 +8,27 @@ import static org.junit.Assert.*; import java.io.IOException; - import org.junit.Test; public class MemSourceFileObjectTest { - @Test - public void Simple() { - MemSourceFileObject obj = new MemSourceFileObject("Test", "Hello World"); - assertEquals("Hello World", obj.getCharContent(true).toString()); - } - - @Test - public void OpenWriter() throws IOException { - MemSourceFileObject obj = new MemSourceFileObject("Test"); - obj.openWriter().write("Hello World"); - assertEquals("Hello World", obj.getCharContent(true).toString()); - } - - @Test - public void OpenWriter2() throws IOException { - MemSourceFileObject obj = new MemSourceFileObject("Test"); - obj.openWriter().append("Hello World"); - assertEquals("Hello World", obj.getCharContent(true).toString()); - } - + @Test + public void Simple() { + MemSourceFileObject obj = new MemSourceFileObject("Test", "Hello World"); + assertEquals("Hello World", obj.getCharContent(true).toString()); + } + + @Test + public void OpenWriter() throws IOException { + MemSourceFileObject obj = new MemSourceFileObject("Test"); + obj.openWriter().write("Hello World"); + assertEquals("Hello World", obj.getCharContent(true).toString()); + } + + @Test + public void OpenWriter2() throws IOException { + MemSourceFileObject obj = new MemSourceFileObject("Test"); + obj.openWriter().append("Hello World"); + assertEquals("Hello World", obj.getCharContent(true).toString()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MinImpl.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MinImpl.java index 5375790685..e33e9253bd 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MinImpl.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/MinImpl.java @@ -1,46 +1,43 @@ package com.querydsl.codegen.utils; import java.lang.annotation.Annotation; - import javax.validation.Payload; import javax.validation.constraints.*; /** * @author tiwe - * */ @SuppressWarnings("all") public class MinImpl implements Min { - private final long value; - - public MinImpl(long value) { - this.value = value; - } + private final long value; - @Override - public Class[] groups() { - return new Class[0]; - } + public MinImpl(long value) { + this.value = value; + } - @Override - public String message() { - return "{javax.validation.constraints.Min.message}"; - } + @Override + public Class[] groups() { + return new Class[0]; + } - @Override - public Class[] payload() { - return new Class[0]; - } + @Override + public String message() { + return "{javax.validation.constraints.Min.message}"; + } - @Override - public long value() { - return value; - } + @Override + public Class[] payload() { + return new Class[0]; + } - @Override - public Class annotationType() { - return Min.class; - } + @Override + public long value() { + return value; + } + @Override + public Class annotationType() { + return Min.class; + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/NotNullImpl.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/NotNullImpl.java index 6e3bf29527..2ecea73392 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/NotNullImpl.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/NotNullImpl.java @@ -1,35 +1,32 @@ package com.querydsl.codegen.utils; import java.lang.annotation.Annotation; - import javax.validation.Payload; import javax.validation.constraints.*; /** * @author tiwe - * */ @SuppressWarnings("all") public class NotNullImpl implements NotNull { - @Override - public Class[] groups() { - return new Class[0]; - } - - @Override - public Class[] payload() { - return new Class[0]; - } - - @Override - public String message() { - return "{javax.validation.constraints.NotNull.message}"; - } - - @Override - public Class annotationType() { - return NotNull.class; - } - + @Override + public Class[] groups() { + return new Class[0]; + } + + @Override + public Class[] payload() { + return new Class[0]; + } + + @Override + public String message() { + return "{javax.validation.constraints.NotNull.message}"; + } + + @Override + public Class annotationType() { + return NotNull.class; + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ScalaWriterTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ScalaWriterTest.java index f0ccf847d5..87f7cd541e 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ScalaWriterTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/ScalaWriterTest.java @@ -3,6 +3,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.SimpleType; +import com.querydsl.codegen.utils.model.Type; +import com.querydsl.codegen.utils.model.TypeCategory; +import com.querydsl.codegen.utils.model.Types; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; @@ -12,413 +18,419 @@ import java.util.Arrays; import java.util.List; import java.util.function.Function; - import javax.validation.constraints.Max; - -import com.querydsl.codegen.utils.model.ClassType; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.SimpleType; -import com.querydsl.codegen.utils.model.Type; -import com.querydsl.codegen.utils.model.TypeCategory; -import com.querydsl.codegen.utils.model.Types; import org.junit.Before; import org.junit.Test; public class ScalaWriterTest { - private static final Function transformer = new Function() { + private static final Function transformer = + new Function() { @Override public Parameter apply(Parameter input) { - return input; + return input; } - }; - - private final Writer w = new StringWriter(); - - private final ScalaWriter writer = new ScalaWriter(w, true); - - private Type testType, testType2, testSuperType, testInterface1, testInterface2; - - @Before - public void setUp() { - testType = new ClassType(JavaWriterTest.class); - testType2 = new SimpleType("com.querydsl.codegen.utils.Test", "com.querydsl.codegen.utils", "Test"); - testSuperType = new SimpleType("com.querydsl.codegen.utils.Superclass", "com.querydsl.codegen.utils", - "Superclass"); - testInterface1 = new SimpleType("com.querydsl.codegen.utils.TestInterface1", "com.querydsl.codegen.utils", - "TestInterface1"); - testInterface2 = new SimpleType("com.querydsl.codegen.utils.TestInterface2", "com.querydsl.codegen.utils", - "TestInterface2"); - } - - @Test - public void Object() throws IOException { - writer.beginObject("Test"); - writer.end(); - assertTrue(w.toString().contains("object Test {")); - } - - @Test - public void Class_With_Interfaces() throws IOException { - writer.beginClass(testType, testType2, testInterface1); - assertTrue(w.toString().contains("class JavaWriterTest extends Test with TestInterface1 {")); - } - - @Test - public void Interface_With_Superinterfaces() throws IOException { - writer.beginInterface(testType, testType2, testInterface1); - assertTrue(w.toString().contains("trait JavaWriterTest extends Test with TestInterface1 {")); - } - - @Test - public void CustomHeader() throws IOException { - // class QDepartment(path: String) extends - // RelationalPathBase[QDepartment](classOf[QDepartment], path){ - // val id = createNumber("ID", classOf[Integer]); - // val company = createNumber("COMPANY", classOf[Integer]); - // val idKey = createPrimaryKey(id); - // val companyKey: ForeignKey[QCompany] = createForeignKey(company, - // "ID"); - // } - writer.beginClass("QDepartment(path: String) extends RelationalPathBase[QDepartment](classOf[QDepartment], path)"); - writer.publicFinal(Types.OBJECT, "id", "createNumber(\"ID\", classOf[Integer])"); - writer.publicFinal(Types.OBJECT, "company", "createNumber(\"COMPANY\", classOf[Integer])"); - writer.publicFinal(Types.OBJECT, "idKey", "createPrimaryKey(id)"); - writer.publicFinal(Types.OBJECT, "companyKey", "createForeignKey(company,\"ID\")"); - writer.end(); - - System.out.println(w); - } - - @Test - public void BeanAccessors() throws IOException { - writer.beginClass(new SimpleType("Person")); - writer.beginPublicMethod(Types.STRING, "getName"); - writer.line("\"Daniel Spiewak\""); - writer.end(); - writer.beginPublicMethod(Types.VOID, "setName", new Parameter("name", Types.STRING)); - writer.line("//"); - writer.end(); - writer.end(); - - System.out.println(w); - } - - @Test - public void Arrays() throws IOException { - // def main(args: Array[String]) { - writer.beginClass(new SimpleType("Main")); - writer.field(Types.STRING.asArrayType(), "stringArray"); - writer.beginPublicMethod(Types.VOID, "main", - new Parameter("args", Types.STRING.asArrayType())); - writer.line("//"); - writer.end(); - writer.beginPublicMethod(Types.VOID, "main2", new Parameter("args", new ClassType( - TypeCategory.ARRAY, String[].class))); - writer.line("//"); - writer.end(); - writer.end(); - - System.out.println(w); - assertTrue(w.toString().contains("var stringArray: Array[String]")); - assertTrue(w.toString().contains("def main(args: Array[String])")); - assertTrue(w.toString().contains("def main2(args: Array[String])")); - } - - @Test - public void Arrays2() throws IOException { - writer.field(Types.BYTE_P.asArrayType(), "byteArray"); - - System.out.println(w); - assertTrue(w.toString().contains("var byteArray: Array[Byte]")); - } - - @Test - public void Trait() throws IOException { - // trait MyTrait - writer.beginInterface(new SimpleType("MyTrait")); - writer.line("//"); - writer.end(); - - System.out.println(w); - assertTrue(w.toString().contains("trait MyTrait")); - } - - @Test - public void Field() throws IOException { - // private val people: List[Person] - writer.imports(List.class); - writer.beginClass(new SimpleType("Main")); - writer.privateFinal(new SimpleType(Types.LIST, new SimpleType("Person")), "people"); - writer.end(); - - System.out.println(w); - assertTrue(w.toString().contains("private val people: List[Person]")); - } - - @Test - public void Basic() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.beginClass(testType); - writer.annotation(Test.class); - writer.beginPublicMethod(Types.VOID, "test"); - writer.line("// TODO"); - writer.end(); - writer.end(); - - System.out.println(w); - } - - @Test - public void Extends() throws IOException { - writer.beginClass(testType2, testSuperType); - writer.end(); - - System.out.println(w); - } - - @Test - public void Implements() throws IOException { - writer.beginClass(testType2, null, testInterface1, testInterface2); - writer.end(); - - System.out.println(w); - } - - @Test - public void Interface() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.beginInterface(testType); - writer.end(); - - System.out.println(w); - } - - @Test - public void Interface2() throws IOException { - writer.beginInterface(testType2, testInterface1); - writer.end(); - - System.out.println(w); - } - - @Test - public void Javadoc() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class, Test.class); - writer.javadoc("JavaWriterTest is a test class"); - writer.beginClass(testType); - writer.end(); - - System.out.println(w); - } - - @Test - public void AnnotationConstant() throws IOException { - Max annotation = new MaxImpl(0L) { - @Override - public Class[] groups() { - return new Class[] { Object.class, String.class, int.class }; - } + }; + + private final Writer w = new StringWriter(); + + private final ScalaWriter writer = new ScalaWriter(w, true); + + private Type testType, testType2, testSuperType, testInterface1, testInterface2; + + @Before + public void setUp() { + testType = new ClassType(JavaWriterTest.class); + testType2 = + new SimpleType("com.querydsl.codegen.utils.Test", "com.querydsl.codegen.utils", "Test"); + testSuperType = + new SimpleType( + "com.querydsl.codegen.utils.Superclass", "com.querydsl.codegen.utils", "Superclass"); + testInterface1 = + new SimpleType( + "com.querydsl.codegen.utils.TestInterface1", + "com.querydsl.codegen.utils", + "TestInterface1"); + testInterface2 = + new SimpleType( + "com.querydsl.codegen.utils.TestInterface2", + "com.querydsl.codegen.utils", + "TestInterface2"); + } + + @Test + public void Object() throws IOException { + writer.beginObject("Test"); + writer.end(); + assertTrue(w.toString().contains("object Test {")); + } + + @Test + public void Class_With_Interfaces() throws IOException { + writer.beginClass(testType, testType2, testInterface1); + assertTrue(w.toString().contains("class JavaWriterTest extends Test with TestInterface1 {")); + } + + @Test + public void Interface_With_Superinterfaces() throws IOException { + writer.beginInterface(testType, testType2, testInterface1); + assertTrue(w.toString().contains("trait JavaWriterTest extends Test with TestInterface1 {")); + } + + @Test + public void CustomHeader() throws IOException { + // class QDepartment(path: String) extends + // RelationalPathBase[QDepartment](classOf[QDepartment], path){ + // val id = createNumber("ID", classOf[Integer]); + // val company = createNumber("COMPANY", classOf[Integer]); + // val idKey = createPrimaryKey(id); + // val companyKey: ForeignKey[QCompany] = createForeignKey(company, + // "ID"); + // } + writer.beginClass( + "QDepartment(path: String) extends RelationalPathBase[QDepartment](classOf[QDepartment]," + + " path)"); + writer.publicFinal(Types.OBJECT, "id", "createNumber(\"ID\", classOf[Integer])"); + writer.publicFinal(Types.OBJECT, "company", "createNumber(\"COMPANY\", classOf[Integer])"); + writer.publicFinal(Types.OBJECT, "idKey", "createPrimaryKey(id)"); + writer.publicFinal(Types.OBJECT, "companyKey", "createForeignKey(company,\"ID\")"); + writer.end(); + + System.out.println(w); + } + + @Test + public void BeanAccessors() throws IOException { + writer.beginClass(new SimpleType("Person")); + writer.beginPublicMethod(Types.STRING, "getName"); + writer.line("\"Daniel Spiewak\""); + writer.end(); + writer.beginPublicMethod(Types.VOID, "setName", new Parameter("name", Types.STRING)); + writer.line("//"); + writer.end(); + writer.end(); + + System.out.println(w); + } + + @Test + public void Arrays() throws IOException { + // def main(args: Array[String]) { + writer.beginClass(new SimpleType("Main")); + writer.field(Types.STRING.asArrayType(), "stringArray"); + writer.beginPublicMethod(Types.VOID, "main", new Parameter("args", Types.STRING.asArrayType())); + writer.line("//"); + writer.end(); + writer.beginPublicMethod( + Types.VOID, + "main2", + new Parameter("args", new ClassType(TypeCategory.ARRAY, String[].class))); + writer.line("//"); + writer.end(); + writer.end(); + + System.out.println(w); + assertTrue(w.toString().contains("var stringArray: Array[String]")); + assertTrue(w.toString().contains("def main(args: Array[String])")); + assertTrue(w.toString().contains("def main2(args: Array[String])")); + } + + @Test + public void Arrays2() throws IOException { + writer.field(Types.BYTE_P.asArrayType(), "byteArray"); + + System.out.println(w); + assertTrue(w.toString().contains("var byteArray: Array[Byte]")); + } + + @Test + public void Trait() throws IOException { + // trait MyTrait + writer.beginInterface(new SimpleType("MyTrait")); + writer.line("//"); + writer.end(); + + System.out.println(w); + assertTrue(w.toString().contains("trait MyTrait")); + } + + @Test + public void Field() throws IOException { + // private val people: List[Person] + writer.imports(List.class); + writer.beginClass(new SimpleType("Main")); + writer.privateFinal(new SimpleType(Types.LIST, new SimpleType("Person")), "people"); + writer.end(); + + System.out.println(w); + assertTrue(w.toString().contains("private val people: List[Person]")); + } + + @Test + public void Basic() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.beginClass(testType); + writer.annotation(Test.class); + writer.beginPublicMethod(Types.VOID, "test"); + writer.line("// TODO"); + writer.end(); + writer.end(); + + System.out.println(w); + } + + @Test + public void Extends() throws IOException { + writer.beginClass(testType2, testSuperType); + writer.end(); + + System.out.println(w); + } + + @Test + public void Implements() throws IOException { + writer.beginClass(testType2, null, testInterface1, testInterface2); + writer.end(); + + System.out.println(w); + } + + @Test + public void Interface() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.beginInterface(testType); + writer.end(); + + System.out.println(w); + } + + @Test + public void Interface2() throws IOException { + writer.beginInterface(testType2, testInterface1); + writer.end(); + + System.out.println(w); + } + + @Test + public void Javadoc() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class, Test.class); + writer.javadoc("JavaWriterTest is a test class"); + writer.beginClass(testType); + writer.end(); + + System.out.println(w); + } + + @Test + public void AnnotationConstant() throws IOException { + Max annotation = + new MaxImpl(0L) { + @Override + public Class[] groups() { + return new Class[] {Object.class, String.class, int.class}; + } }; - writer.annotation(annotation); - - System.out.println(w); - } - - @Test - public void Annotation_With_ArrayMethod() throws IOException { - Target annotation = new Target() { - @Override - public ElementType[] value() { - return new ElementType[] { ElementType.FIELD, ElementType.METHOD }; - } - - @Override - public Class annotationType() { - return Target.class; - } + writer.annotation(annotation); + + System.out.println(w); + } + + @Test + public void Annotation_With_ArrayMethod() throws IOException { + Target annotation = + new Target() { + @Override + public ElementType[] value() { + return new ElementType[] {ElementType.FIELD, ElementType.METHOD}; + } + + @Override + public Class annotationType() { + return Target.class; + } }; - writer.imports(Target.class.getPackage()); - writer.annotation(annotation); - assertTrue(w.toString().contains("@Target(Array(FIELD, METHOD))")); - } - - @Test - public void Annotations() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class, StringWriter.class); - writer.annotation(Entity.class); - writer.beginClass(testType); - writer.annotation(Test.class); - writer.beginPublicMethod(Types.VOID, "test"); - writer.end(); - writer.end(); - - System.out.println(w); - } - - @Test - public void Annotations2() throws IOException { - writer.packageDecl("com.querydsl.codegen.utils"); - writer.imports(IOException.class.getPackage(), StringWriter.class.getPackage()); - writer.annotation(Entity.class); - writer.beginClass(testType); - writer.annotation(new Test() { - @Override - public Class expected() { - // TODO Auto-generated method stub - return null; - } - - @Override - public long timeout() { - - return 0; - } - - @Override - public Class annotationType() { - return Test.class; - } + writer.imports(Target.class.getPackage()); + writer.annotation(annotation); + assertTrue(w.toString().contains("@Target(Array(FIELD, METHOD))")); + } + + @Test + public void Annotations() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class, StringWriter.class); + writer.annotation(Entity.class); + writer.beginClass(testType); + writer.annotation(Test.class); + writer.beginPublicMethod(Types.VOID, "test"); + writer.end(); + writer.end(); + + System.out.println(w); + } + + @Test + public void Annotations2() throws IOException { + writer.packageDecl("com.querydsl.codegen.utils"); + writer.imports(IOException.class.getPackage(), StringWriter.class.getPackage()); + writer.annotation(Entity.class); + writer.beginClass(testType); + writer.annotation( + new Test() { + @Override + public Class expected() { + // TODO Auto-generated method stub + return null; + } + + @Override + public long timeout() { + + return 0; + } + + @Override + public Class annotationType() { + return Test.class; + } }); - writer.beginPublicMethod(Types.VOID, "test"); - writer.end(); - writer.end(); - - System.out.println(w); - } - - @Test - public void Fields() throws IOException { - writer.beginClass(testType); - // private - writer.privateField(Types.STRING, "privateField"); - writer.privateStaticFinal(Types.STRING, "privateStaticFinal", "\"val\""); - // protected - writer.protectedField(Types.STRING, "protectedField"); - // field - writer.field(Types.STRING, "field"); - // public - writer.publicField(Types.STRING, "publicField"); - writer.publicStaticFinal(Types.STRING, "publicStaticFinal", "\"val\""); - writer.publicFinal(Types.STRING, "publicFinalField"); - writer.publicFinal(Types.STRING, "publicFinalField2", "\"val\""); - - writer.end(); - - System.out.println(w); + writer.beginPublicMethod(Types.VOID, "test"); + writer.end(); + writer.end(); + + System.out.println(w); + } + + @Test + public void Fields() throws IOException { + writer.beginClass(testType); + // private + writer.privateField(Types.STRING, "privateField"); + writer.privateStaticFinal(Types.STRING, "privateStaticFinal", "\"val\""); + // protected + writer.protectedField(Types.STRING, "protectedField"); + // field + writer.field(Types.STRING, "field"); + // public + writer.publicField(Types.STRING, "publicField"); + writer.publicStaticFinal(Types.STRING, "publicStaticFinal", "\"val\""); + writer.publicFinal(Types.STRING, "publicFinalField"); + writer.publicFinal(Types.STRING, "publicFinalField2", "\"val\""); + + writer.end(); + + System.out.println(w); + } + + @Test + public void Methods() throws IOException { + writer.beginClass(testType); + // private + + // protected + + // method + + // public + writer.beginPublicMethod( + Types.STRING, "publicMethod", Arrays.asList(new Parameter("a", Types.STRING)), transformer); + writer.line("return null;"); + writer.end(); + + writer.beginStaticMethod( + Types.STRING, "staticMethod", Arrays.asList(new Parameter("a", Types.STRING)), transformer); + writer.line("return null;"); + writer.end(); + + writer.end(); + + System.out.println(w); + } + + @Test + public void Constructors() throws IOException { + writer.beginClass(testType); + + writer.beginConstructor( + Arrays.asList(new Parameter("a", Types.STRING), new Parameter("b", Types.STRING)), + transformer); + writer.end(); + + writer.beginConstructor(new Parameter("a", Types.STRING)); + writer.end(); + + writer.end(); + + System.out.println(w); + } + + @Test + public void CaseClass() throws IOException { + writer.caseClass( + "TestType", new Parameter("a", Types.STRING), new Parameter("b", Types.STRING)); + + System.out.println(w); + assertEquals("case class TestType(a: String, b: String)\n", w.toString()); + } + + @Test + public void ClassConstants() { + assertEquals("classOf[SomeClass]", writer.getClassConstant("SomeClass")); + } + + @Test + public void Primitive() throws IOException { + writer.beginClass(testType); + + writer.beginConstructor(new Parameter("a", Types.INT)); + writer.end(); + + writer.end(); + + System.out.println(w); + + assertTrue(w.toString().contains("def this(a: Int) {")); + } + + @Test + public void Primitive_Types() throws IOException { + writer.field(Types.BOOLEAN_P, "field"); + writer.field(Types.BYTE_P, "field"); + writer.field(Types.CHAR, "field"); + writer.field(Types.INT, "field"); + writer.field(Types.LONG_P, "field"); + writer.field(Types.SHORT_P, "field"); + writer.field(Types.DOUBLE_P, "field"); + writer.field(Types.FLOAT_P, "field"); + + for (String type : + Arrays.asList("boolean", "byte", "char", "int", "long", "short", "double", "float")) { + assertTrue(w.toString().contains("field: " + StringUtils.capitalize(type))); } + } - @Test - public void Methods() throws IOException { - writer.beginClass(testType); - // private + @Test + public void ReservedWords() throws IOException { + writer.beginClass(testType); - // protected - - // method - - // public - writer.beginPublicMethod(Types.STRING, "publicMethod", - Arrays.asList(new Parameter("a", Types.STRING)), transformer); - writer.line("return null;"); - writer.end(); - - writer.beginStaticMethod(Types.STRING, "staticMethod", - Arrays.asList(new Parameter("a", Types.STRING)), transformer); - writer.line("return null;"); - writer.end(); - - writer.end(); - - System.out.println(w); - } + writer.beginConstructor(new Parameter("type", Types.INT)); + writer.end(); - @Test - public void Constructors() throws IOException { - writer.beginClass(testType); + writer.publicField(testType, "class"); - writer.beginConstructor( - Arrays.asList(new Parameter("a", Types.STRING), new Parameter("b", Types.STRING)), - transformer); - writer.end(); + writer.beginPublicMethod(testType, "var"); + writer.end(); - writer.beginConstructor(new Parameter("a", Types.STRING)); - writer.end(); + writer.end(); - writer.end(); + System.out.println(w); - System.out.println(w); - - } - - @Test - public void CaseClass() throws IOException { - writer.caseClass("TestType", new Parameter("a", Types.STRING), new Parameter("b", - Types.STRING)); - - System.out.println(w); - assertEquals("case class TestType(a: String, b: String)\n", w.toString()); - } - - @Test - public void ClassConstants() { - assertEquals("classOf[SomeClass]", writer.getClassConstant("SomeClass")); - } - - @Test - public void Primitive() throws IOException { - writer.beginClass(testType); - - writer.beginConstructor(new Parameter("a", Types.INT)); - writer.end(); - - writer.end(); - - System.out.println(w); - - assertTrue(w.toString().contains("def this(a: Int) {")); - } - - @Test - public void Primitive_Types() throws IOException { - writer.field(Types.BOOLEAN_P, "field"); - writer.field(Types.BYTE_P, "field"); - writer.field(Types.CHAR, "field"); - writer.field(Types.INT, "field"); - writer.field(Types.LONG_P, "field"); - writer.field(Types.SHORT_P, "field"); - writer.field(Types.DOUBLE_P, "field"); - writer.field(Types.FLOAT_P, "field"); - - for (String type : Arrays.asList("boolean", "byte", "char", "int", "long", "short", - "double", "float")) { - assertTrue(w.toString().contains("field: " + StringUtils.capitalize(type))); - } - } - - @Test - public void ReservedWords() throws IOException { - writer.beginClass(testType); - - writer.beginConstructor(new Parameter("type", Types.INT)); - writer.end(); - - writer.publicField(testType, "class"); - - writer.beginPublicMethod(testType, "var"); - writer.end(); - - writer.end(); - - System.out.println(w); - - assertTrue(w.toString().contains("`type`: Int")); - assertTrue(w.toString().contains("`class`: JavaWriterTest")); - assertTrue(w.toString().contains("`var`(): JavaWriterTest")); - } + assertTrue(w.toString().contains("`type`: Int")); + assertTrue(w.toString().contains("`class`: JavaWriterTest")); + assertTrue(w.toString().contains("`var`(): JavaWriterTest")); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java index 38ccbe2d02..840625b135 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java @@ -15,10 +15,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.tools.JavaCompiler; import javax.tools.ToolProvider; - import org.junit.After; import org.junit.Assert; import org.junit.Ignore; @@ -26,62 +24,63 @@ public class SimpleCompilerTest { - @After - public void tearDown() { - new File("src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.class").delete(); - } + @After + public void tearDown() { + new File("src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.class").delete(); + } - @Test - @Ignore - public void Run() throws UnsupportedEncodingException { - new File("target/out").mkdir(); - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); - - // create classpath - StringBuilder path = new StringBuilder(); - for (URL url : classLoader.getURLs()) { - if (path.length() > 0) { - path.append(File.pathSeparator); - } - String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8"); - path.append(new File(decodedPath).getAbsolutePath()); - } - System.err.println(path); - - // compile - List options = Arrays.asList( - "-classpath", path.toString(), - "-s", "target/out", - "src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java"); - int compilationResult = compiler.run(null, null, null, - options.toArray(new String[options.size()])); - if (compilationResult != 0) { - Assert.fail("Compilation Failed"); - } + @Test + @Ignore + public void Run() throws UnsupportedEncodingException { + new File("target/out").mkdir(); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); + + // create classpath + StringBuilder path = new StringBuilder(); + for (URL url : classLoader.getURLs()) { + if (path.length() > 0) { + path.append(File.pathSeparator); + } + String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8"); + path.append(new File(decodedPath).getAbsolutePath()); } - - @Test - public void Run2() { - new File("target/out2").mkdir(); - JavaCompiler compiler = new SimpleCompiler(); - System.out.println(compiler.getClass().getName()); - List options = new ArrayList(3); - options.add("-s"); - options.add("target/out2"); - options.add("src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java"); - int compilationResult = compiler.run(null, null, null, - options.toArray(new String[options.size()])); - if (compilationResult != 0) { - Assert.fail("Compilation Failed"); - } + System.err.println(path); + + // compile + List options = + Arrays.asList( + "-classpath", + path.toString(), + "-s", + "target/out", + "src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java"); + int compilationResult = + compiler.run(null, null, null, options.toArray(new String[options.size()])); + if (compilationResult != 0) { + Assert.fail("Compilation Failed"); } + } - @Test - public void Surefire() { - URLClassLoader cl = (URLClassLoader) Thread.currentThread().getContextClassLoader(); - assertTrue(SimpleCompiler.isSureFireBooter(cl)); + @Test + public void Run2() { + new File("target/out2").mkdir(); + JavaCompiler compiler = new SimpleCompiler(); + System.out.println(compiler.getClass().getName()); + List options = new ArrayList(3); + options.add("-s"); + options.add("target/out2"); + options.add("src/test/java/com/querydsl/codegen/utils/SimpleCompilerTest.java"); + int compilationResult = + compiler.run(null, null, null, options.toArray(new String[options.size()])); + if (compilationResult != 0) { + Assert.fail("Compilation Failed"); } - + } + @Test + public void Surefire() { + URLClassLoader cl = (URLClassLoader) Thread.currentThread().getContextClassLoader(); + assertTrue(SimpleCompiler.isSureFireBooter(cl)); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SurefireBooterTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SurefireBooterTest.java index d5cf4b0b4a..7d8b67c7c8 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SurefireBooterTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/SurefireBooterTest.java @@ -4,22 +4,20 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.jar.Manifest; - import org.junit.Test; public class SurefireBooterTest { - - @Test - public void test() throws IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader instanceof URLClassLoader) { - URLClassLoader cl = (URLClassLoader) classLoader; - if (cl.getURLs().length == 1 && cl.getURLs()[0].getPath().contains("surefirebooter")) { - URL url = cl.findResource("META-INF/MANIFEST.MF"); - Manifest manifest = new Manifest(url.openStream()); - System.out.println(manifest.getMainAttributes().getValue("Class-Path")); - } - } - } + @Test + public void test() throws IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + if (classLoader instanceof URLClassLoader) { + URLClassLoader cl = (URLClassLoader) classLoader; + if (cl.getURLs().length == 1 && cl.getURLs()[0].getPath().contains("surefirebooter")) { + URL url = cl.findResource("META-INF/MANIFEST.MF"); + Manifest manifest = new Manifest(url.openStream()); + System.out.println(manifest.getMainAttributes().getValue("Class-Path")); + } + } + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ClassTypeTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ClassTypeTest.java index c1e5554154..21cd54de57 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ClassTypeTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ClassTypeTest.java @@ -9,126 +9,127 @@ import java.util.Collections; import java.util.Map; - import org.junit.Test; public class ClassTypeTest { - public class Inner { - public class Inner2 { - public class Inner3 { - } - } - } - - private final ClassType stringType = new ClassType(TypeCategory.STRING, String.class); - - // @Test - // public void asArrayType(){ - // assertEquals(stringType, stringType.asArrayType().getParameter(0)); - // } - - @Test - public void InnerClass_Name() { - assertEquals("com.querydsl.codegen.utils.model.ClassTypeTest.Inner", - new ClassType(Inner.class).getFullName()); - assertEquals("com.querydsl.codegen.utils.model.ClassTypeTest.Inner[]", new ClassType(Inner.class) - .asArrayType().getFullName()); - } - - @Test - public void ArrayType() { - Type type = new ClassType(TypeCategory.ARRAY, String[].class); - assertEquals("java.lang", type.getPackageName()); - } - - @Test - public void ArrayType_Equals_SimpleType() { - Type type = new ClassType(TypeCategory.ARRAY, String[].class); - Type type2 = new SimpleType("java.lang.String[]", "java.lang", "String[]"); - assertEquals(type, type2); - } - - @Test - public void As() { - assertEquals(TypeCategory.COMPARABLE, stringType.as(TypeCategory.COMPARABLE).getCategory()); - } - - @Test - public void GetParameters() { - ClassType mapType = new ClassType(TypeCategory.MAP, Map.class, stringType, stringType); - assertEquals(2, mapType.getParameters().size()); - assertEquals(stringType, mapType.getParameters().get(0)); - assertEquals(stringType, mapType.getParameters().get(1)); - // assertEquals(stringType, mapType.getSelfOrValueType()); - assertFalse(mapType.isPrimitive()); - } - - @Test - public void GetComponentType() { - assertEquals("java.lang.String", new ClassType(String[].class).getComponentType() - .getFullName()); - } - - @Test - public void Primitive_Arrays() { - ClassType byteArray = new ClassType(byte[].class); - assertEquals( - "byte[]", - byteArray.getRawName(Collections.singleton("java.lang"), - Collections. emptySet())); - assertEquals("byte[]", byteArray.getSimpleName()); - assertEquals("byte[]", byteArray.getFullName()); - } - - @Test - public void Array() { - ClassType byteArray = new ClassType(Byte[].class); - assertEquals( - "Byte[]", - byteArray.getRawName(Collections.singleton("java.lang"), - Collections. emptySet())); - assertEquals("Byte[]", byteArray.getSimpleName()); - assertEquals("java.lang.Byte[]", byteArray.getFullName()); - } - - @Test - public void IsPrimitive() { - assertTrue(Types.CHAR.isPrimitive()); - assertTrue(Types.DOUBLE_P.isPrimitive()); - assertTrue(Types.FLOAT_P.isPrimitive()); - assertTrue(Types.INT.isPrimitive()); - assertTrue(Types.LONG_P.isPrimitive()); - assertTrue(Types.SHORT_P.isPrimitive()); - } - -// @Test -// public void GetPrimitiveName() { -// assertEquals("char", Types.CHARACTER.getPrimitiveName()); -// assertEquals("double", Types.DOUBLE.getPrimitiveName()); -// assertEquals("float", Types.FLOAT.getPrimitiveName()); -// assertEquals("int", Types.INTEGER.getPrimitiveName()); -// assertEquals("long", Types.LONG.getPrimitiveName()); -// assertEquals("short", Types.SHORT.getPrimitiveName()); -// } - - @Test - public void GetEnclosingType() { - Type outer = new ClassType(ClassTypeTest.class); - Type inner = new ClassType(ClassTypeTest.Inner.class); - Type inner2 = new ClassType(ClassTypeTest.Inner.Inner2.class); - Type inner3 = new ClassType(ClassTypeTest.Inner.Inner2.Inner3.class); - - assertEquals(inner2, inner3.getEnclosingType()); - assertEquals(inner, inner2.getEnclosingType()); - assertEquals(outer, inner.getEnclosingType()); - assertNull(outer.getEnclosingType()); - - assertEquals("ClassTypeTest.Inner.Inner2.Inner3", - inner3.getRawName(Collections.singleton(outer.getPackageName()), Collections.emptySet())); - assertEquals("Inner2.Inner3", - inner3.getRawName(Collections.emptySet(), Collections.singleton(inner2.getFullName()))); - assertEquals("Inner3", - inner3.getRawName(Collections.emptySet(), Collections.singleton(inner3.getFullName()))); + public class Inner { + public class Inner2 { + public class Inner3 {} } + } + + private final ClassType stringType = new ClassType(TypeCategory.STRING, String.class); + + // @Test + // public void asArrayType(){ + // assertEquals(stringType, stringType.asArrayType().getParameter(0)); + // } + + @Test + public void InnerClass_Name() { + assertEquals( + "com.querydsl.codegen.utils.model.ClassTypeTest.Inner", + new ClassType(Inner.class).getFullName()); + assertEquals( + "com.querydsl.codegen.utils.model.ClassTypeTest.Inner[]", + new ClassType(Inner.class).asArrayType().getFullName()); + } + + @Test + public void ArrayType() { + Type type = new ClassType(TypeCategory.ARRAY, String[].class); + assertEquals("java.lang", type.getPackageName()); + } + + @Test + public void ArrayType_Equals_SimpleType() { + Type type = new ClassType(TypeCategory.ARRAY, String[].class); + Type type2 = new SimpleType("java.lang.String[]", "java.lang", "String[]"); + assertEquals(type, type2); + } + + @Test + public void As() { + assertEquals(TypeCategory.COMPARABLE, stringType.as(TypeCategory.COMPARABLE).getCategory()); + } + + @Test + public void GetParameters() { + ClassType mapType = new ClassType(TypeCategory.MAP, Map.class, stringType, stringType); + assertEquals(2, mapType.getParameters().size()); + assertEquals(stringType, mapType.getParameters().get(0)); + assertEquals(stringType, mapType.getParameters().get(1)); + // assertEquals(stringType, mapType.getSelfOrValueType()); + assertFalse(mapType.isPrimitive()); + } + + @Test + public void GetComponentType() { + assertEquals( + "java.lang.String", new ClassType(String[].class).getComponentType().getFullName()); + } + + @Test + public void Primitive_Arrays() { + ClassType byteArray = new ClassType(byte[].class); + assertEquals( + "byte[]", + byteArray.getRawName(Collections.singleton("java.lang"), Collections.emptySet())); + assertEquals("byte[]", byteArray.getSimpleName()); + assertEquals("byte[]", byteArray.getFullName()); + } + + @Test + public void Array() { + ClassType byteArray = new ClassType(Byte[].class); + assertEquals( + "Byte[]", + byteArray.getRawName(Collections.singleton("java.lang"), Collections.emptySet())); + assertEquals("Byte[]", byteArray.getSimpleName()); + assertEquals("java.lang.Byte[]", byteArray.getFullName()); + } + + @Test + public void IsPrimitive() { + assertTrue(Types.CHAR.isPrimitive()); + assertTrue(Types.DOUBLE_P.isPrimitive()); + assertTrue(Types.FLOAT_P.isPrimitive()); + assertTrue(Types.INT.isPrimitive()); + assertTrue(Types.LONG_P.isPrimitive()); + assertTrue(Types.SHORT_P.isPrimitive()); + } + + // @Test + // public void GetPrimitiveName() { + // assertEquals("char", Types.CHARACTER.getPrimitiveName()); + // assertEquals("double", Types.DOUBLE.getPrimitiveName()); + // assertEquals("float", Types.FLOAT.getPrimitiveName()); + // assertEquals("int", Types.INTEGER.getPrimitiveName()); + // assertEquals("long", Types.LONG.getPrimitiveName()); + // assertEquals("short", Types.SHORT.getPrimitiveName()); + // } + + @Test + public void GetEnclosingType() { + Type outer = new ClassType(ClassTypeTest.class); + Type inner = new ClassType(ClassTypeTest.Inner.class); + Type inner2 = new ClassType(ClassTypeTest.Inner.Inner2.class); + Type inner3 = new ClassType(ClassTypeTest.Inner.Inner2.Inner3.class); + + assertEquals(inner2, inner3.getEnclosingType()); + assertEquals(inner, inner2.getEnclosingType()); + assertEquals(outer, inner.getEnclosingType()); + assertNull(outer.getEnclosingType()); + + assertEquals( + "ClassTypeTest.Inner.Inner2.Inner3", + inner3.getRawName(Collections.singleton(outer.getPackageName()), Collections.emptySet())); + assertEquals( + "Inner2.Inner3", + inner3.getRawName(Collections.emptySet(), Collections.singleton(inner2.getFullName()))); + assertEquals( + "Inner3", + inner3.getRawName(Collections.emptySet(), Collections.singleton(inner3.getFullName()))); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ConstructorTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ConstructorTest.java index 95c819ae10..98f441b937 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ConstructorTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ConstructorTest.java @@ -8,22 +8,20 @@ import static org.junit.Assert.assertEquals; import java.util.Arrays; - import org.junit.Test; public class ConstructorTest { - @Test - public void test() { - Parameter firstName = new Parameter("firstName", new ClassType(TypeCategory.STRING, - String.class)); - Parameter lastName = new Parameter("lastName", new ClassType(TypeCategory.STRING, - String.class)); - Constructor c1 = new Constructor(Arrays.asList(firstName, lastName)); - Constructor c2 = new Constructor(Arrays.asList(firstName, lastName)); - assertEquals(c1, c1); - assertEquals(c1, c2); - assertEquals(c1.hashCode(), c2.hashCode()); - } - + @Test + public void test() { + Parameter firstName = + new Parameter("firstName", new ClassType(TypeCategory.STRING, String.class)); + Parameter lastName = + new Parameter("lastName", new ClassType(TypeCategory.STRING, String.class)); + Constructor c1 = new Constructor(Arrays.asList(firstName, lastName)); + Constructor c2 = new Constructor(Arrays.asList(firstName, lastName)); + assertEquals(c1, c1); + assertEquals(c1, c2); + assertEquals(c1.hashCode(), c2.hashCode()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ParameterTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ParameterTest.java index 265adac9c4..c6a8f885e8 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ParameterTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/ParameterTest.java @@ -11,16 +11,14 @@ public class ParameterTest { - @Test - public void test() { - Parameter param1 = new Parameter("test", new ClassType(TypeCategory.STRING, String.class)); - Parameter param2 = new Parameter("test2", new ClassType(TypeCategory.STRING, String.class)); - Parameter param3 = new Parameter("test2", - new ClassType(TypeCategory.NUMERIC, Integer.class)); - - assertFalse(param1.equals(param2)); - assertFalse(param1.equals(param3)); - assertFalse(param2.equals(param3)); - } + @Test + public void test() { + Parameter param1 = new Parameter("test", new ClassType(TypeCategory.STRING, String.class)); + Parameter param2 = new Parameter("test2", new ClassType(TypeCategory.STRING, String.class)); + Parameter param3 = new Parameter("test2", new ClassType(TypeCategory.NUMERIC, Integer.class)); + assertFalse(param1.equals(param2)); + assertFalse(param1.equals(param3)); + assertFalse(param2.equals(param3)); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/SimpleTypeTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/SimpleTypeTest.java index fb9c838ca3..4adfa98d5c 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/SimpleTypeTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/SimpleTypeTest.java @@ -3,95 +3,97 @@ import static org.junit.Assert.*; import java.util.Collections; - import org.junit.Test; public class SimpleTypeTest { - public static class Inner { - public class Inner2 { - public class Inner3 { - } - } - } - - @Test - public void PrimitiveArray() { - Type byteArray = new ClassType(byte[].class); - Type byteArray2 = new SimpleType(byteArray, byteArray.getParameters()); - assertEquals( - "byte[]", - byteArray.getRawName(Collections.singleton("java.lang"), - Collections. emptySet())); - assertEquals( - "byte[]", - byteArray2.getRawName(Collections.singleton("java.lang"), - Collections. emptySet())); + public static class Inner { + public class Inner2 { + public class Inner3 {} } + } - @Test - public void Array_FullName() { - Type type = new SimpleType(new ClassType(String[].class)); - assertEquals("java.lang.String[]", type.getFullName()); - } + @Test + public void PrimitiveArray() { + Type byteArray = new ClassType(byte[].class); + Type byteArray2 = new SimpleType(byteArray, byteArray.getParameters()); + assertEquals( + "byte[]", + byteArray.getRawName(Collections.singleton("java.lang"), Collections.emptySet())); + assertEquals( + "byte[]", + byteArray2.getRawName(Collections.singleton("java.lang"), Collections.emptySet())); + } - @Test - public void GetComponentType() { - Type type = new SimpleType(new ClassType(String[].class)); - assertEquals("java.lang.String", type.getComponentType().getFullName()); - } + @Test + public void Array_FullName() { + Type type = new SimpleType(new ClassType(String[].class)); + assertEquals("java.lang.String[]", type.getFullName()); + } - @Test - public void GetRawName() { - assertEquals("String", new SimpleType(Types.STRING).getRawName( - Collections. emptySet(), Collections.singleton(Types.STRING.getFullName()))); - } + @Test + public void GetComponentType() { + Type type = new SimpleType(new ClassType(String[].class)); + assertEquals("java.lang.String", type.getComponentType().getFullName()); + } - @Test - public void GetJavaClass_For_Array() { - System.out.println(Inner.class.getName()); - assertEquals(byte[].class, new ClassType(byte[].class).getJavaClass()); - assertEquals(byte[].class, new SimpleType(new ClassType(byte[].class)).getJavaClass()); - } + @Test + public void GetRawName() { + assertEquals( + "String", + new SimpleType(Types.STRING) + .getRawName( + Collections.emptySet(), Collections.singleton(Types.STRING.getFullName()))); + } - @Test - public void GetJavaClass_For_InnerClass() { - assertEquals(Inner.class, new ClassType(Inner.class).getJavaClass()); - assertEquals(Inner.class, new SimpleType(new ClassType(Inner.class)).getJavaClass()); - } - -// @Test -// public void GetPrimitiveName() { -// assertEquals("int", Types.INT.getPrimitiveName()); -// assertEquals("int", new SimpleType(Types.INT).getPrimitiveName()); -// -// assertEquals("int", Types.INTEGER.getPrimitiveName()); -// assertEquals("int", new SimpleType(Types.INTEGER).getPrimitiveName()); -// } + @Test + public void GetJavaClass_For_Array() { + System.out.println(Inner.class.getName()); + assertEquals(byte[].class, new ClassType(byte[].class).getJavaClass()); + assertEquals(byte[].class, new SimpleType(new ClassType(byte[].class)).getJavaClass()); + } - @Test - public void GetEnclosingType() { - Type outer = new SimpleType(new ClassType(SimpleTypeTest.class)); - Type inner = new SimpleType(new ClassType(SimpleTypeTest.Inner.class)); - Type inner2 = new SimpleType(new ClassType(SimpleTypeTest.Inner.Inner2.class)); - Type inner3 = new SimpleType(new ClassType(SimpleTypeTest.Inner.Inner2.Inner3.class)); + @Test + public void GetJavaClass_For_InnerClass() { + assertEquals(Inner.class, new ClassType(Inner.class).getJavaClass()); + assertEquals(Inner.class, new SimpleType(new ClassType(Inner.class)).getJavaClass()); + } - assertEquals(inner2, inner3.getEnclosingType()); - assertEquals(inner, inner2.getEnclosingType()); - assertEquals(outer, inner.getEnclosingType()); - assertNull(outer.getEnclosingType()); + // @Test + // public void GetPrimitiveName() { + // assertEquals("int", Types.INT.getPrimitiveName()); + // assertEquals("int", new SimpleType(Types.INT).getPrimitiveName()); + // + // assertEquals("int", Types.INTEGER.getPrimitiveName()); + // assertEquals("int", new SimpleType(Types.INTEGER).getPrimitiveName()); + // } - assertEquals("SimpleTypeTest.Inner.Inner2.Inner3", - inner3.getRawName(Collections.singleton(outer.getPackageName()), Collections.emptySet())); - assertEquals("Inner2.Inner3", - inner3.getRawName(Collections.emptySet(), Collections.singleton(inner2.getFullName()))); - assertEquals("Inner3", - inner3.getRawName(Collections.emptySet(), Collections.singleton(inner3.getFullName()))); - } - @Test - public void IsMember() { - assertTrue(new SimpleType(new ClassType(SimpleTypeTest.Inner.class)).isMember()); - assertFalse(new SimpleType(new ClassType(SimpleType.class)).isMember()); - } + @Test + public void GetEnclosingType() { + Type outer = new SimpleType(new ClassType(SimpleTypeTest.class)); + Type inner = new SimpleType(new ClassType(SimpleTypeTest.Inner.class)); + Type inner2 = new SimpleType(new ClassType(SimpleTypeTest.Inner.Inner2.class)); + Type inner3 = new SimpleType(new ClassType(SimpleTypeTest.Inner.Inner2.Inner3.class)); + + assertEquals(inner2, inner3.getEnclosingType()); + assertEquals(inner, inner2.getEnclosingType()); + assertEquals(outer, inner.getEnclosingType()); + assertNull(outer.getEnclosingType()); + + assertEquals( + "SimpleTypeTest.Inner.Inner2.Inner3", + inner3.getRawName(Collections.singleton(outer.getPackageName()), Collections.emptySet())); + assertEquals( + "Inner2.Inner3", + inner3.getRawName(Collections.emptySet(), Collections.singleton(inner2.getFullName()))); + assertEquals( + "Inner3", + inner3.getRawName(Collections.emptySet(), Collections.singleton(inner3.getFullName()))); + } + @Test + public void IsMember() { + assertTrue(new SimpleType(new ClassType(SimpleTypeTest.Inner.class)).isMember()); + assertFalse(new SimpleType(new ClassType(SimpleType.class)).isMember()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeAdapterTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeAdapterTest.java index b0b5b2e992..7b46f7bf3e 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeAdapterTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeAdapterTest.java @@ -6,19 +6,19 @@ public class TypeAdapterTest { - @Test - public void Delegation() { - Type inner = Types.OBJECT; - Type type = new TypeAdapter(inner); - assertEquals(inner.getCategory(), type.getCategory()); - assertEquals(inner.getComponentType(), type.getComponentType()); - assertEquals(inner.getFullName(), type.getFullName()); - assertEquals(inner.getGenericName(true), type.getGenericName(true)); - assertEquals(inner.getPackageName(), type.getPackageName()); - assertEquals(inner.getParameters(), type.getParameters()); -// assertEquals(inner.getPrimitiveName(), type.getPrimitiveName()); - assertEquals(inner.getSimpleName(), type.getSimpleName()); - assertEquals(inner.isFinal(), type.isFinal()); - assertEquals(inner.isPrimitive(), type.isPrimitive()); - } + @Test + public void Delegation() { + Type inner = Types.OBJECT; + Type type = new TypeAdapter(inner); + assertEquals(inner.getCategory(), type.getCategory()); + assertEquals(inner.getComponentType(), type.getComponentType()); + assertEquals(inner.getFullName(), type.getFullName()); + assertEquals(inner.getGenericName(true), type.getGenericName(true)); + assertEquals(inner.getPackageName(), type.getPackageName()); + assertEquals(inner.getParameters(), type.getParameters()); + // assertEquals(inner.getPrimitiveName(), type.getPrimitiveName()); + assertEquals(inner.getSimpleName(), type.getSimpleName()); + assertEquals(inner.isFinal(), type.isFinal()); + assertEquals(inner.isPrimitive(), type.isPrimitive()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeCategoryTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeCategoryTest.java index f141dd63a3..2f854924da 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeCategoryTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeCategoryTest.java @@ -11,37 +11,35 @@ import java.sql.Date; import java.sql.Time; - import org.junit.Test; public class TypeCategoryTest { - @Test - public void IsSubCategoryOf() { - assertTrue(TypeCategory.BOOLEAN.isSubCategoryOf(TypeCategory.COMPARABLE)); - assertTrue(TypeCategory.STRING.isSubCategoryOf(TypeCategory.COMPARABLE)); - assertTrue(TypeCategory.NUMERIC.isSubCategoryOf(TypeCategory.COMPARABLE)); - assertTrue(TypeCategory.COMPARABLE.isSubCategoryOf(TypeCategory.SIMPLE)); - assertFalse(TypeCategory.ENTITY.isSubCategoryOf(TypeCategory.SIMPLE)); - } - - @Test - public void Get() { - assertEquals(TypeCategory.BOOLEAN, TypeCategory.get(Boolean.class.getName())); - assertEquals(TypeCategory.STRING, TypeCategory.get(String.class.getName())); - assertEquals(TypeCategory.DATE, TypeCategory.get(Date.class.getName())); - assertEquals(TypeCategory.TIME, TypeCategory.get(Time.class.getName())); - } - - @Test - public void Java8() { - assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.Instant")); - assertEquals(TypeCategory.DATE, TypeCategory.get("java.time.LocalDate")); - assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.LocalDateTime")); - assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.LocalTime")); - assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.OffsetDateTime")); - assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.OffsetTime")); - assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.ZonedDateTime")); - } - + @Test + public void IsSubCategoryOf() { + assertTrue(TypeCategory.BOOLEAN.isSubCategoryOf(TypeCategory.COMPARABLE)); + assertTrue(TypeCategory.STRING.isSubCategoryOf(TypeCategory.COMPARABLE)); + assertTrue(TypeCategory.NUMERIC.isSubCategoryOf(TypeCategory.COMPARABLE)); + assertTrue(TypeCategory.COMPARABLE.isSubCategoryOf(TypeCategory.SIMPLE)); + assertFalse(TypeCategory.ENTITY.isSubCategoryOf(TypeCategory.SIMPLE)); + } + + @Test + public void Get() { + assertEquals(TypeCategory.BOOLEAN, TypeCategory.get(Boolean.class.getName())); + assertEquals(TypeCategory.STRING, TypeCategory.get(String.class.getName())); + assertEquals(TypeCategory.DATE, TypeCategory.get(Date.class.getName())); + assertEquals(TypeCategory.TIME, TypeCategory.get(Time.class.getName())); + } + + @Test + public void Java8() { + assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.Instant")); + assertEquals(TypeCategory.DATE, TypeCategory.get("java.time.LocalDate")); + assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.LocalDateTime")); + assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.LocalTime")); + assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.OffsetDateTime")); + assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.OffsetTime")); + assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.ZonedDateTime")); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeExtendsTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeExtendsTest.java index e0b1621b61..8090a1809b 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeExtendsTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeExtendsTest.java @@ -6,26 +6,27 @@ public class TypeExtendsTest { - @Test - public void GetVarName() { - assertEquals("var", new TypeExtends("var", Types.COLLECTION).getVarName()); - } - - @Test - public void GetGenericName() { - assertEquals("? extends java.util.Collection", new TypeExtends( - Types.COLLECTION).getGenericName(false)); - } - - @Test - public void GetGenericName_As_ArgType() { - assertEquals("java.util.Collection", - new TypeExtends(Types.COLLECTION).getGenericName(true)); - } - - @Test - public void GetGenericName_With_Object() { - assertEquals("?", new TypeExtends(Types.OBJECT).getGenericName(false)); - } - + @Test + public void GetVarName() { + assertEquals("var", new TypeExtends("var", Types.COLLECTION).getVarName()); + } + + @Test + public void GetGenericName() { + assertEquals( + "? extends java.util.Collection", + new TypeExtends(Types.COLLECTION).getGenericName(false)); + } + + @Test + public void GetGenericName_As_ArgType() { + assertEquals( + "java.util.Collection", + new TypeExtends(Types.COLLECTION).getGenericName(true)); + } + + @Test + public void GetGenericName_With_Object() { + assertEquals("?", new TypeExtends(Types.OBJECT).getGenericName(false)); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeSuperTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeSuperTest.java index 95ddee3fcd..a99a956a8a 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeSuperTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeSuperTest.java @@ -6,28 +6,28 @@ public class TypeSuperTest { - @Test - public void GetVarName() { - assertEquals("var", new TypeSuper("var", Types.STRING).getVarName()); - } + @Test + public void GetVarName() { + assertEquals("var", new TypeSuper("var", Types.STRING).getVarName()); + } - @Test - public void GetGenericName() { - assertEquals("? super java.lang.String", new TypeSuper(Types.STRING).getGenericName(false)); - } + @Test + public void GetGenericName() { + assertEquals("? super java.lang.String", new TypeSuper(Types.STRING).getGenericName(false)); + } - @Test - public void GetGenericName_As_ArgType() { - assertEquals("java.lang.Object", new TypeSuper(Types.STRING).getGenericName(true)); - } - - @Test - public void Comparable() { - // T extends Comparable - Type comparable = new ClassType(Comparable.class); - Type type = new TypeExtends("T", - new SimpleType(comparable, new TypeSuper(new TypeExtends("T", comparable)))); - assertEquals("? extends java.lang.Comparable", type.getGenericName(false)); - } + @Test + public void GetGenericName_As_ArgType() { + assertEquals("java.lang.Object", new TypeSuper(Types.STRING).getGenericName(true)); + } + @Test + public void Comparable() { + // T extends Comparable + Type comparable = new ClassType(Comparable.class); + Type type = + new TypeExtends( + "T", new SimpleType(comparable, new TypeSuper(new TypeExtends("T", comparable)))); + assertEquals("? extends java.lang.Comparable", type.getGenericName(false)); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeTest.java index e3e6ab60b2..e3a0cbfccc 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/model/TypeTest.java @@ -14,175 +14,173 @@ import java.util.Locale; import java.util.Map; import java.util.Set; - import org.junit.Test; public class TypeTest { - private Set packages = Collections.singleton("java.lang"); - - private Set classes = Collections.emptySet(); - - private ClassType locale = new ClassType(TypeCategory.SIMPLE, Locale.class); - - private Type string = Types.STRING; - - private Type string2 = new SimpleType(string); - - private Type locale2 = new SimpleType(locale); - - private Type stringList = new ClassType(TypeCategory.LIST, List.class, Types.STRING); - - private Type stringList2 = new SimpleType(Types.LIST, Types.STRING); - - private Type stringMap = new ClassType(TypeCategory.MAP, Map.class, Types.STRING, Types.STRING); - - private Type stringMap2 = new SimpleType(Types.MAP, Types.STRING, Types.STRING); - - @Test - public void arrayType() { - assertEquals("Object[]", Types.OBJECTS.getGenericName(true).toString()); - } - - @Test - public void Equals() { - assertEquals(locale, locale2); - assertEquals(locale2, locale); - assertEquals(stringList, stringList2); - assertEquals(stringList2, stringList); - } - - @Test - public void Hashcode() { - assertEquals(locale.hashCode(), locale2.hashCode()); - assertEquals(stringList.hashCode(), stringList2.hashCode()); - } - - @Test - public void GetGenericNameBoolean() { - assertEquals("java.util.Locale", locale.getGenericName(true)); - assertEquals("java.util.Locale", locale2.getGenericName(true)); - assertEquals("java.util.List", stringList.getGenericName(true)); - assertEquals("java.util.List", stringList2.getGenericName(true)); - assertEquals("java.util.Map", stringMap.getGenericName(true)); - assertEquals("java.util.Map", stringMap2.getGenericName(true)); - - assertEquals("String", string.getGenericName(true)); - assertEquals("String", string2.getGenericName(true)); - } - - @Test - public void GetRawName() { - assertEquals("java.util.Locale", locale.getRawName(packages, classes)); - assertEquals("java.util.Locale", locale2.getRawName(packages, classes)); - assertEquals("java.util.List", stringList.getRawName(packages, classes)); - assertEquals("java.util.List", stringList2.getRawName(packages, classes)); - - assertEquals("String", string.getRawName(packages, classes)); - assertEquals("String", string2.getRawName(packages, classes)); - } - - @Test - public void GetGenericNameBooleanSetOfStringSetOfString() { - assertEquals("java.util.Locale", locale.getGenericName(true, packages, classes)); - assertEquals("java.util.Locale", locale2.getGenericName(true, packages, classes)); - assertEquals("java.util.List", stringList.getGenericName(true, packages, classes)); - assertEquals("java.util.List", stringList2.getGenericName(true, packages, classes)); - } - - @Test - public void GetFullName() { - assertEquals("java.util.Locale", locale.getFullName()); - assertEquals("java.util.Locale", locale2.getFullName()); - assertEquals("java.util.List", stringList.getFullName()); - assertEquals("java.util.List", stringList2.getFullName()); - } - - @Test - public void GetPackageName() { - assertEquals("java.util", locale.getPackageName()); - assertEquals("java.util", locale2.getPackageName()); - assertEquals("java.util", stringList.getPackageName()); - assertEquals("java.util", stringList2.getPackageName()); - } - - @Test - public void GetParameters() { - assertEquals(Collections.emptyList(), locale.getParameters()); - assertEquals(Collections.emptyList(), locale2.getParameters()); - assertEquals(Collections.singletonList(Types.STRING), stringList.getParameters()); - assertEquals(Collections.singletonList(Types.STRING), stringList2.getParameters()); - } - - @Test - public void GetSimpleName() { - assertEquals("Locale", locale.getSimpleName()); - assertEquals("Locale", locale2.getSimpleName()); - assertEquals("List", stringList.getSimpleName()); - assertEquals("List", stringList2.getSimpleName()); - } - - @Test - public void GetJavaClass() { - assertEquals(Locale.class, locale.getJavaClass()); - } - - @Test - public void IsFinal() { - assertTrue(locale.isFinal()); - assertTrue(locale2.isFinal()); - assertFalse(stringList.isFinal()); - - assertTrue(Types.STRING.isFinal()); - assertTrue(Types.LONG.isFinal()); - } - - @Test - public void IsPrimitive() { - assertFalse(locale.isPrimitive()); - assertFalse(locale2.isPrimitive()); - assertFalse(stringList.isPrimitive()); - assertFalse(stringList2.isPrimitive()); - } - - @Test - public void GetCategory() { - assertEquals(TypeCategory.SIMPLE, locale.getCategory()); - assertEquals(TypeCategory.SIMPLE, locale2.getCategory()); - assertEquals(TypeCategory.LIST, stringList.getCategory()); - assertEquals(TypeCategory.LIST, stringList2.getCategory()); - } - - @Test - public void As() { - assertEquals(TypeCategory.SIMPLE, stringList.as(TypeCategory.SIMPLE).getCategory()); - assertEquals(TypeCategory.SIMPLE, stringList2.as(TypeCategory.SIMPLE).getCategory()); - } - -// @Test -// public void GetPrimitiveName() { -// assertNull(locale.getPrimitiveName()); -// assertNull(locale2.getPrimitiveName()); -// assertNull(stringList.getPrimitiveName()); -// assertNull(stringList2.getPrimitiveName()); -// } - - @Test - public void ToString() { - assertEquals("java.util.Locale", locale.toString()); - assertEquals("java.util.Locale", locale2.toString()); - assertEquals("java.util.List", stringList.toString()); - assertEquals("java.util.List", stringList2.toString()); - } - - @Test - public void AsArrayType() { - assertEquals("java.util.Locale[]", locale.asArrayType().getFullName()); - assertEquals(TypeCategory.ARRAY, locale.asArrayType().getCategory()); - assertEquals("java.util.Locale[]", locale2.asArrayType().getFullName()); - assertEquals(TypeCategory.ARRAY, locale2.asArrayType().getCategory()); - assertEquals("java.util.List[]", stringList.asArrayType().getFullName()); - assertEquals("java.util.List[]", stringList2.asArrayType().getFullName()); - } - + private Set packages = Collections.singleton("java.lang"); + + private Set classes = Collections.emptySet(); + + private ClassType locale = new ClassType(TypeCategory.SIMPLE, Locale.class); + + private Type string = Types.STRING; + + private Type string2 = new SimpleType(string); + + private Type locale2 = new SimpleType(locale); + + private Type stringList = new ClassType(TypeCategory.LIST, List.class, Types.STRING); + + private Type stringList2 = new SimpleType(Types.LIST, Types.STRING); + + private Type stringMap = new ClassType(TypeCategory.MAP, Map.class, Types.STRING, Types.STRING); + + private Type stringMap2 = new SimpleType(Types.MAP, Types.STRING, Types.STRING); + + @Test + public void arrayType() { + assertEquals("Object[]", Types.OBJECTS.getGenericName(true).toString()); + } + + @Test + public void Equals() { + assertEquals(locale, locale2); + assertEquals(locale2, locale); + assertEquals(stringList, stringList2); + assertEquals(stringList2, stringList); + } + + @Test + public void Hashcode() { + assertEquals(locale.hashCode(), locale2.hashCode()); + assertEquals(stringList.hashCode(), stringList2.hashCode()); + } + + @Test + public void GetGenericNameBoolean() { + assertEquals("java.util.Locale", locale.getGenericName(true)); + assertEquals("java.util.Locale", locale2.getGenericName(true)); + assertEquals("java.util.List", stringList.getGenericName(true)); + assertEquals("java.util.List", stringList2.getGenericName(true)); + assertEquals("java.util.Map", stringMap.getGenericName(true)); + assertEquals("java.util.Map", stringMap2.getGenericName(true)); + + assertEquals("String", string.getGenericName(true)); + assertEquals("String", string2.getGenericName(true)); + } + + @Test + public void GetRawName() { + assertEquals("java.util.Locale", locale.getRawName(packages, classes)); + assertEquals("java.util.Locale", locale2.getRawName(packages, classes)); + assertEquals("java.util.List", stringList.getRawName(packages, classes)); + assertEquals("java.util.List", stringList2.getRawName(packages, classes)); + + assertEquals("String", string.getRawName(packages, classes)); + assertEquals("String", string2.getRawName(packages, classes)); + } + + @Test + public void GetGenericNameBooleanSetOfStringSetOfString() { + assertEquals("java.util.Locale", locale.getGenericName(true, packages, classes)); + assertEquals("java.util.Locale", locale2.getGenericName(true, packages, classes)); + assertEquals("java.util.List", stringList.getGenericName(true, packages, classes)); + assertEquals("java.util.List", stringList2.getGenericName(true, packages, classes)); + } + + @Test + public void GetFullName() { + assertEquals("java.util.Locale", locale.getFullName()); + assertEquals("java.util.Locale", locale2.getFullName()); + assertEquals("java.util.List", stringList.getFullName()); + assertEquals("java.util.List", stringList2.getFullName()); + } + + @Test + public void GetPackageName() { + assertEquals("java.util", locale.getPackageName()); + assertEquals("java.util", locale2.getPackageName()); + assertEquals("java.util", stringList.getPackageName()); + assertEquals("java.util", stringList2.getPackageName()); + } + + @Test + public void GetParameters() { + assertEquals(Collections.emptyList(), locale.getParameters()); + assertEquals(Collections.emptyList(), locale2.getParameters()); + assertEquals(Collections.singletonList(Types.STRING), stringList.getParameters()); + assertEquals(Collections.singletonList(Types.STRING), stringList2.getParameters()); + } + + @Test + public void GetSimpleName() { + assertEquals("Locale", locale.getSimpleName()); + assertEquals("Locale", locale2.getSimpleName()); + assertEquals("List", stringList.getSimpleName()); + assertEquals("List", stringList2.getSimpleName()); + } + + @Test + public void GetJavaClass() { + assertEquals(Locale.class, locale.getJavaClass()); + } + + @Test + public void IsFinal() { + assertTrue(locale.isFinal()); + assertTrue(locale2.isFinal()); + assertFalse(stringList.isFinal()); + + assertTrue(Types.STRING.isFinal()); + assertTrue(Types.LONG.isFinal()); + } + + @Test + public void IsPrimitive() { + assertFalse(locale.isPrimitive()); + assertFalse(locale2.isPrimitive()); + assertFalse(stringList.isPrimitive()); + assertFalse(stringList2.isPrimitive()); + } + + @Test + public void GetCategory() { + assertEquals(TypeCategory.SIMPLE, locale.getCategory()); + assertEquals(TypeCategory.SIMPLE, locale2.getCategory()); + assertEquals(TypeCategory.LIST, stringList.getCategory()); + assertEquals(TypeCategory.LIST, stringList2.getCategory()); + } + + @Test + public void As() { + assertEquals(TypeCategory.SIMPLE, stringList.as(TypeCategory.SIMPLE).getCategory()); + assertEquals(TypeCategory.SIMPLE, stringList2.as(TypeCategory.SIMPLE).getCategory()); + } + + // @Test + // public void GetPrimitiveName() { + // assertNull(locale.getPrimitiveName()); + // assertNull(locale2.getPrimitiveName()); + // assertNull(stringList.getPrimitiveName()); + // assertNull(stringList2.getPrimitiveName()); + // } + + @Test + public void ToString() { + assertEquals("java.util.Locale", locale.toString()); + assertEquals("java.util.Locale", locale2.toString()); + assertEquals("java.util.List", stringList.toString()); + assertEquals("java.util.List", stringList2.toString()); + } + + @Test + public void AsArrayType() { + assertEquals("java.util.Locale[]", locale.asArrayType().getFullName()); + assertEquals(TypeCategory.ARRAY, locale.asArrayType().getCategory()); + assertEquals("java.util.Locale[]", locale2.asArrayType().getFullName()); + assertEquals(TypeCategory.ARRAY, locale2.asArrayType().getCategory()); + assertEquals("java.util.List[]", stringList.asArrayType().getFullName()); + assertEquals("java.util.List[]", stringList2.asArrayType().getFullName()); + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/Cat.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/Cat.java index 853acc0aec..ddc33ec46c 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/Cat.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/Cat.java @@ -1,6 +1,6 @@ /* * Copyright 2011, Mysema Ltd - * + * * 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 @@ -21,139 +21,141 @@ public class Cat { - private int breed; - - private java.sql.Date dateField; - - public enum Color { - BLUE, GREEN, BROWN - } - private Color eyecolor; - - private List kittens; - - private Cat[] kittenArray; - - private Map kittensByName; - - private Cat mate; - - private String stringAsSimple; - - private java.sql.Time timeField; - - private String name; - - public void setName(String name) { - this.name = name; - } - - private Date birthdate; - private int id; - - public Cat() { - this.kittensByName = Collections.emptyMap(); - } - - public Cat(String name) { - Cat kitten = new Cat(); - this.kittens = Arrays.asList(kitten); - this.kittenArray = new Cat[]{kitten}; - this.kittensByName = Collections.singletonMap("Kitty", kitten); - this.name = name; - } - - public Cat(String name, String kittenName) { - this(name); - kittens.get(0).setName(kittenName); - } - - public Cat(String name, int id) { - this(name); - this.id = id; - } - - public Cat(String name, int id, Date birthdate) { - this(name, id); - this.birthdate = new Date(birthdate.getTime()); - this.dateField = new java.sql.Date(birthdate.getTime()); - this.timeField = new java.sql.Time(birthdate.getTime()); - } - - public int getBreed() { - return breed; - } - - public java.sql.Date getDateField() { - return dateField; - } - - public Color getEyecolor() { - return eyecolor; - } - - public List getKittens() { - return kittens; - } - - public Map getKittensByName() { - return kittensByName; - } - - public Cat getMate() { - return mate; - } - - public String getStringAsSimple() { - return stringAsSimple; - } - - public java.sql.Time getTimeField() { - return timeField; - } - - public void setBreed(int breed) { - this.breed = breed; - } - - public void setDateField(java.sql.Date dateField) { - this.dateField = new java.sql.Date(dateField.getTime()); - } - - public void setEyecolor(Color eyecolor) { - this.eyecolor = eyecolor; - } - - public void setKittens(List kittens) { - this.kittens = kittens; - } - - public void setKittensByName(Map kittensByName) { - this.kittensByName = kittensByName; - } - - public void setMate(Cat mate) { - this.mate = mate; - } - - public void setStringAsSimple(String stringAsSimple) { - this.stringAsSimple = stringAsSimple; - } - - public void setTimeField(java.sql.Time timeField) { - this.timeField = timeField; - } - - public Cat[] getKittenArray() { - return kittenArray; - } - - public void setKittenArray(Cat[] kittenArray) { - this.kittenArray = kittenArray.clone(); - } - - public String toString() { - return name; - } + private int breed; + private java.sql.Date dateField; + + public enum Color { + BLUE, + GREEN, + BROWN + } + + private Color eyecolor; + + private List kittens; + + private Cat[] kittenArray; + + private Map kittensByName; + + private Cat mate; + + private String stringAsSimple; + + private java.sql.Time timeField; + + private String name; + + public void setName(String name) { + this.name = name; + } + + private Date birthdate; + private int id; + + public Cat() { + this.kittensByName = Collections.emptyMap(); + } + + public Cat(String name) { + Cat kitten = new Cat(); + this.kittens = Arrays.asList(kitten); + this.kittenArray = new Cat[] {kitten}; + this.kittensByName = Collections.singletonMap("Kitty", kitten); + this.name = name; + } + + public Cat(String name, String kittenName) { + this(name); + kittens.get(0).setName(kittenName); + } + + public Cat(String name, int id) { + this(name); + this.id = id; + } + + public Cat(String name, int id, Date birthdate) { + this(name, id); + this.birthdate = new Date(birthdate.getTime()); + this.dateField = new java.sql.Date(birthdate.getTime()); + this.timeField = new java.sql.Time(birthdate.getTime()); + } + + public int getBreed() { + return breed; + } + + public java.sql.Date getDateField() { + return dateField; + } + + public Color getEyecolor() { + return eyecolor; + } + + public List getKittens() { + return kittens; + } + + public Map getKittensByName() { + return kittensByName; + } + + public Cat getMate() { + return mate; + } + + public String getStringAsSimple() { + return stringAsSimple; + } + + public java.sql.Time getTimeField() { + return timeField; + } + + public void setBreed(int breed) { + this.breed = breed; + } + + public void setDateField(java.sql.Date dateField) { + this.dateField = new java.sql.Date(dateField.getTime()); + } + + public void setEyecolor(Color eyecolor) { + this.eyecolor = eyecolor; + } + + public void setKittens(List kittens) { + this.kittens = kittens; + } + + public void setKittensByName(Map kittensByName) { + this.kittensByName = kittensByName; + } + + public void setMate(Cat mate) { + this.mate = mate; + } + + public void setStringAsSimple(String stringAsSimple) { + this.stringAsSimple = stringAsSimple; + } + + public void setTimeField(java.sql.Time timeField) { + this.timeField = timeField; + } + + public Cat[] getKittenArray() { + return kittenArray; + } + + public void setKittenArray(Cat[] kittenArray) { + this.kittenArray = kittenArray.clone(); + } + + public String toString() { + return name; + } } diff --git a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/ClassUtilsTest.java b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/ClassUtilsTest.java index c9a847ec12..fc3895ef6a 100644 --- a/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/ClassUtilsTest.java +++ b/querydsl-codegen-utils/src/test/java/com/querydsl/codegen/utils/support/ClassUtilsTest.java @@ -8,38 +8,43 @@ import static org.junit.Assert.assertEquals; import java.util.*; - import org.junit.Test; + public class ClassUtilsTest { - @Test - public void GetName() { - assertEquals("int", ClassUtils.getName(int.class)); - assertEquals("int", ClassUtils.getName(int.class, Collections. emptySet(), - Collections. emptySet())); - assertEquals("Object", ClassUtils.getName(Object.class)); - assertEquals("Object[]", ClassUtils.getName(Object[].class)); - assertEquals("int", ClassUtils.getName(int.class)); - assertEquals("int[]", ClassUtils.getName(int[].class)); - assertEquals("void", ClassUtils.getName(void.class)); - assertEquals("java.util.Locale", ClassUtils.getName(Locale.class)); - assertEquals("java.util.Locale[]", ClassUtils.getName(Locale[].class)); - } - - @Test - public void GetName_Packge() { - assertEquals("Locale", ClassUtils.getName(Locale.class, - Collections.singleton("java.util"), Collections.emptySet())); - assertEquals("java.util.Locale", ClassUtils.getName(Locale.class, - Collections.singleton("java.util.gen"), Collections.emptySet())); - } + @Test + public void GetName() { + assertEquals("int", ClassUtils.getName(int.class)); + assertEquals( + "int", + ClassUtils.getName( + int.class, Collections.emptySet(), Collections.emptySet())); + assertEquals("Object", ClassUtils.getName(Object.class)); + assertEquals("Object[]", ClassUtils.getName(Object[].class)); + assertEquals("int", ClassUtils.getName(int.class)); + assertEquals("int[]", ClassUtils.getName(int[].class)); + assertEquals("void", ClassUtils.getName(void.class)); + assertEquals("java.util.Locale", ClassUtils.getName(Locale.class)); + assertEquals("java.util.Locale[]", ClassUtils.getName(Locale[].class)); + } - @Test - public void Normalize() { - assertEquals(List.class, ClassUtils.normalize(ArrayList.class)); - assertEquals(Set.class, ClassUtils.normalize(HashSet.class)); - assertEquals(Map.class, ClassUtils.normalize(HashMap.class)); -// assertEquals(Collection.class, ClassUtils.normalize(Bag.class)); - } + @Test + public void GetName_Packge() { + assertEquals( + "Locale", + ClassUtils.getName( + Locale.class, Collections.singleton("java.util"), Collections.emptySet())); + assertEquals( + "java.util.Locale", + ClassUtils.getName( + Locale.class, Collections.singleton("java.util.gen"), Collections.emptySet())); + } + @Test + public void Normalize() { + assertEquals(List.class, ClassUtils.normalize(ArrayList.class)); + assertEquals(Set.class, ClassUtils.normalize(HashSet.class)); + assertEquals(Map.class, ClassUtils.normalize(HashMap.class)); + // assertEquals(Collection.class, ClassUtils.normalize(Bag.class)); + } } diff --git a/querydsl-codegen/pom.xml b/querydsl-codegen/pom.xml index f25388ba17..2b6ef5c8a5 100644 --- a/querydsl-codegen/pom.xml +++ b/querydsl-codegen/pom.xml @@ -1,5 +1,5 @@ - + 4.0.0 @@ -11,17 +11,17 @@ com.querydsl querydsl-codegen + jar Querydsl - Codegen module codegen module for querydsl ${project.homepage} - jar - + ${project.checkout} ${project.checkout} ${project.githubpage} - + com.querydsl @@ -48,27 +48,34 @@ classgraph compile - - + + com.querydsl querydsl-core ${project.version} - test test-jar - - + test + + - + org.apache.felix maven-bundle-plugin - + org.apache.maven.plugins maven-jar-plugin + + + + com.querydsl.codegen + + + test-jar @@ -77,22 +84,15 @@ - - - - com.querydsl.codegen - - - maven-source-plugin - package test-jar + package diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/AbstractModule.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/AbstractModule.java index 7581d6fcff..f8d7938079 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/AbstractModule.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/AbstractModule.java @@ -19,7 +19,6 @@ import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; - import javax.inject.Inject; import javax.inject.Named; @@ -27,148 +26,145 @@ * {@code AbstractModule} provides a base class for annotation based dependency injection * * @author tiwe - * */ public abstract class AbstractModule { - private final Map, Object> instances = new HashMap, Object>(); - - private final Map, Class> bindings = new HashMap, Class>(); - - private final Map namedInstances = new HashMap(); + private final Map, Object> instances = new HashMap, Object>(); - private final Map> namedBindings = new HashMap>(); + private final Map, Class> bindings = new HashMap, Class>(); - public AbstractModule() { - configure(); - } - - public final AbstractModule bind(Class clazz) { - if (clazz.isInterface()) { - throw new IllegalArgumentException("Interfaces can't be instantiated"); - } - bind(clazz, clazz); - return this; - } + private final Map namedInstances = new HashMap(); - public final AbstractModule bind(String name, Class implementation) { - namedBindings.put(name, implementation); - return this; - } + private final Map> namedBindings = new HashMap>(); - public final AbstractModule bind(String name, T implementation) { - namedInstances.put(name, implementation); - return this; - } + public AbstractModule() { + configure(); + } - public final AbstractModule bindInstance(String name, Class implementation) { - namedInstances.put(name, implementation); - return this; + public final AbstractModule bind(Class clazz) { + if (clazz.isInterface()) { + throw new IllegalArgumentException("Interfaces can't be instantiated"); } - - public final AbstractModule bind(Class iface, Class implementation) { - bindings.put(iface, implementation); - return this; + bind(clazz, clazz); + return this; + } + + public final AbstractModule bind(String name, Class implementation) { + namedBindings.put(name, implementation); + return this; + } + + public final AbstractModule bind(String name, T implementation) { + namedInstances.put(name, implementation); + return this; + } + + public final AbstractModule bindInstance(String name, Class implementation) { + namedInstances.put(name, implementation); + return this; + } + + public final AbstractModule bind(Class iface, Class implementation) { + bindings.put(iface, implementation); + return this; + } + + public final AbstractModule bind(Class iface, T implementation) { + instances.put(iface, implementation); + return this; + } + + public final void loadExtensions() { + ServiceLoader loader = + ServiceLoader.load(Extension.class, Extension.class.getClassLoader()); + + for (Extension extension : loader) { + extension.addSupport(this); } - - public final AbstractModule bind(Class iface, T implementation) { - instances.put(iface, implementation); - return this; + } + + protected abstract void configure(); + + @SuppressWarnings("unchecked") + public final T get(Class iface) { + if (instances.containsKey(iface)) { + return (T) instances.get(iface); + } else if (bindings.containsKey(iface)) { + Class implementation = bindings.get(iface); + T instance = (T) createInstance(implementation); + instances.put(iface, instance); + return instance; + } else { + throw new IllegalArgumentException(iface.getName() + " is not registered"); } - - public final void loadExtensions() { - ServiceLoader loader = ServiceLoader.load(Extension.class, Extension.class.getClassLoader()); - - for (Extension extension : loader) { - extension.addSupport(this); - } + } + + @SuppressWarnings("unchecked") + public final T get(Class iface, String name) { + if (namedInstances.containsKey(name)) { + return (T) namedInstances.get(name); + } else if (namedBindings.containsKey(name)) { + Class implementation = namedBindings.get(name); + if (implementation != null) { + T instance = (T) createInstance(implementation); + namedInstances.put(name, instance); + return instance; + } else { + return null; + } + } else { + throw new IllegalArgumentException(iface.getName() + " " + name + " is not registered"); } - - protected abstract void configure(); - - @SuppressWarnings("unchecked") - public final T get(Class iface) { - if (instances.containsKey(iface)) { - return (T) instances.get(iface); - } else if (bindings.containsKey(iface)) { - Class implementation = bindings.get(iface); - T instance = (T) createInstance(implementation); - instances.put(iface, instance); - return instance; - } else { - throw new IllegalArgumentException(iface.getName() + " is not registered"); - } + } + + @SuppressWarnings("unchecked") + private T createInstance(Class implementation) { + Constructor constructor = null; + for (Constructor c : implementation.getConstructors()) { + if (c.isAnnotationPresent(Inject.class)) { + constructor = c; + break; + } } - @SuppressWarnings("unchecked") - public final T get(Class iface, String name) { - if (namedInstances.containsKey(name)) { - return (T) namedInstances.get(name); - } else if (namedBindings.containsKey(name)) { - Class implementation = namedBindings.get(name); - if (implementation != null) { - T instance = (T) createInstance(implementation); - namedInstances.put(name, instance); - return instance; - } else { - return null; - } - } else { - throw new IllegalArgumentException(iface.getName() + " " + name + " is not registered"); - } + // fallback to default constructor + if (constructor == null) { + try { + constructor = implementation.getConstructor(); + } catch (SecurityException | NoSuchMethodException e) { + throw new RuntimeException(e); + } } - @SuppressWarnings("unchecked") - private T createInstance(Class implementation) { - Constructor constructor = null; - for (Constructor c : implementation.getConstructors()) { - if (c.isAnnotationPresent(Inject.class)) { - constructor = c; - break; - } - } - - // fallback to default constructor - if (constructor == null) { - try { - constructor = implementation.getConstructor(); - } catch (SecurityException | NoSuchMethodException e) { - throw new RuntimeException(e); - } - } - - if (constructor != null) { - Object[] args = new Object[constructor.getParameterTypes().length]; - for (int i = 0; i < constructor.getParameterTypes().length; i++) { - Named named = getNamedAnnotation(constructor.getParameterAnnotations()[i]); - if (named != null) { - args[i] = get(constructor.getParameterTypes()[i], named.value()); - } else { - args[i] = get(constructor.getParameterTypes()[i]); - } - } - try { - return (T) constructor.newInstance(args); - // TODO : populate fields as well?!? - } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { - throw new RuntimeException(e); - } - + if (constructor != null) { + Object[] args = new Object[constructor.getParameterTypes().length]; + for (int i = 0; i < constructor.getParameterTypes().length; i++) { + Named named = getNamedAnnotation(constructor.getParameterAnnotations()[i]); + if (named != null) { + args[i] = get(constructor.getParameterTypes()[i], named.value()); } else { - throw new IllegalArgumentException("Got no annotated constructor for " + implementation.getName()); + args[i] = get(constructor.getParameterTypes()[i]); } - + } + try { + return (T) constructor.newInstance(args); + // TODO : populate fields as well?!? + } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { + throw new RuntimeException(e); + } + + } else { + throw new IllegalArgumentException( + "Got no annotated constructor for " + implementation.getName()); } + } - private Named getNamedAnnotation(Annotation[] annotations) { - for (Annotation annotation : annotations) { - if (annotation.annotationType().equals(Named.class)) { - return (Named) annotation; - } - } - return null; + private Named getNamedAnnotation(Annotation[] annotations) { + for (Annotation annotation : annotations) { + if (annotation.annotationType().equals(Named.class)) { + return (Named) annotation; + } } - - - + return null; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/AnnotationHelper.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/AnnotationHelper.java index c61a0fc6f3..8b878c96a2 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/AnnotationHelper.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/AnnotationHelper.java @@ -13,37 +13,39 @@ */ package com.querydsl.codegen; -import java.lang.annotation.Annotation; - import com.querydsl.codegen.utils.model.TypeCategory; +import java.lang.annotation.Annotation; /** - * {@code AnnotationHelper} defines a interface to provide custom annotation processing - * for {@link TypeFactory}. + * {@code AnnotationHelper} defines a interface to provide custom annotation processing for {@link + * TypeFactory}. * * @author dyorgio */ public interface AnnotationHelper { - /** - * Verify if AnnotationHelper instance can handle the annotation. - * @param annotationClass Annotation class. - * @return {@code true} if this AnnotationHelper can handle the annotation. - */ - boolean isSupported(Class annotationClass); + /** + * Verify if AnnotationHelper instance can handle the annotation. + * + * @param annotationClass Annotation class. + * @return {@code true} if this AnnotationHelper can handle the annotation. + */ + boolean isSupported(Class annotationClass); - /** - * Get specific object that will be used as part of type cache key. - * @param annotation Annotation instance. - * @return Any object, normally a annotation param. Can be {@code null}. - */ - Object getCustomKey(Annotation annotation); + /** + * Get specific object that will be used as part of type cache key. + * + * @param annotation Annotation instance. + * @return Any object, normally a annotation param. Can be {@code null}. + */ + Object getCustomKey(Annotation annotation); - /** - * Get the {@link TypeCategory} according with object Class and Annotation. - * @param cl Class of type. - * @param annotation Annotation found on element. - * @return Custom {@link TypeCategory}. - */ - TypeCategory getTypeByAnnotation(Class cl, Annotation annotation); + /** + * Get the {@link TypeCategory} according with object Class and Annotation. + * + * @param cl Class of type. + * @param annotation Annotation found on element. + * @return Custom {@link TypeCategory}. + */ + TypeCategory getTypeByAnnotation(Class cl, Annotation annotation); } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/BeanSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/BeanSerializer.java index 7d4200d2ba..76f1fac6f8 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/BeanSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/BeanSerializer.java @@ -20,9 +20,6 @@ import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.codegen.utils.model.Types; import com.querydsl.core.util.BeanUtils; - -import javax.inject.Inject; -import javax.inject.Named; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; @@ -33,6 +30,8 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; +import javax.inject.Inject; +import javax.inject.Named; /** * {@code BeanSerializer} is a {@link Serializer} implementation which serializes {@link EntityType} @@ -42,264 +41,273 @@ */ public class BeanSerializer implements Serializer { - public static final String DEFAULT_JAVADOC_SUFFIX = " is a Querydsl bean type"; + public static final String DEFAULT_JAVADOC_SUFFIX = " is a Querydsl bean type"; - public static final boolean DEFAULT_PROPERTY_ANNOTATIONS = true; + public static final boolean DEFAULT_PROPERTY_ANNOTATIONS = true; - private static final Function propertyToParameter = new Function() { + private static final Function propertyToParameter = + new Function() { @Override public Parameter apply(Property input) { - return new Parameter(input.getName(), input.getType()); + return new Parameter(input.getName(), input.getType()); } - }; - private final Class generatedAnnotationClass; - - private final boolean propertyAnnotations; - - private final List interfaces = new ArrayList<>(); - - private final String javadocSuffix; - - private boolean addToString, addFullConstructor; - - private boolean printSupertype = false; - - /** - * Create a new BeanSerializer - */ - public BeanSerializer() { - this(DEFAULT_PROPERTY_ANNOTATIONS, DEFAULT_JAVADOC_SUFFIX, GeneratedAnnotationResolver.resolveDefault()); + }; + private final Class generatedAnnotationClass; + + private final boolean propertyAnnotations; + + private final List interfaces = new ArrayList<>(); + + private final String javadocSuffix; + + private boolean addToString, addFullConstructor; + + private boolean printSupertype = false; + + /** Create a new BeanSerializer */ + public BeanSerializer() { + this( + DEFAULT_PROPERTY_ANNOTATIONS, + DEFAULT_JAVADOC_SUFFIX, + GeneratedAnnotationResolver.resolveDefault()); + } + + /** + * Create a new BeanSerializer with the given javadoc suffix + * + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + */ + public BeanSerializer(String javadocSuffix) { + this(DEFAULT_PROPERTY_ANNOTATIONS, javadocSuffix); + } + + /** + * Create a new BeanSerializer with the given javadoc suffix and generatedAnnotationClass + * + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated classes. + * @see Single-Element + * Annotation + */ + @Inject + public BeanSerializer( + @Named(CodegenModule.JAVADOC_SUFFIX) String javadocSuffix, + @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) + Class generatedAnnotationClass) { + this(DEFAULT_PROPERTY_ANNOTATIONS, javadocSuffix, generatedAnnotationClass); + } + + /** + * Create a new BeanSerializer + * + * @param propertyAnnotations true, to serialize property annotations + */ + public BeanSerializer(boolean propertyAnnotations) { + this(propertyAnnotations, DEFAULT_JAVADOC_SUFFIX); + } + + /** + * Create a new BeanSerializer + * + * @param propertyAnnotations true, to serialize property annotations + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + */ + public BeanSerializer(boolean propertyAnnotations, String javadocSuffix) { + this(propertyAnnotations, javadocSuffix, GeneratedAnnotationResolver.resolveDefault()); + } + + /** + * Create a new BeanSerializer + * + * @param propertyAnnotations true, to serialize property annotations + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated classes. * @see + * Single-Element + * Annotation + */ + public BeanSerializer( + boolean propertyAnnotations, + String javadocSuffix, + Class generatedAnnotationClass) { + this.propertyAnnotations = propertyAnnotations; + this.javadocSuffix = javadocSuffix; + this.generatedAnnotationClass = generatedAnnotationClass; + } + + @Override + public void serialize(EntityType model, SerializerConfig serializerConfig, CodeWriter writer) + throws IOException { + String simpleName = model.getSimpleName(); + + // package + if (!model.getPackageName().isEmpty()) { + writer.packageDecl(model.getPackageName()); } - /** - * Create a new BeanSerializer with the given javadoc suffix - * - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - */ - public BeanSerializer(String javadocSuffix) { - this(DEFAULT_PROPERTY_ANNOTATIONS, javadocSuffix); + // imports + Set importedClasses = getAnnotationTypes(model); + for (Type iface : interfaces) { + importedClasses.add(iface.getFullName()); } - - /** - * Create a new BeanSerializer with the given javadoc suffix and generatedAnnotationClass - * - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on the generated classes. - * @see Single-Element Annotation - */ - @Inject - public BeanSerializer( - @Named(CodegenModule.JAVADOC_SUFFIX) String javadocSuffix, - @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) Class generatedAnnotationClass) { - this(DEFAULT_PROPERTY_ANNOTATIONS, javadocSuffix, generatedAnnotationClass); + importedClasses.add(generatedAnnotationClass.getName()); + if (model.hasLists()) { + importedClasses.add(List.class.getName()); } - - /** - * Create a new BeanSerializer - * - * @param propertyAnnotations true, to serialize property annotations - */ - public BeanSerializer(boolean propertyAnnotations) { - this(propertyAnnotations, DEFAULT_JAVADOC_SUFFIX); + if (model.hasCollections()) { + importedClasses.add(Collection.class.getName()); } - - /** - * Create a new BeanSerializer - * - * @param propertyAnnotations true, to serialize property annotations - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - */ - public BeanSerializer(boolean propertyAnnotations, String javadocSuffix) { - this(propertyAnnotations, javadocSuffix, GeneratedAnnotationResolver.resolveDefault()); + if (model.hasSets()) { + importedClasses.add(Set.class.getName()); } - - /** - * Create a new BeanSerializer - * - * @param propertyAnnotations true, to serialize property annotations - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on the generated classes. - * * @see Single-Element Annotation - */ - public BeanSerializer(boolean propertyAnnotations, String javadocSuffix, Class generatedAnnotationClass) { - this.propertyAnnotations = propertyAnnotations; - this.javadocSuffix = javadocSuffix; - this.generatedAnnotationClass = generatedAnnotationClass; + if (model.hasMaps()) { + importedClasses.add(Map.class.getName()); } + if (addToString && model.hasArrays()) { + importedClasses.add(Arrays.class.getName()); + } + writer.importClasses(importedClasses.toArray(new String[0])); - @Override - public void serialize( - EntityType model, SerializerConfig serializerConfig, - CodeWriter writer) throws IOException { - String simpleName = model.getSimpleName(); - - // package - if (!model.getPackageName().isEmpty()) { - writer.packageDecl(model.getPackageName()); - } - - // imports - Set importedClasses = getAnnotationTypes(model); - for (Type iface : interfaces) { - importedClasses.add(iface.getFullName()); - } - importedClasses.add(generatedAnnotationClass.getName()); - if (model.hasLists()) { - importedClasses.add(List.class.getName()); - } - if (model.hasCollections()) { - importedClasses.add(Collection.class.getName()); - } - if (model.hasSets()) { - importedClasses.add(Set.class.getName()); - } - if (model.hasMaps()) { - importedClasses.add(Map.class.getName()); - } - if (addToString && model.hasArrays()) { - importedClasses.add(Arrays.class.getName()); - } - writer.importClasses(importedClasses.toArray(new String[0])); - - // javadoc - writer.javadoc(simpleName + javadocSuffix); - - // header - for (Annotation annotation : model.getAnnotations()) { - writer.annotation(annotation); - } - - writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); - - if (!interfaces.isEmpty()) { - Type superType = null; - if (printSupertype && model.getSuperType() != null) { - superType = model.getSuperType().getType(); - } - Type[] ifaces = interfaces.toArray(new Type[0]); - writer.beginClass(model, superType, ifaces); - } else if (printSupertype && model.getSuperType() != null) { - writer.beginClass(model, model.getSuperType().getType()); - } else { - writer.beginClass(model); - } + // javadoc + writer.javadoc(simpleName + javadocSuffix); + // header + for (Annotation annotation : model.getAnnotations()) { + writer.annotation(annotation); + } - bodyStart(model, writer); + writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); + + if (!interfaces.isEmpty()) { + Type superType = null; + if (printSupertype && model.getSuperType() != null) { + superType = model.getSuperType().getType(); + } + Type[] ifaces = interfaces.toArray(new Type[0]); + writer.beginClass(model, superType, ifaces); + } else if (printSupertype && model.getSuperType() != null) { + writer.beginClass(model, model.getSuperType().getType()); + } else { + writer.beginClass(model); + } - if (addFullConstructor) { - addFullConstructor(model, writer); - } + bodyStart(model, writer); - // fields - for (Property property : model.getProperties()) { - if (propertyAnnotations) { - for (Annotation annotation : property.getAnnotations()) { - writer.annotation(annotation); - } - } - writer.privateField(property.getType(), property.getEscapedName()); - } - - // accessors - for (Property property : model.getProperties()) { - String propertyName = property.getEscapedName(); - // getter - writer.beginPublicMethod(property.getType(), "get" + BeanUtils.capitalize(propertyName)); - writer.line("return ", propertyName, ";"); - writer.end(); - // setter - Parameter parameter = new Parameter(propertyName, property.getType()); - writer.beginPublicMethod(Types.VOID, "set" + BeanUtils.capitalize(propertyName), parameter); - writer.line("this.", propertyName, " = ", propertyName, ";"); - writer.end(); - } + if (addFullConstructor) { + addFullConstructor(model, writer); + } - if (addToString) { - addToString(model, writer); + // fields + for (Property property : model.getProperties()) { + if (propertyAnnotations) { + for (Annotation annotation : property.getAnnotations()) { + writer.annotation(annotation); } + } + writer.privateField(property.getType(), property.getEscapedName()); + } - bodyEnd(model, writer); + // accessors + for (Property property : model.getProperties()) { + String propertyName = property.getEscapedName(); + // getter + writer.beginPublicMethod(property.getType(), "get" + BeanUtils.capitalize(propertyName)); + writer.line("return ", propertyName, ";"); + writer.end(); + // setter + Parameter parameter = new Parameter(propertyName, property.getType()); + writer.beginPublicMethod(Types.VOID, "set" + BeanUtils.capitalize(propertyName), parameter); + writer.line("this.", propertyName, " = ", propertyName, ";"); + writer.end(); + } - writer.end(); + if (addToString) { + addToString(model, writer); } - protected void addFullConstructor(EntityType model, CodeWriter writer) throws IOException { - // public empty constructor - writer.beginConstructor(); - writer.end(); + bodyEnd(model, writer); - // full constructor - writer.beginConstructor(model.getProperties(), propertyToParameter::apply); - for (Property property : model.getProperties()) { - writer.line("this.", property.getEscapedName(), " = ", property.getEscapedName(), ";"); - } - writer.end(); - } + writer.end(); + } - protected void addToString(EntityType model, CodeWriter writer) throws IOException { - writer.line("@Override"); - writer.beginPublicMethod(Types.STRING, "toString"); - StringBuilder builder = new StringBuilder(); - for (Property property : model.getProperties()) { - String propertyName = property.getEscapedName(); - if (builder.length() > 0) { - builder.append(" + \", "); - } else { - builder.append("\""); - } - builder.append(propertyName).append(" = \" + "); - if (property.getType().getCategory() == TypeCategory.ARRAY) { - builder.append("Arrays.toString(").append(propertyName).append(")"); - } else { - builder.append(propertyName); - } - } - writer.line(" return ", builder.toString(), ";"); - writer.end(); - } + protected void addFullConstructor(EntityType model, CodeWriter writer) throws IOException { + // public empty constructor + writer.beginConstructor(); + writer.end(); - protected void bodyStart(EntityType model, CodeWriter writer) throws IOException { - // template method + // full constructor + writer.beginConstructor(model.getProperties(), propertyToParameter::apply); + for (Property property : model.getProperties()) { + writer.line("this.", property.getEscapedName(), " = ", property.getEscapedName(), ";"); } - - protected void bodyEnd(EntityType model, CodeWriter writer) throws IOException { - // template method + writer.end(); + } + + protected void addToString(EntityType model, CodeWriter writer) throws IOException { + writer.line("@Override"); + writer.beginPublicMethod(Types.STRING, "toString"); + StringBuilder builder = new StringBuilder(); + for (Property property : model.getProperties()) { + String propertyName = property.getEscapedName(); + if (builder.length() > 0) { + builder.append(" + \", "); + } else { + builder.append("\""); + } + builder.append(propertyName).append(" = \" + "); + if (property.getType().getCategory() == TypeCategory.ARRAY) { + builder.append("Arrays.toString(").append(propertyName).append(")"); + } else { + builder.append(propertyName); + } } - - private Set getAnnotationTypes(EntityType model) { - Set imports = new HashSet(); - for (Annotation annotation : model.getAnnotations()) { - imports.add(annotation.annotationType().getName()); - } - if (propertyAnnotations) { - for (Property property : model.getProperties()) { - for (Annotation annotation : property.getAnnotations()) { - imports.add(annotation.annotationType().getName()); - } - } - } - return imports; + writer.line(" return ", builder.toString(), ";"); + writer.end(); + } + + protected void bodyStart(EntityType model, CodeWriter writer) throws IOException { + // template method + } + + protected void bodyEnd(EntityType model, CodeWriter writer) throws IOException { + // template method + } + + private Set getAnnotationTypes(EntityType model) { + Set imports = new HashSet(); + for (Annotation annotation : model.getAnnotations()) { + imports.add(annotation.annotationType().getName()); } - - public void addInterface(Class iface) { - interfaces.add(new ClassType(iface)); + if (propertyAnnotations) { + for (Property property : model.getProperties()) { + for (Annotation annotation : property.getAnnotations()) { + imports.add(annotation.annotationType().getName()); + } + } } + return imports; + } - public void addInterface(Type type) { - interfaces.add(type); - } + public void addInterface(Class iface) { + interfaces.add(new ClassType(iface)); + } - public void setAddToString(boolean addToString) { - this.addToString = addToString; - } + public void addInterface(Type type) { + interfaces.add(type); + } - public void setAddFullConstructor(boolean addFullConstructor) { - this.addFullConstructor = addFullConstructor; - } + public void setAddToString(boolean addToString) { + this.addToString = addToString; + } - public void setPrintSupertype(boolean printSupertype) { - this.printSupertype = printSupertype; - } + public void setAddFullConstructor(boolean addFullConstructor) { + this.addFullConstructor = addFullConstructor; + } + public void setPrintSupertype(boolean printSupertype) { + this.printSupertype = printSupertype; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/ClassPathUtils.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/ClassPathUtils.java index 803d87adb2..724b5a65ad 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/ClassPathUtils.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/ClassPathUtils.java @@ -14,7 +14,6 @@ package com.querydsl.codegen; import io.github.classgraph.ClassGraph; - import java.io.IOException; import java.util.Set; import java.util.stream.Collectors; @@ -26,56 +25,57 @@ */ public final class ClassPathUtils { - /** - * Return the classes from the given package and subpackages using the supplied classloader - * - * @param classLoader classloader to be used - * @param pkg package to scan - * @return set of found classes - * @throws IOException - */ - public static Set> scanPackage(ClassLoader classLoader, Package pkg) throws IOException { - return scanPackage(classLoader, pkg.getName()); - } + /** + * Return the classes from the given package and subpackages using the supplied classloader + * + * @param classLoader classloader to be used + * @param pkg package to scan + * @return set of found classes + * @throws IOException + */ + public static Set> scanPackage(ClassLoader classLoader, Package pkg) throws IOException { + return scanPackage(classLoader, pkg.getName()); + } - /** - * Return the classes from the given package and subpackages using the supplied classloader - * - * @param classLoader classloader to be used - * @param pkg package to scan - * @return set of found classes - * @throws IOException - */ - public static Set> scanPackage(ClassLoader classLoader, String pkg) throws IOException { - return new ClassGraph() - .enableClassInfo() - .acceptPackages(pkg) - .rejectPackages("com.sun", "com.apple") - .overrideClassLoaders(classLoader) - .scan() - .getAllClasses() - .stream().map(info -> safeClassForName(classLoader, info.getName())) - .collect(Collectors.toSet()); - } + /** + * Return the classes from the given package and subpackages using the supplied classloader + * + * @param classLoader classloader to be used + * @param pkg package to scan + * @return set of found classes + * @throws IOException + */ + public static Set> scanPackage(ClassLoader classLoader, String pkg) throws IOException { + return new ClassGraph() + .enableClassInfo() + .acceptPackages(pkg) + .rejectPackages("com.sun", "com.apple") + .overrideClassLoaders(classLoader) + .scan() + .getAllClasses() + .stream() + .map(info -> safeClassForName(classLoader, info.getName())) + .collect(Collectors.toSet()); + } - /** - * Get the class for the given className via the given classLoader - * - * @param classLoader classloader to be used - * @param className fully qualified class name - * @return {@code Class} instance matching the class name or null if not found - */ - public static Class safeClassForName(ClassLoader classLoader, String className) { - try { - if (className.startsWith("com.sun.") || className.startsWith("com.apple.")) { - return null; - } else { - return Class.forName(className, true, classLoader); - } - } catch (ClassNotFoundException | NoClassDefFoundError e) { - return null; - } + /** + * Get the class for the given className via the given classLoader + * + * @param classLoader classloader to be used + * @param className fully qualified class name + * @return {@code Class} instance matching the class name or null if not found + */ + public static Class safeClassForName(ClassLoader classLoader, String className) { + try { + if (className.startsWith("com.sun.") || className.startsWith("com.apple.")) { + return null; + } else { + return Class.forName(className, true, classLoader); + } + } catch (ClassNotFoundException | NoClassDefFoundError e) { + return null; } + } - private ClassPathUtils() { } + private ClassPathUtils() {} } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/CodegenModule.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/CodegenModule.java index 4bd5bd7698..47fc5c5b09 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/CodegenModule.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/CodegenModule.java @@ -21,67 +21,54 @@ * {@code CodegenModule} provides a module for general serialization * * @author tiwe - * */ -public class CodegenModule extends AbstractModule { - - /** - * key for the query type name prefix - */ - public static final String PREFIX = "prefix"; +public class CodegenModule extends AbstractModule { - /** - * key for the query type name suffix - */ - public static final String SUFFIX = "suffix"; + /** key for the query type name prefix */ + public static final String PREFIX = "prefix"; - /** - * key for the keywords set - */ - public static final String KEYWORDS = "keywords"; + /** key for the query type name suffix */ + public static final String SUFFIX = "suffix"; - /** - * key for the package suffix - */ - public static final String PACKAGE_SUFFIX = "packageSuffix"; + /** key for the keywords set */ + public static final String KEYWORDS = "keywords"; - /** - * key for the custom imports set - */ - public static final String IMPORTS = "imports"; + /** key for the package suffix */ + public static final String PACKAGE_SUFFIX = "packageSuffix"; - /** - * key for the variable name function class - */ - public static final String VARIABLE_NAME_FUNCTION_CLASS = "variableNameFunction"; + /** key for the custom imports set */ + public static final String IMPORTS = "imports"; - /** - * the fully qualified class name of the Single-Element Annotation (with {@code String} element) - * to indicate that these have been generated. Defaults to java's {@code Generated} annotation (depending on java version) - */ - public static final String GENERATED_ANNOTATION_CLASS = "generatedAnnotationClass"; + /** key for the variable name function class */ + public static final String VARIABLE_NAME_FUNCTION_CLASS = "variableNameFunction"; - protected static final String JAVADOC_SUFFIX = "javadocSuffix"; + /** + * the fully qualified class name of the Single-Element Annotation (with {@code String} + * element) to indicate that these have been generated. Defaults to java's {@code Generated} + * annotation (depending on java version) + */ + public static final String GENERATED_ANNOTATION_CLASS = "generatedAnnotationClass"; - @Override - protected void configure() { - bind(TypeMappings.class, JavaTypeMappings.class); - bind(QueryTypeFactory.class, QueryTypeFactoryImpl.class); - bind(EntitySerializer.class, DefaultEntitySerializer.class); - bind(EmbeddableSerializer.class, DefaultEmbeddableSerializer.class); - bind(ProjectionSerializer.class, DefaultProjectionSerializer.class); - bind(SupertypeSerializer.class, DefaultSupertypeSerializer.class); - bind(Filer.class, DefaultFiler.class); + protected static final String JAVADOC_SUFFIX = "javadocSuffix"; - // configuration for QueryTypeFactory - bind(PREFIX, "Q"); - bind(SUFFIX, ""); - bind(PACKAGE_SUFFIX, ""); - bind(KEYWORDS, Collections.emptySet()); - bind(IMPORTS, Collections.emptySet()); - bind(VARIABLE_NAME_FUNCTION_CLASS, DefaultVariableNameFunction.INSTANCE); - bindInstance(GENERATED_ANNOTATION_CLASS, GeneratedAnnotationResolver.resolveDefault()); - bind(JAVADOC_SUFFIX, DEFAULT_JAVADOC_SUFFIX); - } + @Override + protected void configure() { + bind(TypeMappings.class, JavaTypeMappings.class); + bind(QueryTypeFactory.class, QueryTypeFactoryImpl.class); + bind(EntitySerializer.class, DefaultEntitySerializer.class); + bind(EmbeddableSerializer.class, DefaultEmbeddableSerializer.class); + bind(ProjectionSerializer.class, DefaultProjectionSerializer.class); + bind(SupertypeSerializer.class, DefaultSupertypeSerializer.class); + bind(Filer.class, DefaultFiler.class); + // configuration for QueryTypeFactory + bind(PREFIX, "Q"); + bind(SUFFIX, ""); + bind(PACKAGE_SUFFIX, ""); + bind(KEYWORDS, Collections.emptySet()); + bind(IMPORTS, Collections.emptySet()); + bind(VARIABLE_NAME_FUNCTION_CLASS, DefaultVariableNameFunction.INSTANCE); + bindInstance(GENERATED_ANNOTATION_CLASS, GeneratedAnnotationResolver.resolveDefault()); + bind(JAVADOC_SUFFIX, DEFAULT_JAVADOC_SUFFIX); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEmbeddableSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEmbeddableSerializer.java index 819c18147e..e907447635 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEmbeddableSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEmbeddableSerializer.java @@ -15,13 +15,6 @@ import static com.querydsl.codegen.utils.Symbols.UNCHECKED; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.Collection; - -import javax.inject.Inject; -import javax.inject.Named; - import com.querydsl.codegen.utils.CodeWriter; import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.Type; @@ -29,80 +22,103 @@ import com.querydsl.codegen.utils.model.Types; import com.querydsl.core.types.Path; import com.querydsl.core.types.dsl.*; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.util.Collection; +import javax.inject.Inject; +import javax.inject.Named; /** * {@code EmbeddableSerializer} is a {@link Serializer} implementation for embeddable types * * @author tiwe - * */ -public final class DefaultEmbeddableSerializer extends DefaultEntitySerializer implements EmbeddableSerializer { +public final class DefaultEmbeddableSerializer extends DefaultEntitySerializer + implements EmbeddableSerializer { - /** - * Create a new {@code EmbeddableSerializer} instance - * - * @param typeMappings type mappings to be used - * @param keywords keywords to be used - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on the generated classes. - * @see Single-Element Annotation - */ - @Inject - public DefaultEmbeddableSerializer( - TypeMappings typeMappings, - @Named(CodegenModule.KEYWORDS) Collection keywords, - @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) Class generatedAnnotationClass) { - super(typeMappings, keywords, generatedAnnotationClass); - } + /** + * Create a new {@code EmbeddableSerializer} instance + * + * @param typeMappings type mappings to be used + * @param keywords keywords to be used + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated classes. + * @see Single-Element + * Annotation + */ + @Inject + public DefaultEmbeddableSerializer( + TypeMappings typeMappings, + @Named(CodegenModule.KEYWORDS) Collection keywords, + @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) + Class generatedAnnotationClass) { + super(typeMappings, keywords, generatedAnnotationClass); + } - /** - * Create a new {@code EmbeddableSerializer} instance. - * - * @param typeMappings type mappings to be used - * @param keywords keywords to be used - */ - public DefaultEmbeddableSerializer( - TypeMappings typeMappings, - Collection keywords) { - this(typeMappings, keywords, GeneratedAnnotationResolver.resolveDefault()); - } - - @Override - @SuppressWarnings(UNCHECKED) - protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { - Type queryType = typeMappings.getPathType(model, model, true); + /** + * Create a new {@code EmbeddableSerializer} instance. + * + * @param typeMappings type mappings to be used + * @param keywords keywords to be used + */ + public DefaultEmbeddableSerializer(TypeMappings typeMappings, Collection keywords) { + this(typeMappings, keywords, GeneratedAnnotationResolver.resolveDefault()); + } - TypeCategory category = model.getOriginalCategory(); - Class pathType; - if (model.getProperties().isEmpty()) { - switch (category) { - case COMPARABLE : pathType = ComparablePath.class; break; - case ENUM: pathType = EnumPath.class; break; - case DATE: pathType = DatePath.class; break; - case DATETIME: pathType = DateTimePath.class; break; - case TIME: pathType = TimePath.class; break; - case NUMERIC: pathType = NumberPath.class; break; - case STRING: pathType = StringPath.class; break; - case BOOLEAN: pathType = BooleanPath.class; break; - default : pathType = BeanPath.class; - } - } else { - pathType = BeanPath.class; - } + @Override + @SuppressWarnings(UNCHECKED) + protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { + Type queryType = typeMappings.getPathType(model, model, true); - for (Annotation annotation : model.getAnnotations()) { - writer.annotation(annotation); - } + TypeCategory category = model.getOriginalCategory(); + Class pathType; + if (model.getProperties().isEmpty()) { + switch (category) { + case COMPARABLE: + pathType = ComparablePath.class; + break; + case ENUM: + pathType = EnumPath.class; + break; + case DATE: + pathType = DatePath.class; + break; + case DATETIME: + pathType = DateTimePath.class; + break; + case TIME: + pathType = TimePath.class; + break; + case NUMERIC: + pathType = NumberPath.class; + break; + case STRING: + pathType = StringPath.class; + break; + case BOOLEAN: + pathType = BooleanPath.class; + break; + default: + pathType = BeanPath.class; + } + } else { + pathType = BeanPath.class; + } - writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); + for (Annotation annotation : model.getAnnotations()) { + writer.annotation(annotation); + } - if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING) { - writer.beginClass(queryType, new ClassType(pathType)); - } else { - writer.beginClass(queryType, new ClassType(category, pathType, model)); - } + writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); - // TODO : generate proper serialVersionUID here - writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", model.hashCode() + "L"); + if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING) { + writer.beginClass(queryType, new ClassType(pathType)); + } else { + writer.beginClass(queryType, new ClassType(category, pathType, model)); } + // TODO : generate proper serialVersionUID here + writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", model.hashCode() + "L"); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEntitySerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEntitySerializer.java index 1dbe0b7955..aae22a0f0d 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEntitySerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultEntitySerializer.java @@ -15,833 +15,1005 @@ import static com.querydsl.codegen.utils.Symbols.*; +import com.querydsl.codegen.utils.CodeWriter; +import com.querydsl.codegen.utils.model.*; +import com.querydsl.core.types.*; +import com.querydsl.core.types.dsl.*; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.*; import java.util.function.Function; - import javax.inject.Inject; import javax.inject.Named; -import com.querydsl.codegen.utils.CodeWriter; -import com.querydsl.codegen.utils.model.*; -import com.querydsl.core.types.*; -import com.querydsl.core.types.dsl.*; - /** * {@code EntitySerializer} is a {@link Serializer} implementation for entity types * * @author tiwe - * */ public class DefaultEntitySerializer implements EntitySerializer { - private static final Parameter PATH_METADATA = new Parameter("metadata", new ClassType(PathMetadata.class)); - - private static final Parameter PATH_INITS = new Parameter("inits", new ClassType(PathInits.class)); - - private static final ClassType PATH_INITS_TYPE = new ClassType(PathInits.class); - - protected final TypeMappings typeMappings; - - protected final Collection keywords; - - protected final Class generatedAnnotationClass; - - /** - * Create a new {@code EntitySerializer} instance - * - * @param mappings type mappings to be used - * @param keywords keywords to be used - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on the generated classes. - * @see Single-Element Annotation - */ - @Inject - public DefaultEntitySerializer( - TypeMappings mappings, - @Named(CodegenModule.KEYWORDS) Collection keywords, - @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) Class generatedAnnotationClass) { - this.typeMappings = mappings; - this.keywords = keywords; - this.generatedAnnotationClass = generatedAnnotationClass; - } - - /** - * Create a new {@code EntitySerializer} instance - * - * @param mappings type mappings to be used - * @param keywords keywords to be used - */ - public DefaultEntitySerializer(TypeMappings mappings, Collection keywords) { - this(mappings, keywords, GeneratedAnnotationResolver.resolveDefault()); - } - - private boolean superTypeHasEntityFields(EntityType model) { - Supertype superType = model.getSuperType(); - return null != superType && null != superType.getEntityType() - && superType.getEntityType().hasEntityFields(); - } - - protected void constructors(EntityType model, SerializerConfig config, - CodeWriter writer) throws IOException { - - String localName = writer.getRawName(model); - String genericName = writer.getGenericName(true, model); - - boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); - boolean stringOrBoolean = model.getOriginalCategory() == TypeCategory.STRING - || model.getOriginalCategory() == TypeCategory.BOOLEAN; - String thisOrSuper = hasEntityFields ? THIS : SUPER; - String additionalParams = getAdditionalConstructorParameter(model); - String classCast = localName.equals(genericName) ? EMPTY : "(Class) "; - - - // String - constructorsForVariables(writer, model); - - // Path - if (!localName.equals(genericName)) { - suppressAllWarnings(writer); - } - Type simpleModel = new SimpleType(model); - if (model.isFinal()) { - Type type = new ClassType(Path.class, simpleModel); - writer.beginConstructor(new Parameter("path", type)); - } else { - Type type = new ClassType(Path.class, new TypeExtends(simpleModel)); - writer.beginConstructor(new Parameter("path", type)); - } - - if (!hasEntityFields) { - if (stringOrBoolean) { - writer.line("super(path.getMetadata());"); - } else { - writer.line("super(", classCast, "path.getType(), path.getMetadata()" + additionalParams + ");"); - } - constructorContent(writer, model); - } else { - writer.line("this(", classCast, "path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));"); - } - writer.end(); - - // PathMetadata - if (hasEntityFields) { - writer.beginConstructor(PATH_METADATA); - writer.line("this(metadata, PathInits.getFor(metadata, INITS));"); - writer.end(); - } else { - if (!localName.equals(genericName)) { - suppressAllWarnings(writer); - } - writer.beginConstructor(PATH_METADATA); - if (stringOrBoolean) { - writer.line("super(metadata);"); - } else { - writer.line("super(", classCast, writer.getClassConstant(localName) + COMMA + "metadata" + additionalParams + ");"); - } - constructorContent(writer, model); - writer.end(); - } - - // PathMetadata, PathInits - if (hasEntityFields) { - if (!localName.equals(genericName)) { - suppressAllWarnings(writer); - } - writer.beginConstructor(PATH_METADATA, PATH_INITS); - writer.line(thisOrSuper, "(", classCast, writer.getClassConstant(localName) + COMMA + "metadata, inits" + additionalParams + ");"); - if (!hasEntityFields) { - constructorContent(writer, model); + private static final Parameter PATH_METADATA = + new Parameter("metadata", new ClassType(PathMetadata.class)); + + private static final Parameter PATH_INITS = + new Parameter("inits", new ClassType(PathInits.class)); + + private static final ClassType PATH_INITS_TYPE = new ClassType(PathInits.class); + + protected final TypeMappings typeMappings; + + protected final Collection keywords; + + protected final Class generatedAnnotationClass; + + /** + * Create a new {@code EntitySerializer} instance + * + * @param mappings type mappings to be used + * @param keywords keywords to be used + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated classes. + * @see Single-Element + * Annotation + */ + @Inject + public DefaultEntitySerializer( + TypeMappings mappings, + @Named(CodegenModule.KEYWORDS) Collection keywords, + @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) + Class generatedAnnotationClass) { + this.typeMappings = mappings; + this.keywords = keywords; + this.generatedAnnotationClass = generatedAnnotationClass; + } + + /** + * Create a new {@code EntitySerializer} instance + * + * @param mappings type mappings to be used + * @param keywords keywords to be used + */ + public DefaultEntitySerializer(TypeMappings mappings, Collection keywords) { + this(mappings, keywords, GeneratedAnnotationResolver.resolveDefault()); + } + + private boolean superTypeHasEntityFields(EntityType model) { + Supertype superType = model.getSuperType(); + return null != superType + && null != superType.getEntityType() + && superType.getEntityType().hasEntityFields(); + } + + protected void constructors(EntityType model, SerializerConfig config, CodeWriter writer) + throws IOException { + + String localName = writer.getRawName(model); + String genericName = writer.getGenericName(true, model); + + boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); + boolean stringOrBoolean = + model.getOriginalCategory() == TypeCategory.STRING + || model.getOriginalCategory() == TypeCategory.BOOLEAN; + String thisOrSuper = hasEntityFields ? THIS : SUPER; + String additionalParams = getAdditionalConstructorParameter(model); + String classCast = localName.equals(genericName) ? EMPTY : "(Class) "; + + // String + constructorsForVariables(writer, model); + + // Path + if (!localName.equals(genericName)) { + suppressAllWarnings(writer); + } + Type simpleModel = new SimpleType(model); + if (model.isFinal()) { + Type type = new ClassType(Path.class, simpleModel); + writer.beginConstructor(new Parameter("path", type)); + } else { + Type type = new ClassType(Path.class, new TypeExtends(simpleModel)); + writer.beginConstructor(new Parameter("path", type)); + } + + if (!hasEntityFields) { + if (stringOrBoolean) { + writer.line("super(path.getMetadata());"); + } else { + writer.line( + "super(", classCast, "path.getType(), path.getMetadata()" + additionalParams + ");"); + } + constructorContent(writer, model); + } else { + writer.line( + "this(", + classCast, + "path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));"); + } + writer.end(); + + // PathMetadata + if (hasEntityFields) { + writer.beginConstructor(PATH_METADATA); + writer.line("this(metadata, PathInits.getFor(metadata, INITS));"); + writer.end(); + } else { + if (!localName.equals(genericName)) { + suppressAllWarnings(writer); + } + writer.beginConstructor(PATH_METADATA); + if (stringOrBoolean) { + writer.line("super(metadata);"); + } else { + writer.line( + "super(", + classCast, + writer.getClassConstant(localName) + COMMA + "metadata" + additionalParams + ");"); + } + constructorContent(writer, model); + writer.end(); + } + + // PathMetadata, PathInits + if (hasEntityFields) { + if (!localName.equals(genericName)) { + suppressAllWarnings(writer); + } + writer.beginConstructor(PATH_METADATA, PATH_INITS); + writer.line( + thisOrSuper, + "(", + classCast, + writer.getClassConstant(localName) + COMMA + "metadata, inits" + additionalParams + ");"); + if (!hasEntityFields) { + constructorContent(writer, model); + } + writer.end(); + } + + // Class, PathMetadata, PathInits + if (hasEntityFields) { + Type type = new ClassType(Class.class, new TypeExtends(model)); + writer.beginConstructor(new Parameter("type", type), PATH_METADATA, PATH_INITS); + writer.line("super(type, metadata, inits" + additionalParams + ");"); + initEntityFields(writer, config, model); + constructorContent(writer, model); + writer.end(); + } + } + + protected void constructorContent(CodeWriter writer, EntityType model) throws IOException { + // override in subclasses + } + + protected String getAdditionalConstructorParameter(EntityType model) { + return ""; + } + + protected void constructorsForVariables(CodeWriter writer, EntityType model) throws IOException { + String localName = writer.getRawName(model); + String genericName = writer.getGenericName(true, model); + + boolean stringOrBoolean = + model.getOriginalCategory() == TypeCategory.STRING + || model.getOriginalCategory() == TypeCategory.BOOLEAN; + boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); + String thisOrSuper = hasEntityFields ? THIS : SUPER; + String additionalParams = hasEntityFields ? "" : getAdditionalConstructorParameter(model); + + if (!localName.equals(genericName)) { + suppressAllWarnings(writer); + } + writer.beginConstructor(new Parameter("variable", Types.STRING)); + if (stringOrBoolean) { + writer.line(thisOrSuper, "(forVariable(variable)", additionalParams, ");"); + } else { + writer.line( + thisOrSuper, + "(", + localName.equals(genericName) ? EMPTY : "(Class) ", + writer.getClassConstant(localName) + COMMA + "forVariable(variable)", + hasEntityFields ? ", INITS" : EMPTY, + additionalParams, + ");"); + } + if (!hasEntityFields) { + constructorContent(writer, model); + } + writer.end(); + } + + protected void entityAccessor(EntityType model, Property field, CodeWriter writer) + throws IOException { + Type queryType = typeMappings.getPathType(field.getType(), model, false); + writer.beginPublicMethod(queryType, field.getEscapedName()); + writer.line("if (", field.getEscapedName(), " == null) {"); + writer.line( + " ", + field.getEscapedName(), + " = new ", + writer.getRawName(queryType), + "(forProperty(\"", + field.getName(), + "\"));"); + writer.line("}"); + writer.line(RETURN, field.getEscapedName(), SEMICOLON); + writer.end(); + } + + protected void entityField( + EntityType model, Property field, SerializerConfig config, CodeWriter writer) + throws IOException { + Type queryType = typeMappings.getPathType(field.getType(), model, false); + if (field.isInherited()) { + writer.line("// inherited"); + } + if (config.useEntityAccessors()) { + writer.protectedField(queryType, field.getEscapedName()); + } else { + writer.publicFinal(queryType, field.getEscapedName()); + } + } + + protected boolean hasOwnEntityProperties(EntityType model) { + if (model.hasEntityFields()) { + for (Property property : model.getProperties()) { + if (!property.isInherited() && property.getType().getCategory() == TypeCategory.ENTITY) { + return true; + } + } + } + return false; + } + + protected void initEntityFields(CodeWriter writer, SerializerConfig config, EntityType model) + throws IOException { + Supertype superType = model.getSuperType(); + if (superType != null) { + EntityType entityType = superType.getEntityType(); + if (entityType != null && entityType.hasEntityFields()) { + Type superQueryType = typeMappings.getPathType(entityType, model, false); + writer.line( + "this._super = new " + writer.getRawName(superQueryType) + "(type, metadata, inits);"); + } + } + + for (Property field : model.getProperties()) { + if (field.getType().getCategory() == TypeCategory.ENTITY) { + initEntityField(writer, config, model, field); + + } else if (field.isInherited() + && superType != null + && superType.getEntityType().hasEntityFields()) { + writer.line( + "this.", field.getEscapedName(), " = _super.", field.getEscapedName(), SEMICOLON); + } + } + } + + protected void initEntityField( + CodeWriter writer, SerializerConfig config, EntityType model, Property field) + throws IOException { + Type queryType = typeMappings.getPathType(field.getType(), model, false); + if (!field.isInherited()) { + boolean hasEntityFields = + field.getType() instanceof EntityType && ((EntityType) field.getType()).hasEntityFields(); + writer.line( + "this." + field.getEscapedName() + ASSIGN, + "inits.isInitialized(\"" + field.getName() + "\") ? ", + NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\")", + hasEntityFields ? (", inits.get(\"" + field.getName() + "\")") : EMPTY, + ") : null;"); + } else if (!config.useEntityAccessors()) { + writer.line( + "this.", field.getEscapedName(), ASSIGN, "_super.", field.getEscapedName(), SEMICOLON); + } + } + + protected void intro(EntityType model, SerializerConfig config, CodeWriter writer) + throws IOException { + introPackage(writer, model); + introImports(writer, config, model); + + writer.nl(); + + introJavadoc(writer, model); + introClassHeader(writer, model); + + introFactoryMethods(writer, model); + introInits(writer, model); + if (config.createDefaultVariable()) { + introDefaultInstance(writer, model, config.defaultVariableName()); + } + if (model.getSuperType() != null && model.getSuperType().getEntityType() != null) { + introSuper(writer, model); + } + } + + @SuppressWarnings(UNCHECKED) + protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { + Type queryType = typeMappings.getPathType(model, model, true); + + TypeCategory category = model.getOriginalCategory(); + Class pathType; + + if (model.getProperties().isEmpty()) { + switch (category) { + case COMPARABLE: + pathType = ComparablePath.class; + break; + case ENUM: + pathType = EnumPath.class; + break; + case DATE: + pathType = DatePath.class; + break; + case DATETIME: + pathType = DateTimePath.class; + break; + case TIME: + pathType = TimePath.class; + break; + case NUMERIC: + pathType = NumberPath.class; + break; + case STRING: + pathType = StringPath.class; + break; + case BOOLEAN: + pathType = BooleanPath.class; + break; + default: + pathType = EntityPathBase.class; + } + } else { + pathType = EntityPathBase.class; + } + + for (Annotation annotation : model.getAnnotations()) { + writer.annotation(annotation); + } + + writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); + + if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING) { + writer.beginClass(queryType, new ClassType(pathType)); + } else { + writer.beginClass(queryType, new ClassType(category, pathType, model)); + } + + // TODO : generate proper serialVersionUID here + long serialVersionUID = model.getFullName().hashCode(); + writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", serialVersionUID + "L"); + } + + protected void introDefaultInstance(CodeWriter writer, EntityType model, String defaultName) + throws IOException { + String simpleName = !defaultName.isEmpty() ? defaultName : model.getModifiedSimpleName(); + Type queryType = typeMappings.getPathType(model, model, true); + String alias = simpleName; + if (keywords.contains(simpleName.toUpperCase())) { + alias += "1"; + } + writer.publicStaticFinal( + queryType, simpleName, NEW + queryType.getSimpleName() + "(\"" + alias + "\")"); + } + + protected void introFactoryMethods(CodeWriter writer, final EntityType model) throws IOException { + String localName = writer.getRawName(model); + String genericName = writer.getGenericName(true, model); + Set sizes = new HashSet<>(); + + for (Constructor c : model.getConstructors()) { + // begin + if (!localName.equals(genericName)) { + writer.suppressWarnings(UNCHECKED); + } + Type returnType = new ClassType(ConstructorExpression.class, model); + final boolean asExpr = sizes.add(c.getParameters().size()); + writer.beginStaticMethod( + returnType, + "create", + c.getParameters(), + new Function() { + @Override + public Parameter apply(Parameter p) { + Type type; + if (!asExpr) { + type = typeMappings.getExprType(p.getType(), model, false, false, true); + } else if (p.getType().isFinal()) { + type = new ClassType(Expression.class, p.getType()); + } else { + type = new ClassType(Expression.class, new TypeExtends(p.getType())); + } + return new Parameter(p.getName(), type); } - writer.end(); - } - - // Class, PathMetadata, PathInits - if (hasEntityFields) { - Type type = new ClassType(Class.class, new TypeExtends(model)); - writer.beginConstructor(new Parameter("type", type), PATH_METADATA, PATH_INITS); - writer.line("super(type, metadata, inits" + additionalParams + ");"); - initEntityFields(writer, config, model); - constructorContent(writer, model); - writer.end(); - } - - } - - protected void constructorContent(CodeWriter writer, EntityType model) throws IOException { - // override in subclasses - } - - protected String getAdditionalConstructorParameter(EntityType model) { - return ""; - } - - protected void constructorsForVariables(CodeWriter writer, EntityType model) throws IOException { - String localName = writer.getRawName(model); - String genericName = writer.getGenericName(true, model); - - boolean stringOrBoolean = model.getOriginalCategory() == TypeCategory.STRING - || model.getOriginalCategory() == TypeCategory.BOOLEAN; - boolean hasEntityFields = model.hasEntityFields() || superTypeHasEntityFields(model); - String thisOrSuper = hasEntityFields ? THIS : SUPER; - String additionalParams = hasEntityFields ? "" : getAdditionalConstructorParameter(model); - - if (!localName.equals(genericName)) { - suppressAllWarnings(writer); - } - writer.beginConstructor(new Parameter("variable", Types.STRING)); - if (stringOrBoolean) { - writer.line(thisOrSuper,"(forVariable(variable)",additionalParams,");"); + }); + + // body + // TODO : replace with class reference + writer.beginLine("return Projections.constructor("); + // if (!localName.equals(genericName)) { + // writer.append("(Class)"); + // } + writer.append(writer.getClassConstant(localName)); + writer.append(", new Class[]{"); + boolean first = true; + for (Parameter p : c.getParameters()) { + if (!first) { + writer.append(COMMA); + } + if (Types.PRIMITIVES.containsKey(p.getType())) { + Type primitive = Types.PRIMITIVES.get(p.getType()); + writer.append(writer.getClassConstant(primitive.getFullName())); } else { - writer.line(thisOrSuper,"(", localName.equals(genericName) ? EMPTY : "(Class) ", - writer.getClassConstant(localName) + COMMA + "forVariable(variable)", hasEntityFields ? ", INITS" : EMPTY, - additionalParams,");"); - } - if (!hasEntityFields) { - constructorContent(writer, model); - } - writer.end(); - } - - protected void entityAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { - Type queryType = typeMappings.getPathType(field.getType(), model, false); - writer.beginPublicMethod(queryType, field.getEscapedName()); - writer.line("if (", field.getEscapedName(), " == null) {"); - writer.line(" ", field.getEscapedName(), " = new ", writer.getRawName(queryType), - "(forProperty(\"", field.getName(), "\"));"); - writer.line("}"); - writer.line(RETURN, field.getEscapedName(), SEMICOLON); - writer.end(); - } - - protected void entityField(EntityType model, Property field, SerializerConfig config, - CodeWriter writer) throws IOException { - Type queryType = typeMappings.getPathType(field.getType(), model, false); - if (field.isInherited()) { - writer.line("// inherited"); - } - if (config.useEntityAccessors()) { - writer.protectedField(queryType, field.getEscapedName()); - } else { - writer.publicFinal(queryType, field.getEscapedName()); - } - } - - protected boolean hasOwnEntityProperties(EntityType model) { - if (model.hasEntityFields()) { - for (Property property : model.getProperties()) { - if (!property.isInherited() && property.getType().getCategory() == TypeCategory.ENTITY) { - return true; - } - } - } - return false; - } - - protected void initEntityFields(CodeWriter writer, SerializerConfig config, - EntityType model) throws IOException { - Supertype superType = model.getSuperType(); - if (superType != null) { - EntityType entityType = superType.getEntityType(); - if (entityType != null && entityType.hasEntityFields()) { - Type superQueryType = typeMappings.getPathType(entityType, model, false); - writer.line("this._super = new " + writer.getRawName(superQueryType) + "(type, metadata, inits);"); - } - } - - for (Property field : model.getProperties()) { - if (field.getType().getCategory() == TypeCategory.ENTITY) { - initEntityField(writer, config, model, field); - - } else if (field.isInherited() && superType != null && superType.getEntityType().hasEntityFields()) { - writer.line("this.", field.getEscapedName(), " = _super.", field.getEscapedName(), SEMICOLON); - } - } - } - - protected void initEntityField(CodeWriter writer, SerializerConfig config, EntityType model, - Property field) throws IOException { - Type queryType = typeMappings.getPathType(field.getType(), model, false); - if (!field.isInherited()) { - boolean hasEntityFields = field.getType() instanceof EntityType - && ((EntityType) field.getType()).hasEntityFields(); - writer.line("this." + field.getEscapedName() + ASSIGN, - "inits.isInitialized(\"" + field.getName() + "\") ? ", - NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\")", - hasEntityFields ? (", inits.get(\"" + field.getName() + "\")") : EMPTY, - ") : null;"); - } else if (!config.useEntityAccessors()) { - writer.line("this.", field.getEscapedName(), ASSIGN, "_super.", field.getEscapedName(), SEMICOLON); - } - } - - protected void intro(EntityType model, SerializerConfig config, - CodeWriter writer) throws IOException { - introPackage(writer, model); - introImports(writer, config, model); - - writer.nl(); - - introJavadoc(writer, model); - introClassHeader(writer, model); - - introFactoryMethods(writer, model); - introInits(writer, model); - if (config.createDefaultVariable()) { - introDefaultInstance(writer, model, config.defaultVariableName()); - } - if (model.getSuperType() != null && model.getSuperType().getEntityType() != null) { - introSuper(writer, model); - } - } - - @SuppressWarnings(UNCHECKED) - protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { - Type queryType = typeMappings.getPathType(model, model, true); - - TypeCategory category = model.getOriginalCategory(); - Class pathType; - - if (model.getProperties().isEmpty()) { - switch (category) { - case COMPARABLE : pathType = ComparablePath.class; break; - case ENUM: pathType = EnumPath.class; break; - case DATE: pathType = DatePath.class; break; - case DATETIME: pathType = DateTimePath.class; break; - case TIME: pathType = TimePath.class; break; - case NUMERIC: pathType = NumberPath.class; break; - case STRING: pathType = StringPath.class; break; - case BOOLEAN: pathType = BooleanPath.class; break; - default : pathType = EntityPathBase.class; - } - } else { - pathType = EntityPathBase.class; - } - - for (Annotation annotation : model.getAnnotations()) { - writer.annotation(annotation); - } - - writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); - - if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING) { - writer.beginClass(queryType, new ClassType(pathType)); - } else { - writer.beginClass(queryType, new ClassType(category, pathType, model)); - } - - // TODO : generate proper serialVersionUID here - long serialVersionUID = model.getFullName().hashCode(); - writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", serialVersionUID + "L"); - } - - protected void introDefaultInstance(CodeWriter writer, EntityType model, String defaultName) throws IOException { - String simpleName = !defaultName.isEmpty() ? defaultName : model.getModifiedSimpleName(); - Type queryType = typeMappings.getPathType(model, model, true); - String alias = simpleName; - if (keywords.contains(simpleName.toUpperCase())) { - alias += "1"; - } - writer.publicStaticFinal(queryType, simpleName, NEW + queryType.getSimpleName() + "(\"" + alias + "\")"); - - } - - protected void introFactoryMethods(CodeWriter writer, final EntityType model) throws IOException { - String localName = writer.getRawName(model); - String genericName = writer.getGenericName(true, model); - Set sizes = new HashSet<>(); - - for (Constructor c : model.getConstructors()) { - // begin - if (!localName.equals(genericName)) { - writer.suppressWarnings(UNCHECKED); - } - Type returnType = new ClassType(ConstructorExpression.class, model); - final boolean asExpr = sizes.add(c.getParameters().size()); - writer.beginStaticMethod(returnType, "create", c.getParameters(), - new Function() { - @Override - public Parameter apply(Parameter p) { - Type type; - if (!asExpr) { - type = typeMappings.getExprType( - p.getType(), model, false, false, true); - } else if (p.getType().isFinal()) { - type = new ClassType(Expression.class, p.getType()); - } else { - type = new ClassType(Expression.class, new TypeExtends(p.getType())); - } - return new Parameter(p.getName(), type); - } - }); - - // body - // TODO : replace with class reference - writer.beginLine("return Projections.constructor("); -// if (!localName.equals(genericName)) { -// writer.append("(Class)"); -// } - writer.append(writer.getClassConstant(localName)); - writer.append(", new Class[]{"); - boolean first = true; - for (Parameter p : c.getParameters()) { - if (!first) { - writer.append(COMMA); - } - if (Types.PRIMITIVES.containsKey(p.getType())) { - Type primitive = Types.PRIMITIVES.get(p.getType()); - writer.append(writer.getClassConstant(primitive.getFullName())); - } else { - writer.append(writer.getClassConstant(writer.getRawName(p.getType()))); - } - first = false; - } - writer.append("}"); - - for (Parameter p : c.getParameters()) { - writer.append(COMMA).append(p.getName()); - } - - // end - writer.append(");\n"); - writer.end(); - } - } - - protected void introImports(CodeWriter writer, SerializerConfig config, - EntityType model) throws IOException { - writer.staticimports(PathMetadataFactory.class); - - // import package of query type - Type queryType = typeMappings.getPathType(model, model, true); - if (!model.getPackageName().isEmpty() - && !queryType.getPackageName().equals(model.getPackageName()) - && !queryType.getSimpleName().equals(model.getSimpleName())) { - String fullName = model.getFullName(); - String packageName = model.getPackageName(); - if (fullName.substring(packageName.length() + 1).contains(".")) { - fullName = fullName.substring(0, fullName.lastIndexOf('.')); - } - writer.importClasses(fullName); - } - - // delegate packages - introDelegatePackages(writer, model); - - // other packages - writer.imports(SimpleExpression.class.getPackage()); - - // other classes - List> classes = new ArrayList<>(); - classes.add(PathMetadata.class); - classes.add(generatedAnnotationClass); - - if (!getUsedClassNames(model).contains("Path")) { - classes.add(Path.class); - } - if (!model.getConstructors().isEmpty()) { - classes.add(ConstructorExpression.class); - classes.add(Projections.class); - classes.add(Expression.class); - } - boolean inits = false; - if (model.hasEntityFields() || model.hasInits()) { - inits = true; - } else { - Set collections = EnumSet.of(TypeCategory.COLLECTION, TypeCategory.LIST, TypeCategory.SET); - for (Property property : model.getProperties()) { - if (!property.isInherited() && collections.contains(property.getType().getCategory())) { - inits = true; - break; - } - } - } - if (inits) { - classes.add(PathInits.class); - } - writer.imports(classes.toArray(new Class[0])); - } - - private Set getUsedClassNames(EntityType model) { - Set result = new HashSet<>(); - result.add(model.getSimpleName()); - for (Property property : model.getProperties()) { - result.add(property.getType().getSimpleName()); - for (Type type : property.getType().getParameters()) { - if (type != null) { - result.add(type.getSimpleName()); - } - } - } - return result; - } - - protected boolean isImportExprPackage(EntityType model) { - if (!model.getConstructors().isEmpty() || !model.getDelegates().isEmpty()) { - boolean importExprPackage = false; - for (Constructor c : model.getConstructors()) { - for (Parameter cp : c.getParameters()) { - importExprPackage |= cp.getType().getPackageName() - .equals(ComparableExpression.class.getPackage().getName()); - } - } - for (Delegate d : model.getDelegates()) { - for (Parameter dp : d.getParameters()) { - importExprPackage |= dp.getType().getPackageName() - .equals(ComparableExpression.class.getPackage().getName()); - } - } - return importExprPackage; - - } else { - return false; - } - } - - protected void introDelegatePackages(CodeWriter writer, EntityType model) throws IOException { - Set packages = new HashSet(); - for (Delegate delegate : model.getDelegates()) { - if (!delegate.getDelegateType().getPackageName().equals(model.getPackageName())) { - packages.add(delegate.getDelegateType().getPackageName()); - } - } - writer.importPackages(packages.toArray(new String[0])); - } - - protected void introInits(CodeWriter writer, EntityType model) throws IOException { - List inits = new ArrayList(); - for (Property property : model.getProperties()) { - for (String init : property.getInits()) { - inits.add(property.getEscapedName() + DOT + init); - } - } - if (!inits.isEmpty()) { - inits.add(0, STAR); - String initsAsString = QUOTE + String.join("\", \"", inits) + QUOTE; - writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "new PathInits(" + initsAsString + ")"); - } else if (model.hasEntityFields() || superTypeHasEntityFields(model)) { - writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "PathInits.DIRECT2"); - } - } - - protected void introJavadoc(CodeWriter writer, EntityType model) throws IOException { - Type queryType = typeMappings.getPathType(model, model, true); - writer.javadoc(queryType.getSimpleName() + " is a Querydsl query type for " + - model.getSimpleName()); - } - - protected void introPackage(CodeWriter writer, EntityType model) throws IOException { - Type queryType = typeMappings.getPathType(model, model, false); - if (!queryType.getPackageName().isEmpty()) { - writer.packageDecl(queryType.getPackageName()); - } - } - - protected void introSuper(CodeWriter writer, EntityType model) throws IOException { - EntityType superType = model.getSuperType().getEntityType(); - Type superQueryType = typeMappings.getPathType(superType, model, false); - if (!superType.hasEntityFields()) { - writer.publicFinal(superQueryType, "_super", NEW + writer.getRawName(superQueryType) + "(this)"); - } else { - writer.publicFinal(superQueryType, "_super"); - } - } - - protected void listAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { - String escapedName = field.getEscapedName(); - Type queryType = typeMappings.getPathType(field.getParameter(0), model, false); - - writer.beginPublicMethod(queryType, escapedName, new Parameter("index", Types.INT)); - writer.line(RETURN + escapedName + ".get(index);").end(); - - writer.beginPublicMethod(queryType, escapedName, new Parameter("index", - new ClassType(Expression.class, Types.INTEGER))); - writer.line(RETURN + escapedName + ".get(index);").end(); - } - - protected void mapAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { - String escapedName = field.getEscapedName(); - Type queryType = typeMappings.getPathType(field.getParameter(1), model, false); - - writer.beginPublicMethod(queryType, escapedName, new Parameter("key", field.getParameter(0))); - writer.line(RETURN + escapedName + ".get(key);").end(); - - writer.beginPublicMethod(queryType, escapedName, new Parameter("key", - new ClassType(Expression.class, field.getParameter(0)))); - writer.line(RETURN + escapedName + ".get(key);").end(); - } - - private void delegate(final EntityType model, Delegate delegate, SerializerConfig config, - CodeWriter writer) throws IOException { - Parameter[] params = delegate.getParameters().toArray(new Parameter[0]); - writer.beginPublicMethod(delegate.getReturnType(), delegate.getName(), params); - - // body start - writer.beginLine(RETURN + writer.getRawName(delegate.getDelegateType()) + "." + delegate.getName() + "("); - writer.append("this"); - if (!model.equals(delegate.getDeclaringType())) { - int counter = 0; - EntityType type = model; - while (type != null && !type.equals(delegate.getDeclaringType())) { - type = type.getSuperType() != null ? type.getSuperType().getEntityType() : null; - counter++; - } - for (int i = 0; i < counter; i++) { - writer.append("._super"); - } - } - for (Parameter parameter : delegate.getParameters()) { - writer.append(COMMA).append(parameter.getName()); - } - writer.append(");\n"); - - // body end - writer.end(); - } - - protected void outro(EntityType model, CodeWriter writer) throws IOException { - writer.end(); - } - - @Override - public void serialize(EntityType model, SerializerConfig config, - CodeWriter writer) throws IOException { - intro(model, config, writer); - - // properties - serializeProperties(model, config, writer); - - // constructors - constructors(model, config, writer); - - // delegates - for (Delegate delegate : model.getDelegates()) { - delegate(model, delegate, config, writer); - } - - // property accessors - for (Property property : model.getProperties()) { - TypeCategory category = property.getType().getCategory(); - if (category == TypeCategory.MAP && config.useMapAccessors()) { - mapAccessor(model, property, writer); - } else if (category == TypeCategory.LIST && config.useListAccessors()) { - listAccessor(model, property, writer); - } else if (category == TypeCategory.ENTITY && config.useEntityAccessors()) { - entityAccessor(model, property, writer); - } - } - outro(model, writer); - } - - protected void serialize(EntityType model, Property field, Type type, CodeWriter writer, - String factoryMethod, String... args) throws IOException { - Supertype superType = model.getSuperType(); - // construct value - StringBuilder value = new StringBuilder(); - if (field.isInherited() && superType != null) { - if (!superType.getEntityType().hasEntityFields()) { - value.append("_super.").append(field.getEscapedName()); - } - } else { - value.append(factoryMethod).append("(\"").append(field.getName()).append(QUOTE); - for (String arg : args) { - value.append(COMMA).append(arg); - } - value.append(")"); - } - - // serialize it - if (field.isInherited()) { - writer.line("//inherited"); - } - if (value.length() > 0) { - writer.publicFinal(type, field.getEscapedName(), value.toString()); - } else { - writer.publicFinal(type, field.getEscapedName()); - } - } - - protected void customField(EntityType model, Property field, SerializerConfig config, - CodeWriter writer) throws IOException { - Type queryType = typeMappings.getPathType(field.getType(), model, false); - writer.line("// custom"); - if (field.isInherited()) { - writer.line("// inherited"); - Supertype superType = model.getSuperType(); - if (!superType.getEntityType().hasEntityFields()) { - String value = NEW + writer.getRawName(queryType) + "(_super." + field.getEscapedName() + ")"; - writer.publicFinal(queryType, field.getEscapedName(), value); - } else { - writer.publicFinal(queryType, field.getEscapedName()); - } - } else { - String value = NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\"))"; - writer.publicFinal(queryType, field.getEscapedName(), value); - } - } - - // TODO move this to codegen - private Type wrap(Type type) { - if (type.equals(Types.BOOLEAN_P)) { - return Types.BOOLEAN; - } else if (type.equals(Types.BYTE_P)) { - return Types.BYTE; - } else if (type.equals(Types.CHAR)) { - return Types.CHARACTER; - } else if (type.equals(Types.DOUBLE_P)) { - return Types.DOUBLE; - } else if (type.equals(Types.FLOAT_P)) { - return Types.FLOAT; - } else if (type.equals(Types.INT)) { - return Types.INTEGER; - } else if (type.equals(Types.LONG_P)) { - return Types.LONG; - } else if (type.equals(Types.SHORT_P)) { - return Types.SHORT; - } else { - return type; - } - } - - protected void serializeProperties(EntityType model, SerializerConfig config, - CodeWriter writer) throws IOException { - for (Property property : model.getProperties()) { - // FIXME : the custom types should have the custom type category - if (typeMappings.isRegistered(property.getType()) - && property.getType().getCategory() != TypeCategory.CUSTOM - && property.getType().getCategory() != TypeCategory.ENTITY) { - customField(model, property, config, writer); - continue; - } - - // strips of "? extends " etc - Type propertyType = new SimpleType(property.getType(), property.getType().getParameters()); - Type queryType = typeMappings.getPathType(propertyType, model, false); - Type genericQueryType = null; - String localRawName = writer.getRawName(property.getType()); - String inits = getInits(property); - - switch (property.getType().getCategory()) { - case STRING: - serialize(model, property, queryType, writer, "createString"); - break; - - case BOOLEAN: - serialize(model, property, queryType, writer, "createBoolean"); - break; - - case SIMPLE: - serialize(model, property, queryType, writer, "createSimple", writer.getClassConstant(localRawName)); - break; - - case COMPARABLE: - serialize(model, property, queryType, writer, "createComparable", writer.getClassConstant(localRawName)); - break; - - case ENUM: - serialize(model, property, queryType, writer, "createEnum", writer.getClassConstant(localRawName)); - break; - - case DATE: - serialize(model, property, queryType, writer, "createDate", writer.getClassConstant(localRawName)); - break; - - case DATETIME: - serialize(model, property, queryType, writer, "createDateTime", writer.getClassConstant(localRawName)); - break; - - case TIME: - serialize(model, property, queryType, writer, "createTime", writer.getClassConstant(localRawName)); - break; - - case NUMERIC: - serialize(model, property, queryType, writer, "createNumber", writer.getClassConstant(localRawName)); - break; - - case CUSTOM: - customField(model, property, config, writer); - break; - - case ARRAY: - serialize(model, property, new ClassType(ArrayPath.class, - property.getType(), - wrap(property.getType().getComponentType())), - writer, "createArray", writer.getClassConstant(localRawName)); - break; - - case COLLECTION: - genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); - String genericKey = writer.getGenericName(true, property.getParameter(0)); - localRawName = writer.getRawName(property.getParameter(0)); - queryType = typeMappings.getPathType(property.getParameter(0), model, true); - - serialize(model, property, new ClassType(CollectionPath.class, getRaw(property.getParameter(0)), genericQueryType), - writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createCollection", - writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); - break; - - case SET: - genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); - genericKey = writer.getGenericName(true, property.getParameter(0)); - localRawName = writer.getRawName(property.getParameter(0)); - queryType = typeMappings.getPathType(property.getParameter(0), model, true); - - serialize(model, property, new ClassType(SetPath.class, getRaw(property.getParameter(0)), genericQueryType), - writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createSet", - writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); - break; - - case LIST: - genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); - genericKey = writer.getGenericName(true, property.getParameter(0)); - localRawName = writer.getRawName(property.getParameter(0)); - queryType = typeMappings.getPathType(property.getParameter(0), model, true); - - serialize(model, property, new ClassType(ListPath.class, getRaw(property.getParameter(0)), genericQueryType), - writer, "this.<" + genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createList", - writer.getClassConstant(localRawName), writer.getClassConstant(writer.getRawName(queryType)), inits); - break; - - case MAP: - genericKey = writer.getGenericName(true, property.getParameter(0)); - String genericValue = writer.getGenericName(true, property.getParameter(1)); - genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(1)), model, false); - String keyType = writer.getRawName(property.getParameter(0)); - String valueType = writer.getRawName(property.getParameter(1)); - queryType = typeMappings.getPathType(property.getParameter(1), model, true); - - serialize(model, property, new ClassType(MapPath.class, getRaw(property.getParameter(0)), - getRaw(property.getParameter(1)), genericQueryType), - writer, "this.<" + genericKey + COMMA + genericValue + COMMA + - writer.getGenericName(true, genericQueryType) + ">createMap", - writer.getClassConstant(keyType), writer.getClassConstant(valueType), writer.getClassConstant(writer.getRawName(queryType))); - break; - - case ENTITY: - entityField(model, property, config, writer); - break; - } - } - } - - private String getInits(Property property) { - if (!property.getInits().isEmpty()) { - return "INITS.get(\"" + property.getName() + "\")"; - } else { - return "PathInits.DIRECT2"; - } - } - - private Type getRaw(Type type) { - if (type instanceof EntityType && type.getPackageName().startsWith("ext.java")) { - return type; - } else { - return new SimpleType(type, type.getParameters()); - } - } - - private static CodeWriter suppressAllWarnings(CodeWriter writer) throws IOException { - return writer.suppressWarnings("all", "rawtypes", "unchecked"); - } - + writer.append(writer.getClassConstant(writer.getRawName(p.getType()))); + } + first = false; + } + writer.append("}"); + + for (Parameter p : c.getParameters()) { + writer.append(COMMA).append(p.getName()); + } + + // end + writer.append(");\n"); + writer.end(); + } + } + + protected void introImports(CodeWriter writer, SerializerConfig config, EntityType model) + throws IOException { + writer.staticimports(PathMetadataFactory.class); + + // import package of query type + Type queryType = typeMappings.getPathType(model, model, true); + if (!model.getPackageName().isEmpty() + && !queryType.getPackageName().equals(model.getPackageName()) + && !queryType.getSimpleName().equals(model.getSimpleName())) { + String fullName = model.getFullName(); + String packageName = model.getPackageName(); + if (fullName.substring(packageName.length() + 1).contains(".")) { + fullName = fullName.substring(0, fullName.lastIndexOf('.')); + } + writer.importClasses(fullName); + } + + // delegate packages + introDelegatePackages(writer, model); + + // other packages + writer.imports(SimpleExpression.class.getPackage()); + + // other classes + List> classes = new ArrayList<>(); + classes.add(PathMetadata.class); + classes.add(generatedAnnotationClass); + + if (!getUsedClassNames(model).contains("Path")) { + classes.add(Path.class); + } + if (!model.getConstructors().isEmpty()) { + classes.add(ConstructorExpression.class); + classes.add(Projections.class); + classes.add(Expression.class); + } + boolean inits = false; + if (model.hasEntityFields() || model.hasInits()) { + inits = true; + } else { + Set collections = + EnumSet.of(TypeCategory.COLLECTION, TypeCategory.LIST, TypeCategory.SET); + for (Property property : model.getProperties()) { + if (!property.isInherited() && collections.contains(property.getType().getCategory())) { + inits = true; + break; + } + } + } + if (inits) { + classes.add(PathInits.class); + } + writer.imports(classes.toArray(new Class[0])); + } + + private Set getUsedClassNames(EntityType model) { + Set result = new HashSet<>(); + result.add(model.getSimpleName()); + for (Property property : model.getProperties()) { + result.add(property.getType().getSimpleName()); + for (Type type : property.getType().getParameters()) { + if (type != null) { + result.add(type.getSimpleName()); + } + } + } + return result; + } + + protected boolean isImportExprPackage(EntityType model) { + if (!model.getConstructors().isEmpty() || !model.getDelegates().isEmpty()) { + boolean importExprPackage = false; + for (Constructor c : model.getConstructors()) { + for (Parameter cp : c.getParameters()) { + importExprPackage |= + cp.getType() + .getPackageName() + .equals(ComparableExpression.class.getPackage().getName()); + } + } + for (Delegate d : model.getDelegates()) { + for (Parameter dp : d.getParameters()) { + importExprPackage |= + dp.getType() + .getPackageName() + .equals(ComparableExpression.class.getPackage().getName()); + } + } + return importExprPackage; + + } else { + return false; + } + } + + protected void introDelegatePackages(CodeWriter writer, EntityType model) throws IOException { + Set packages = new HashSet(); + for (Delegate delegate : model.getDelegates()) { + if (!delegate.getDelegateType().getPackageName().equals(model.getPackageName())) { + packages.add(delegate.getDelegateType().getPackageName()); + } + } + writer.importPackages(packages.toArray(new String[0])); + } + + protected void introInits(CodeWriter writer, EntityType model) throws IOException { + List inits = new ArrayList(); + for (Property property : model.getProperties()) { + for (String init : property.getInits()) { + inits.add(property.getEscapedName() + DOT + init); + } + } + if (!inits.isEmpty()) { + inits.add(0, STAR); + String initsAsString = QUOTE + String.join("\", \"", inits) + QUOTE; + writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "new PathInits(" + initsAsString + ")"); + } else if (model.hasEntityFields() || superTypeHasEntityFields(model)) { + writer.privateStaticFinal(PATH_INITS_TYPE, "INITS", "PathInits.DIRECT2"); + } + } + + protected void introJavadoc(CodeWriter writer, EntityType model) throws IOException { + Type queryType = typeMappings.getPathType(model, model, true); + writer.javadoc( + queryType.getSimpleName() + " is a Querydsl query type for " + model.getSimpleName()); + } + + protected void introPackage(CodeWriter writer, EntityType model) throws IOException { + Type queryType = typeMappings.getPathType(model, model, false); + if (!queryType.getPackageName().isEmpty()) { + writer.packageDecl(queryType.getPackageName()); + } + } + + protected void introSuper(CodeWriter writer, EntityType model) throws IOException { + EntityType superType = model.getSuperType().getEntityType(); + Type superQueryType = typeMappings.getPathType(superType, model, false); + if (!superType.hasEntityFields()) { + writer.publicFinal( + superQueryType, "_super", NEW + writer.getRawName(superQueryType) + "(this)"); + } else { + writer.publicFinal(superQueryType, "_super"); + } + } + + protected void listAccessor(EntityType model, Property field, CodeWriter writer) + throws IOException { + String escapedName = field.getEscapedName(); + Type queryType = typeMappings.getPathType(field.getParameter(0), model, false); + + writer.beginPublicMethod(queryType, escapedName, new Parameter("index", Types.INT)); + writer.line(RETURN + escapedName + ".get(index);").end(); + + writer.beginPublicMethod( + queryType, + escapedName, + new Parameter("index", new ClassType(Expression.class, Types.INTEGER))); + writer.line(RETURN + escapedName + ".get(index);").end(); + } + + protected void mapAccessor(EntityType model, Property field, CodeWriter writer) + throws IOException { + String escapedName = field.getEscapedName(); + Type queryType = typeMappings.getPathType(field.getParameter(1), model, false); + + writer.beginPublicMethod(queryType, escapedName, new Parameter("key", field.getParameter(0))); + writer.line(RETURN + escapedName + ".get(key);").end(); + + writer.beginPublicMethod( + queryType, + escapedName, + new Parameter("key", new ClassType(Expression.class, field.getParameter(0)))); + writer.line(RETURN + escapedName + ".get(key);").end(); + } + + private void delegate( + final EntityType model, Delegate delegate, SerializerConfig config, CodeWriter writer) + throws IOException { + Parameter[] params = delegate.getParameters().toArray(new Parameter[0]); + writer.beginPublicMethod(delegate.getReturnType(), delegate.getName(), params); + + // body start + writer.beginLine( + RETURN + writer.getRawName(delegate.getDelegateType()) + "." + delegate.getName() + "("); + writer.append("this"); + if (!model.equals(delegate.getDeclaringType())) { + int counter = 0; + EntityType type = model; + while (type != null && !type.equals(delegate.getDeclaringType())) { + type = type.getSuperType() != null ? type.getSuperType().getEntityType() : null; + counter++; + } + for (int i = 0; i < counter; i++) { + writer.append("._super"); + } + } + for (Parameter parameter : delegate.getParameters()) { + writer.append(COMMA).append(parameter.getName()); + } + writer.append(");\n"); + + // body end + writer.end(); + } + + protected void outro(EntityType model, CodeWriter writer) throws IOException { + writer.end(); + } + + @Override + public void serialize(EntityType model, SerializerConfig config, CodeWriter writer) + throws IOException { + intro(model, config, writer); + + // properties + serializeProperties(model, config, writer); + + // constructors + constructors(model, config, writer); + + // delegates + for (Delegate delegate : model.getDelegates()) { + delegate(model, delegate, config, writer); + } + + // property accessors + for (Property property : model.getProperties()) { + TypeCategory category = property.getType().getCategory(); + if (category == TypeCategory.MAP && config.useMapAccessors()) { + mapAccessor(model, property, writer); + } else if (category == TypeCategory.LIST && config.useListAccessors()) { + listAccessor(model, property, writer); + } else if (category == TypeCategory.ENTITY && config.useEntityAccessors()) { + entityAccessor(model, property, writer); + } + } + outro(model, writer); + } + + protected void serialize( + EntityType model, + Property field, + Type type, + CodeWriter writer, + String factoryMethod, + String... args) + throws IOException { + Supertype superType = model.getSuperType(); + // construct value + StringBuilder value = new StringBuilder(); + if (field.isInherited() && superType != null) { + if (!superType.getEntityType().hasEntityFields()) { + value.append("_super.").append(field.getEscapedName()); + } + } else { + value.append(factoryMethod).append("(\"").append(field.getName()).append(QUOTE); + for (String arg : args) { + value.append(COMMA).append(arg); + } + value.append(")"); + } + + // serialize it + if (field.isInherited()) { + writer.line("//inherited"); + } + if (value.length() > 0) { + writer.publicFinal(type, field.getEscapedName(), value.toString()); + } else { + writer.publicFinal(type, field.getEscapedName()); + } + } + + protected void customField( + EntityType model, Property field, SerializerConfig config, CodeWriter writer) + throws IOException { + Type queryType = typeMappings.getPathType(field.getType(), model, false); + writer.line("// custom"); + if (field.isInherited()) { + writer.line("// inherited"); + Supertype superType = model.getSuperType(); + if (!superType.getEntityType().hasEntityFields()) { + String value = + NEW + writer.getRawName(queryType) + "(_super." + field.getEscapedName() + ")"; + writer.publicFinal(queryType, field.getEscapedName(), value); + } else { + writer.publicFinal(queryType, field.getEscapedName()); + } + } else { + String value = + NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\"))"; + writer.publicFinal(queryType, field.getEscapedName(), value); + } + } + + // TODO move this to codegen + private Type wrap(Type type) { + if (type.equals(Types.BOOLEAN_P)) { + return Types.BOOLEAN; + } else if (type.equals(Types.BYTE_P)) { + return Types.BYTE; + } else if (type.equals(Types.CHAR)) { + return Types.CHARACTER; + } else if (type.equals(Types.DOUBLE_P)) { + return Types.DOUBLE; + } else if (type.equals(Types.FLOAT_P)) { + return Types.FLOAT; + } else if (type.equals(Types.INT)) { + return Types.INTEGER; + } else if (type.equals(Types.LONG_P)) { + return Types.LONG; + } else if (type.equals(Types.SHORT_P)) { + return Types.SHORT; + } else { + return type; + } + } + + protected void serializeProperties(EntityType model, SerializerConfig config, CodeWriter writer) + throws IOException { + for (Property property : model.getProperties()) { + // FIXME : the custom types should have the custom type category + if (typeMappings.isRegistered(property.getType()) + && property.getType().getCategory() != TypeCategory.CUSTOM + && property.getType().getCategory() != TypeCategory.ENTITY) { + customField(model, property, config, writer); + continue; + } + + // strips of "? extends " etc + Type propertyType = new SimpleType(property.getType(), property.getType().getParameters()); + Type queryType = typeMappings.getPathType(propertyType, model, false); + Type genericQueryType = null; + String localRawName = writer.getRawName(property.getType()); + String inits = getInits(property); + + switch (property.getType().getCategory()) { + case STRING: + serialize(model, property, queryType, writer, "createString"); + break; + + case BOOLEAN: + serialize(model, property, queryType, writer, "createBoolean"); + break; + + case SIMPLE: + serialize( + model, + property, + queryType, + writer, + "createSimple", + writer.getClassConstant(localRawName)); + break; + + case COMPARABLE: + serialize( + model, + property, + queryType, + writer, + "createComparable", + writer.getClassConstant(localRawName)); + break; + + case ENUM: + serialize( + model, + property, + queryType, + writer, + "createEnum", + writer.getClassConstant(localRawName)); + break; + + case DATE: + serialize( + model, + property, + queryType, + writer, + "createDate", + writer.getClassConstant(localRawName)); + break; + + case DATETIME: + serialize( + model, + property, + queryType, + writer, + "createDateTime", + writer.getClassConstant(localRawName)); + break; + + case TIME: + serialize( + model, + property, + queryType, + writer, + "createTime", + writer.getClassConstant(localRawName)); + break; + + case NUMERIC: + serialize( + model, + property, + queryType, + writer, + "createNumber", + writer.getClassConstant(localRawName)); + break; + + case CUSTOM: + customField(model, property, config, writer); + break; + + case ARRAY: + serialize( + model, + property, + new ClassType( + ArrayPath.class, property.getType(), wrap(property.getType().getComponentType())), + writer, + "createArray", + writer.getClassConstant(localRawName)); + break; + + case COLLECTION: + genericQueryType = + typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); + String genericKey = writer.getGenericName(true, property.getParameter(0)); + localRawName = writer.getRawName(property.getParameter(0)); + queryType = typeMappings.getPathType(property.getParameter(0), model, true); + + serialize( + model, + property, + new ClassType( + CollectionPath.class, getRaw(property.getParameter(0)), genericQueryType), + writer, + "this.<" + + genericKey + + COMMA + + writer.getGenericName(true, genericQueryType) + + ">createCollection", + writer.getClassConstant(localRawName), + writer.getClassConstant(writer.getRawName(queryType)), + inits); + break; + + case SET: + genericQueryType = + typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); + genericKey = writer.getGenericName(true, property.getParameter(0)); + localRawName = writer.getRawName(property.getParameter(0)); + queryType = typeMappings.getPathType(property.getParameter(0), model, true); + + serialize( + model, + property, + new ClassType(SetPath.class, getRaw(property.getParameter(0)), genericQueryType), + writer, + "this.<" + + genericKey + + COMMA + + writer.getGenericName(true, genericQueryType) + + ">createSet", + writer.getClassConstant(localRawName), + writer.getClassConstant(writer.getRawName(queryType)), + inits); + break; + + case LIST: + genericQueryType = + typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); + genericKey = writer.getGenericName(true, property.getParameter(0)); + localRawName = writer.getRawName(property.getParameter(0)); + queryType = typeMappings.getPathType(property.getParameter(0), model, true); + + serialize( + model, + property, + new ClassType(ListPath.class, getRaw(property.getParameter(0)), genericQueryType), + writer, + "this.<" + + genericKey + + COMMA + + writer.getGenericName(true, genericQueryType) + + ">createList", + writer.getClassConstant(localRawName), + writer.getClassConstant(writer.getRawName(queryType)), + inits); + break; + + case MAP: + genericKey = writer.getGenericName(true, property.getParameter(0)); + String genericValue = writer.getGenericName(true, property.getParameter(1)); + genericQueryType = + typeMappings.getPathType(getRaw(property.getParameter(1)), model, false); + String keyType = writer.getRawName(property.getParameter(0)); + String valueType = writer.getRawName(property.getParameter(1)); + queryType = typeMappings.getPathType(property.getParameter(1), model, true); + + serialize( + model, + property, + new ClassType( + MapPath.class, + getRaw(property.getParameter(0)), + getRaw(property.getParameter(1)), + genericQueryType), + writer, + "this.<" + + genericKey + + COMMA + + genericValue + + COMMA + + writer.getGenericName(true, genericQueryType) + + ">createMap", + writer.getClassConstant(keyType), + writer.getClassConstant(valueType), + writer.getClassConstant(writer.getRawName(queryType))); + break; + + case ENTITY: + entityField(model, property, config, writer); + break; + } + } + } + + private String getInits(Property property) { + if (!property.getInits().isEmpty()) { + return "INITS.get(\"" + property.getName() + "\")"; + } else { + return "PathInits.DIRECT2"; + } + } + + private Type getRaw(Type type) { + if (type instanceof EntityType && type.getPackageName().startsWith("ext.java")) { + return type; + } else { + return new SimpleType(type, type.getParameters()); + } + } + + private static CodeWriter suppressAllWarnings(CodeWriter writer) throws IOException { + return writer.suppressWarnings("all", "rawtypes", "unchecked"); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultFiler.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultFiler.java index c40f905ea1..daa8558346 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultFiler.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultFiler.java @@ -13,11 +13,11 @@ */ package com.querydsl.codegen; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.Element; import java.io.IOException; import java.io.Writer; import java.util.Collection; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.Element; /** * creates files with {@link javax.annotation.processing.Filer}. @@ -25,8 +25,15 @@ * @author f43nd1r */ public class DefaultFiler implements Filer { - @Override - public Writer createFile(ProcessingEnvironment processingEnvironment, String classname, Collection elements) throws IOException { - return processingEnvironment.getFiler().createSourceFile(classname, elements.toArray(new Element[0])).openWriter(); - } + @Override + public Writer createFile( + ProcessingEnvironment processingEnvironment, + String classname, + Collection elements) + throws IOException { + return processingEnvironment + .getFiler() + .createSourceFile(classname, elements.toArray(new Element[0])) + .openWriter(); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultProjectionSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultProjectionSerializer.java index 0010e6b260..6d1c21cbd4 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultProjectionSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultProjectionSerializer.java @@ -13,153 +13,154 @@ */ package com.querydsl.codegen; +import com.querydsl.codegen.utils.CodeWriter; +import com.querydsl.codegen.utils.model.*; +import com.querydsl.core.types.ConstructorExpression; +import com.querydsl.core.types.Expression; +import com.querydsl.core.types.dsl.NumberExpression; import java.io.IOException; - -import java.util.HashSet; import java.lang.annotation.Annotation; +import java.util.HashSet; import java.util.Set; import java.util.function.Function; - import javax.inject.Inject; import javax.inject.Named; -import com.querydsl.codegen.utils.CodeWriter; -import com.querydsl.codegen.utils.model.*; -import com.querydsl.core.types.ConstructorExpression; -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.dsl.NumberExpression; - /** * {@code ProjectionSerializer} is a {@link Serializer} implementation for projection types * * @author tiwe - * */ public final class DefaultProjectionSerializer implements ProjectionSerializer { - private final Class generatedAnnotationClass; - private final TypeMappings typeMappings; - - /** - * Create a new {@code ProjectionSerializer} instance - * - * @param typeMappings type mappings to be used - */ - public DefaultProjectionSerializer(TypeMappings typeMappings) { - this(typeMappings, GeneratedAnnotationResolver.resolveDefault()); - } - - /** - * Create a new {@code ProjectionSerializer} instance - * - * @param typeMappings type mappings to be used - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on the generated classes. - * @see Single-Element Annotation - */ - @Inject - public DefaultProjectionSerializer( - TypeMappings typeMappings, - @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) Class generatedAnnotationClass) { - this.typeMappings = typeMappings; - this.generatedAnnotationClass = generatedAnnotationClass; + private final Class generatedAnnotationClass; + private final TypeMappings typeMappings; + + /** + * Create a new {@code ProjectionSerializer} instance + * + * @param typeMappings type mappings to be used + */ + public DefaultProjectionSerializer(TypeMappings typeMappings) { + this(typeMappings, GeneratedAnnotationResolver.resolveDefault()); + } + + /** + * Create a new {@code ProjectionSerializer} instance + * + * @param typeMappings type mappings to be used + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated classes. + * @see Single-Element + * Annotation + */ + @Inject + public DefaultProjectionSerializer( + TypeMappings typeMappings, + @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) + Class generatedAnnotationClass) { + this.typeMappings = typeMappings; + this.generatedAnnotationClass = generatedAnnotationClass; + } + + protected void intro(EntityType model, CodeWriter writer) throws IOException { + String simpleName = model.getSimpleName(); + Type queryType = typeMappings.getPathType(model, model, false); + + // package + if (!queryType.getPackageName().isEmpty()) { + writer.packageDecl(queryType.getPackageName()); } - protected void intro(EntityType model, CodeWriter writer) throws IOException { - String simpleName = model.getSimpleName(); - Type queryType = typeMappings.getPathType(model, model, false); - - // package - if (!queryType.getPackageName().isEmpty()) { - writer.packageDecl(queryType.getPackageName()); - } - - // imports - writer.imports(NumberExpression.class.getPackage()); - writer.imports(ConstructorExpression.class, generatedAnnotationClass); + // imports + writer.imports(NumberExpression.class.getPackage()); + writer.imports(ConstructorExpression.class, generatedAnnotationClass); - Set sizes = new HashSet<>(); - for (Constructor c : model.getConstructors()) { - sizes.add(c.getParameters().size()); - } - if (sizes.size() != model.getConstructors().size()) { - writer.imports(Expression.class); - } - - // javadoc - writer.javadoc(queryType + " is a Querydsl Projection type for " + simpleName); - - writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); - - // class header -// writer.suppressWarnings("serial"); - Type superType = new ClassType(TypeCategory.SIMPLE, ConstructorExpression.class, model); - writer.beginClass(queryType, superType); - writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", model.hashCode() + "L"); + Set sizes = new HashSet<>(); + for (Constructor c : model.getConstructors()) { + sizes.add(c.getParameters().size()); } - - protected void outro(EntityType model, CodeWriter writer) throws IOException { - writer.end(); + if (sizes.size() != model.getConstructors().size()) { + writer.imports(Expression.class); } - @Override - public void serialize(final EntityType model, SerializerConfig serializerConfig, - CodeWriter writer) throws IOException { - // intro - intro(model, writer); - - String localName = writer.getRawName(model); - Set sizes = new HashSet<>(); - - for (Constructor c : model.getConstructors()) { - final boolean asExpr = sizes.add(c.getParameters().size()); - // begin - writer.beginConstructor(c.getParameters(), new Function() { - @Override - public Parameter apply(Parameter p) { - Type type; - if (!asExpr) { - type = typeMappings.getExprType(p.getType(), - model, false, false, true); - } else if (p.getType().isFinal()) { - type = new ClassType(Expression.class, p.getType()); - } else { - type = new ClassType(Expression.class, new TypeExtends(p.getType())); - } - return new Parameter(p.getName(), type); - } - }); - - // body - writer.beginLine("super(" + writer.getClassConstant(localName)); - // TODO: Fix for Scala (Array[Class]) - writer.append(", new Class[]{"); - boolean first = true; - - for (Parameter p : c.getParameters()) { - if (!first) { - writer.append(", "); - } - if (Types.PRIMITIVES.containsKey(p.getType())) { - Type primitive = Types.PRIMITIVES.get(p.getType()); - writer.append(writer.getClassConstant(primitive.getFullName())); - } else { - writer.append(writer.getClassConstant(writer.getRawName(p.getType()))); - } - first = false; + // javadoc + writer.javadoc(queryType + " is a Querydsl Projection type for " + simpleName); + + writer.line("@", generatedAnnotationClass.getSimpleName(), "(\"", getClass().getName(), "\")"); + + // class header + // writer.suppressWarnings("serial"); + Type superType = new ClassType(TypeCategory.SIMPLE, ConstructorExpression.class, model); + writer.beginClass(queryType, superType); + writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", model.hashCode() + "L"); + } + + protected void outro(EntityType model, CodeWriter writer) throws IOException { + writer.end(); + } + + @Override + public void serialize( + final EntityType model, SerializerConfig serializerConfig, CodeWriter writer) + throws IOException { + // intro + intro(model, writer); + + String localName = writer.getRawName(model); + Set sizes = new HashSet<>(); + + for (Constructor c : model.getConstructors()) { + final boolean asExpr = sizes.add(c.getParameters().size()); + // begin + writer.beginConstructor( + c.getParameters(), + new Function() { + @Override + public Parameter apply(Parameter p) { + Type type; + if (!asExpr) { + type = typeMappings.getExprType(p.getType(), model, false, false, true); + } else if (p.getType().isFinal()) { + type = new ClassType(Expression.class, p.getType()); + } else { + type = new ClassType(Expression.class, new TypeExtends(p.getType())); + } + return new Parameter(p.getName(), type); } - writer.append("}"); + }); - for (Parameter p : c.getParameters()) { - writer.append(", ").append(p.getName()); - } + // body + writer.beginLine("super(" + writer.getClassConstant(localName)); + // TODO: Fix for Scala (Array[Class]) + writer.append(", new Class[]{"); + boolean first = true; - // end - writer.append(");\n"); - writer.end(); + for (Parameter p : c.getParameters()) { + if (!first) { + writer.append(", "); + } + if (Types.PRIMITIVES.containsKey(p.getType())) { + Type primitive = Types.PRIMITIVES.get(p.getType()); + writer.append(writer.getClassConstant(primitive.getFullName())); + } else { + writer.append(writer.getClassConstant(writer.getRawName(p.getType()))); } + first = false; + } + writer.append("}"); + + for (Parameter p : c.getParameters()) { + writer.append(", ").append(p.getName()); + } - // outro - outro(model, writer); + // end + writer.append(");\n"); + writer.end(); } + // outro + outro(model, writer); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultSupertypeSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultSupertypeSerializer.java index 06d236bafa..d3cd01d96b 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultSupertypeSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultSupertypeSerializer.java @@ -15,7 +15,6 @@ import java.lang.annotation.Annotation; import java.util.Collection; - import javax.inject.Inject; import javax.inject.Named; @@ -23,32 +22,34 @@ * {@code SupertypeSerializer} is a {@link Serializer} implementation for supertypes * * @author tiwe - * */ -public final class DefaultSupertypeSerializer extends DefaultEntitySerializer implements SupertypeSerializer { +public final class DefaultSupertypeSerializer extends DefaultEntitySerializer + implements SupertypeSerializer { - /** - * Create a new SupertypeSerializer instance - * - * @param typeMappings type mappings to be used - * @param keywords keywords to be used - * @param generatedAnnotationClass fully qualified class name to be used as class level "@Generated" annotation. - */ - @Inject - public DefaultSupertypeSerializer( - TypeMappings typeMappings, - @Named(CodegenModule.KEYWORDS) Collection keywords, - @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) Class generatedAnnotationClass) { - super(typeMappings, keywords, generatedAnnotationClass); - } - /** - * Create a new SupertypeSerializer instance - * - * @param typeMappings type mappings to be used - * @param keywords keywords to be used - */ - public DefaultSupertypeSerializer(TypeMappings typeMappings, Collection keywords) { - super(typeMappings, keywords, GeneratedAnnotationResolver.resolveDefault()); - } + /** + * Create a new SupertypeSerializer instance + * + * @param typeMappings type mappings to be used + * @param keywords keywords to be used + * @param generatedAnnotationClass fully qualified class name to be used as class level + * "@Generated" annotation. + */ + @Inject + public DefaultSupertypeSerializer( + TypeMappings typeMappings, + @Named(CodegenModule.KEYWORDS) Collection keywords, + @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) + Class generatedAnnotationClass) { + super(typeMappings, keywords, generatedAnnotationClass); + } + /** + * Create a new SupertypeSerializer instance + * + * @param typeMappings type mappings to be used + * @param keywords keywords to be used + */ + public DefaultSupertypeSerializer(TypeMappings typeMappings, Collection keywords) { + super(typeMappings, keywords, GeneratedAnnotationResolver.resolveDefault()); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultVariableNameFunction.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultVariableNameFunction.java index 790c62ae5c..c27fec4259 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultVariableNameFunction.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/DefaultVariableNameFunction.java @@ -16,24 +16,23 @@ package com.querydsl.codegen; import com.querydsl.codegen.utils.StringUtils; - -import javax.lang.model.SourceVersion; import java.util.function.Function; +import javax.lang.model.SourceVersion; /** - * Default variable name generation strategy which un-capitalizes the first letter of the class name. - * + * Default variable name generation strategy which un-capitalizes the first letter of the class + * name. */ public final class DefaultVariableNameFunction implements Function { - public static final DefaultVariableNameFunction INSTANCE = new DefaultVariableNameFunction(); + public static final DefaultVariableNameFunction INSTANCE = new DefaultVariableNameFunction(); - @Override - public String apply(EntityType entity) { - String uncapSimpleName = StringUtils.uncapitalize(entity.getInnerType().getSimpleName()); - if (SourceVersion.isKeyword(uncapSimpleName)) { - uncapSimpleName = uncapSimpleName + "$"; - } - return uncapSimpleName; + @Override + public String apply(EntityType entity) { + String uncapSimpleName = StringUtils.uncapitalize(entity.getInnerType().getSimpleName()); + if (SourceVersion.isKeyword(uncapSimpleName)) { + uncapSimpleName = uncapSimpleName + "$"; } + return uncapSimpleName; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Delegate.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Delegate.java index 322a7362ec..5abbca40e7 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Delegate.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Delegate.java @@ -13,79 +13,76 @@ */ package com.querydsl.codegen; -import java.util.List; -import java.util.Objects; - import com.querydsl.codegen.utils.model.Parameter; import com.querydsl.codegen.utils.model.Type; +import java.util.List; +import java.util.Objects; /** * {@code Delegate} defines a delegate method which dispatches to an external static method * * @author tiwe - * */ public class Delegate { - private final Type declaringType; + private final Type declaringType; - private final Type delegateType; + private final Type delegateType; - private final String name; + private final String name; - private final List parameters; + private final List parameters; - private final Type returnType; + private final Type returnType; - public Delegate(Type declaringType, Type delegateType, String name, List params, - Type returnType) { - this.declaringType = declaringType; - this.delegateType = delegateType; - this.name = name; - this.parameters = params; - this.returnType = returnType; - } + public Delegate( + Type declaringType, Type delegateType, String name, List params, Type returnType) { + this.declaringType = declaringType; + this.delegateType = delegateType; + this.name = name; + this.parameters = params; + this.returnType = returnType; + } - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Delegate) { - Delegate m = (Delegate) o; - return m.name.equals(name) && m.parameters.equals(parameters); - } else { - return false; - } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Delegate) { + Delegate m = (Delegate) o; + return m.name.equals(name) && m.parameters.equals(parameters); + } else { + return false; } + } - public Type getDeclaringType() { - return declaringType; - } + public Type getDeclaringType() { + return declaringType; + } - public Type getDelegateType() { - return delegateType; - } + public Type getDelegateType() { + return delegateType; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public List getParameters() { - return parameters; - } + public List getParameters() { + return parameters; + } - public Type getReturnType() { - return returnType; - } + public Type getReturnType() { + return returnType; + } - @Override - public int hashCode() { - return Objects.hash(name, parameters); - } - - @Override - public String toString() { - return delegateType.getFullName() + "." + name + " " + parameters; - } + @Override + public int hashCode() { + return Objects.hash(name, parameters); + } + @Override + public String toString() { + return delegateType.getFullName() + "." + name + " " + parameters; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/EmbeddableSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/EmbeddableSerializer.java index 9528ba18c8..d8ef05a536 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/EmbeddableSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/EmbeddableSerializer.java @@ -18,5 +18,4 @@ * * @author f43nd1r */ -public interface EmbeddableSerializer extends Serializer { -} +public interface EmbeddableSerializer extends Serializer {} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/EntitySerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/EntitySerializer.java index 5fb66291e3..2188b76d3b 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/EntitySerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/EntitySerializer.java @@ -18,5 +18,4 @@ * * @author f43nd1r */ -public interface EntitySerializer extends Serializer { -} +public interface EntitySerializer extends Serializer {} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/EntityType.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/EntityType.java index 04e68b87e5..5a75ea4d7d 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/EntityType.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/EntityType.java @@ -18,7 +18,6 @@ import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeAdapter; import com.querydsl.codegen.utils.model.TypeCategory; - import java.lang.annotation.Annotation; import java.util.Collection; import java.util.HashMap; @@ -29,6 +28,7 @@ import java.util.TreeSet; import java.util.function.Function; import org.jetbrains.annotations.Nullable; + /** * {@code EntityType} represents a model of a query domain type with properties * @@ -36,252 +36,251 @@ */ public class EntityType extends TypeAdapter implements Comparable { - private final Map,Annotation> annotations = new HashMap,Annotation>(); - - private final Set constructors = new LinkedHashSet(); - - private int escapeSuffix = 1; - - private final Set delegates = new HashSet(); - - private final Set properties = new TreeSet(); - - private final Set propertyNames = new HashSet(); - - private final Set escapedPropertyNames = new HashSet(); - - private final Set superTypes; - - private final Map data = new HashMap(); - - private String modifiedSimpleName; - - /** - * Create a new {@code EntityType} instance for the given type - * - * @param type - */ - public EntityType(Type type) { - this(type, new LinkedHashSet(), DefaultVariableNameFunction.INSTANCE); - } - - /** - * Create a new {@code EntityType} instance for the given type - * - * @param type the type to be used - * @param variableNameFunction the variable name function to be used - */ - public EntityType(Type type, Function variableNameFunction) { - this(type, new LinkedHashSet(), variableNameFunction); - } - - /** - * Create a new {@code EntityType} instance for the given type and superTypes - * - * @param type - * @param superTypes - */ - public EntityType(Type type, Set superTypes) { - this(type, superTypes, DefaultVariableNameFunction.INSTANCE); - } - - /** - * Create a new {@code EntityType} instance for the given type and superTypes - * - * @param type the type to be used - * @param superTypes the super types to be used - * @param variableNameFunction the variable name function to be used - */ - private EntityType(Type type, Set superTypes, Function variableNameFunction) { - super(type); - this.superTypes = superTypes; - this.modifiedSimpleName = variableNameFunction.apply(this); - } - - public void addAnnotation(Annotation annotation) { - annotations.put(annotation.annotationType(), annotation); - } - - public void addConstructor(Constructor co) { - constructors.add(co); - } - - public void addDelegate(Delegate delegate) { - delegates.add(delegate); - } - - public void addProperty(Property field) { - if (!propertyNames.contains(field.getName())) { - propertyNames.add(field.getName()); - escapedPropertyNames.add(field.getEscapedName()); - properties.add(validateField(field)); - } - } - - public void addSupertype(Supertype entityType) { - superTypes.add(entityType); - } - - @Override - public int compareTo(EntityType o) { - return getType().getSimpleName().compareTo(o.getType().getSimpleName()); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Type) { - return getFullName().equals(((Type) o).getFullName()); - } else { - return false; - } - } - - @SuppressWarnings("unchecked") - public T getAnnotation(Class type) { - return (T) annotations.get(type); - } - - public Collection getAnnotations() { - return annotations.values(); - } - - @Override - public Type as(TypeCategory category) { - if (getCategory() == category) { - return this; - } else { - return super.as(category); - } - } - - @Override - public TypeCategory getCategory() { - if (getType().getCategory() == TypeCategory.ENTITY || !properties.isEmpty()) { - return TypeCategory.ENTITY; - } else { - return TypeCategory.CUSTOM; - } - } - - public Set getConstructors() { - return constructors; - } - - public Map getData() { - return data; - } - - public Set getDelegates() { - return delegates; - } - - public TypeCategory getOriginalCategory() { - return super.getCategory(); - } - - public Set getProperties() { - return properties; - } - - @Nullable - public Supertype getSuperType() { - return superTypes.size() == 1 ? superTypes.iterator().next() : null; - } - - public Set getSuperTypes() { - return superTypes; - } - - /** - * Use {@link #getModifiedSimpleName()} - */ - @Deprecated - public String getUncapSimpleName() { - return modifiedSimpleName; - } - - public String getModifiedSimpleName() { - return modifiedSimpleName; - } - - @Override - public int hashCode() { - return getFullName().hashCode(); - } - - public boolean hasArrays() { - return hasPropertyWithType(TypeCategory.ARRAY); - } - - public boolean hasEntityFields() { - return hasPropertyWithType(TypeCategory.ENTITY); - } - - public boolean hasInits() { - for (Property property : properties) { - if (!property.getInits().isEmpty()) { - return true; - } - } - return false; - } - - public boolean hasLists() { - return hasPropertyWithType(TypeCategory.LIST); - } - - public boolean hasCollections() { - return hasPropertyWithType(TypeCategory.COLLECTION); - } - - public boolean hasSets() { - return hasPropertyWithType(TypeCategory.SET); - } - - public boolean hasMaps() { - return hasPropertyWithType(TypeCategory.MAP); - } - - private boolean hasPropertyWithType(TypeCategory category) { - for (Property property : properties) { - if (property.getType().getCategory() == category) { - return true; - } - } - return false; - } - - public void include(Supertype supertype) { - EntityType entityType = supertype.getEntityType(); - for (Delegate delegate : entityType.getDelegates()) { - addDelegate(delegate); - } - for (Property property : entityType.getProperties()) { - addProperty(property.createCopy(this)); - } - } - - private Property validateField(Property field) { - if (field.getName().equals(modifiedSimpleName) || field.getEscapedName().equals(modifiedSimpleName)) { - do { - modifiedSimpleName = StringUtils.uncapitalize(getType().getSimpleName()) + (escapeSuffix++); - } while (propertyNames.contains(modifiedSimpleName)); - } - return field; - } - - public Set getPropertyNames() { - return propertyNames; - } - - public Set getEscapedPropertyNames() { - return escapedPropertyNames; - } - - public Type getInnerType() { - return type; - } - + private final Map, Annotation> annotations = new HashMap, Annotation>(); + + private final Set constructors = new LinkedHashSet(); + + private int escapeSuffix = 1; + + private final Set delegates = new HashSet(); + + private final Set properties = new TreeSet(); + + private final Set propertyNames = new HashSet(); + + private final Set escapedPropertyNames = new HashSet(); + + private final Set superTypes; + + private final Map data = new HashMap(); + + private String modifiedSimpleName; + + /** + * Create a new {@code EntityType} instance for the given type + * + * @param type + */ + public EntityType(Type type) { + this(type, new LinkedHashSet(), DefaultVariableNameFunction.INSTANCE); + } + + /** + * Create a new {@code EntityType} instance for the given type + * + * @param type the type to be used + * @param variableNameFunction the variable name function to be used + */ + public EntityType(Type type, Function variableNameFunction) { + this(type, new LinkedHashSet(), variableNameFunction); + } + + /** + * Create a new {@code EntityType} instance for the given type and superTypes + * + * @param type + * @param superTypes + */ + public EntityType(Type type, Set superTypes) { + this(type, superTypes, DefaultVariableNameFunction.INSTANCE); + } + + /** + * Create a new {@code EntityType} instance for the given type and superTypes + * + * @param type the type to be used + * @param superTypes the super types to be used + * @param variableNameFunction the variable name function to be used + */ + private EntityType( + Type type, Set superTypes, Function variableNameFunction) { + super(type); + this.superTypes = superTypes; + this.modifiedSimpleName = variableNameFunction.apply(this); + } + + public void addAnnotation(Annotation annotation) { + annotations.put(annotation.annotationType(), annotation); + } + + public void addConstructor(Constructor co) { + constructors.add(co); + } + + public void addDelegate(Delegate delegate) { + delegates.add(delegate); + } + + public void addProperty(Property field) { + if (!propertyNames.contains(field.getName())) { + propertyNames.add(field.getName()); + escapedPropertyNames.add(field.getEscapedName()); + properties.add(validateField(field)); + } + } + + public void addSupertype(Supertype entityType) { + superTypes.add(entityType); + } + + @Override + public int compareTo(EntityType o) { + return getType().getSimpleName().compareTo(o.getType().getSimpleName()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Type) { + return getFullName().equals(((Type) o).getFullName()); + } else { + return false; + } + } + + @SuppressWarnings("unchecked") + public T getAnnotation(Class type) { + return (T) annotations.get(type); + } + + public Collection getAnnotations() { + return annotations.values(); + } + + @Override + public Type as(TypeCategory category) { + if (getCategory() == category) { + return this; + } else { + return super.as(category); + } + } + + @Override + public TypeCategory getCategory() { + if (getType().getCategory() == TypeCategory.ENTITY || !properties.isEmpty()) { + return TypeCategory.ENTITY; + } else { + return TypeCategory.CUSTOM; + } + } + + public Set getConstructors() { + return constructors; + } + + public Map getData() { + return data; + } + + public Set getDelegates() { + return delegates; + } + + public TypeCategory getOriginalCategory() { + return super.getCategory(); + } + + public Set getProperties() { + return properties; + } + + @Nullable + public Supertype getSuperType() { + return superTypes.size() == 1 ? superTypes.iterator().next() : null; + } + + public Set getSuperTypes() { + return superTypes; + } + + /** Use {@link #getModifiedSimpleName()} */ + @Deprecated + public String getUncapSimpleName() { + return modifiedSimpleName; + } + + public String getModifiedSimpleName() { + return modifiedSimpleName; + } + + @Override + public int hashCode() { + return getFullName().hashCode(); + } + + public boolean hasArrays() { + return hasPropertyWithType(TypeCategory.ARRAY); + } + + public boolean hasEntityFields() { + return hasPropertyWithType(TypeCategory.ENTITY); + } + + public boolean hasInits() { + for (Property property : properties) { + if (!property.getInits().isEmpty()) { + return true; + } + } + return false; + } + + public boolean hasLists() { + return hasPropertyWithType(TypeCategory.LIST); + } + + public boolean hasCollections() { + return hasPropertyWithType(TypeCategory.COLLECTION); + } + + public boolean hasSets() { + return hasPropertyWithType(TypeCategory.SET); + } + + public boolean hasMaps() { + return hasPropertyWithType(TypeCategory.MAP); + } + + private boolean hasPropertyWithType(TypeCategory category) { + for (Property property : properties) { + if (property.getType().getCategory() == category) { + return true; + } + } + return false; + } + + public void include(Supertype supertype) { + EntityType entityType = supertype.getEntityType(); + for (Delegate delegate : entityType.getDelegates()) { + addDelegate(delegate); + } + for (Property property : entityType.getProperties()) { + addProperty(property.createCopy(this)); + } + } + + private Property validateField(Property field) { + if (field.getName().equals(modifiedSimpleName) + || field.getEscapedName().equals(modifiedSimpleName)) { + do { + modifiedSimpleName = StringUtils.uncapitalize(getType().getSimpleName()) + (escapeSuffix++); + } while (propertyNames.contains(modifiedSimpleName)); + } + return field; + } + + public Set getPropertyNames() { + return propertyNames; + } + + public Set getEscapedPropertyNames() { + return escapedPropertyNames; + } + + public Type getInnerType() { + return type; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Extension.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Extension.java index 7dfca17eaa..224908f590 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Extension.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Extension.java @@ -14,18 +14,17 @@ package com.querydsl.codegen; /** - * {@code Extension} allows for custom code generation extensions to be registered as service provider + * {@code Extension} allows for custom code generation extensions to be registered as service + * provider * * @author Jan-Willem Gmelig Meyling - * */ public interface Extension { - /** - * Register custom types to the given codegen module - * - * @param module module to be customized - */ - void addSupport(AbstractModule module); - + /** + * Register custom types to the given codegen module + * + * @param module module to be customized + */ + void addSupport(AbstractModule module); } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Filer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Filer.java index 139df581a4..18f5a813e7 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Filer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Filer.java @@ -13,11 +13,11 @@ */ package com.querydsl.codegen; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.Element; import java.io.IOException; import java.io.Writer; import java.util.Collection; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.Element; /** * provides files in annotation processing to write classes to @@ -25,5 +25,9 @@ * @author f43nd1r */ public interface Filer { - Writer createFile(ProcessingEnvironment processingEnvironment, String classname, Collection elements) throws IOException; + Writer createFile( + ProcessingEnvironment processingEnvironment, + String classname, + Collection elements) + throws IOException; } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/GeneratedAnnotationResolver.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/GeneratedAnnotationResolver.java index 4f517411c2..3bb2badb12 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/GeneratedAnnotationResolver.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/GeneratedAnnotationResolver.java @@ -1,72 +1,77 @@ package com.querydsl.codegen; -import org.jetbrains.annotations.Nullable; - import java.lang.annotation.Annotation; +import org.jetbrains.annotations.Nullable; /** - * {@code GeneratedAnnotationClassResolver} provides class name resolving functionality for resolving the annotation - * type to be used on {@link Serializer}s generated sources. + * {@code GeneratedAnnotationClassResolver} provides class name resolving functionality for + * resolving the annotation type to be used on {@link Serializer}s generated sources. */ public final class GeneratedAnnotationResolver { - private static final Class DEFAULT_GENERATED_ANNOTATION_CLASS = resolveJavaDefault(); - - /** - * Use the {@code generatedAnnotationClass} or use the JDK one. - *

- * A {@code null generatedAnnotationClass} will resolve to the java {@code @Generated} annotation (can be of type {@code javax.annotation.Generated} - * or {@code javax.annotation.processing.Generated} depending on the java version. - * - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) - * to use or {@code null}. - * @return the provided {@code generatedAnnotationClass} if not {@code null} or the one from java. Never {@code null}. - * @see Single-Element Annotation - */ - public static Class resolve(@Nullable String generatedAnnotationClass) { - if (generatedAnnotationClass != null) { - try { - return (Class) Class.forName(generatedAnnotationClass); - } catch (Exception e) { - // Try next one - } - } + private static final Class DEFAULT_GENERATED_ANNOTATION_CLASS = + resolveJavaDefault(); - return resolveDefault(); + /** + * Use the {@code generatedAnnotationClass} or use the JDK one. + * + *

A {@code null generatedAnnotationClass} will resolve to the java {@code @Generated} + * annotation (can be of type {@code javax.annotation.Generated} or {@code + * javax.annotation.processing.Generated} depending on the java version. + * + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to use or {@code null}. + * @return the provided {@code generatedAnnotationClass} if not {@code null} or the one from java. + * Never {@code null}. + * @see Single-Element + * Annotation + */ + public static Class resolve(@Nullable String generatedAnnotationClass) { + if (generatedAnnotationClass != null) { + try { + return (Class) Class.forName(generatedAnnotationClass); + } catch (Exception e) { + // Try next one + } } - /** - * Resolve the java {@code @Generated} annotation (can be of type {@code javax.annotation.Generated} - * or {@code javax.annotation.processing.Generated} depending on the java version. - * - * @return the Generated annotation class from java. Never {@code null}. - */ - public static Class resolveDefault() { - return DEFAULT_GENERATED_ANNOTATION_CLASS; - } + return resolveDefault(); + } - @SuppressWarnings("unchecked") - private static Class resolveJavaDefault() { - try { - return (Class) Class.forName("javax.annotation.processing.Generated"); - } catch (Exception e) { - // Try next one - } + /** + * Resolve the java {@code @Generated} annotation (can be of type {@code + * javax.annotation.Generated} or {@code javax.annotation.processing.Generated} depending on the + * java version. + * + * @return the Generated annotation class from java. Never {@code null}. + */ + public static Class resolveDefault() { + return DEFAULT_GENERATED_ANNOTATION_CLASS; + } - try { - return (Class) Class.forName("javax.annotation.Generated"); - } catch (Exception e) { - // Try next one - } + @SuppressWarnings("unchecked") + private static Class resolveJavaDefault() { + try { + return (Class) Class.forName("javax.annotation.processing.Generated"); + } catch (Exception e) { + // Try next one + } - try { - return (Class) Class.forName("jakarta.annotation.Generated"); - } catch (Exception e) { - // Try next one - } + try { + return (Class) Class.forName("javax.annotation.Generated"); + } catch (Exception e) { + // Try next one + } - throw new IllegalStateException("Can't find Generated annotation"); + try { + return (Class) Class.forName("jakarta.annotation.Generated"); + } catch (Exception e) { + // Try next one } - private GeneratedAnnotationResolver() { } + throw new IllegalStateException("Can't find Generated annotation"); + } + + private GeneratedAnnotationResolver() {} } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/GenericExporter.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/GenericExporter.java index 1764e2a8c2..66e4c8a4f2 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/GenericExporter.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/GenericExporter.java @@ -35,8 +35,6 @@ import com.querydsl.core.util.Annotations; import com.querydsl.core.util.BeanUtils; import com.querydsl.core.util.ReflectionUtils; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -60,23 +58,24 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; +import org.jetbrains.annotations.Nullable; /** - * {@code GenericExporter} provides query type serialization logic for cases where APT annotation processors - * can't be used. {@code GenericExporter} scans the classpath for classes annotated with specified annotations - * in specific packages and mirrors them into Querydsl expression types. + * {@code GenericExporter} provides query type serialization logic for cases where APT annotation + * processors can't be used. {@code GenericExporter} scans the classpath for classes annotated with + * specified annotations in specific packages and mirrors them into Querydsl expression types. + * + *

Example with Querydsl annotations: * - *

Example with Querydsl annotations:

- *
- * {@code
+ * 
{@code
  * GenericExporter exporter = new GenericExporter();
  * exporter.setTargetFolder(new File("target/generated-sources/java"));
- * exporter.export(com.example.domain.Entity.class.getPackage());}
- * 
+ * exporter.export(com.example.domain.Entity.class.getPackage()); + * }
* - *

Example with JPA annotations:

- *
- * {@code
+ * 

Example with JPA annotations: + * + *

{@code
  * GenericExporter exporter = new GenericExporter();
  * exporter.setKeywords(Keywords.JPA);
  * exporter.setEntityAnnotation(Entity.class);
@@ -85,745 +84,752 @@
  * exporter.setSupertypeAnnotation(MappedSuperclass.class);
  * exporter.setSkipAnnotation(Transient.class);
  * exporter.setTargetFolder(new File("target/generated-sources/java"));
- * exporter.export(com.example.domain.Entity.class.getPackage());}
- * 
+ * exporter.export(com.example.domain.Entity.class.getPackage()); + * }
* * @author tiwe - * */ public class GenericExporter { - private Class entityAnnotation = QueryEntity.class; - - private Class supertypeAnnotation = QuerySupertype.class; + private Class entityAnnotation = QueryEntity.class; - private Class embeddableAnnotation = QueryEmbeddable.class; + private Class supertypeAnnotation = QuerySupertype.class; - private Class embeddedAnnotation = QueryEmbedded.class; + private Class embeddableAnnotation = QueryEmbeddable.class; - private Class skipAnnotation = QueryTransient.class; + private Class embeddedAnnotation = QueryEmbedded.class; - private boolean createScalaSources = false; + private Class skipAnnotation = QueryTransient.class; - private final Set> stopClasses = new HashSet<>(); + private boolean createScalaSources = false; - private final Map allTypes = new HashMap<>(); + private final Set> stopClasses = new HashSet<>(); - private final Map, EntityType> entityTypes = new HashMap<>(); + private final Map allTypes = new HashMap<>(); - private final Map, EntityType> superTypes = new HashMap<>(); + private final Map, EntityType> entityTypes = new HashMap<>(); - private final Map, EntityType> embeddableTypes = new HashMap<>(); + private final Map, EntityType> superTypes = new HashMap<>(); - private final Map, EntityType> projectionTypes = new HashMap<>(); + private final Map, EntityType> embeddableTypes = new HashMap<>(); - private final CodegenModule codegenModule = new CodegenModule(); + private final Map, EntityType> projectionTypes = new HashMap<>(); - private SerializerConfig serializerConfig = SimpleSerializerConfig.DEFAULT; + private final CodegenModule codegenModule = new CodegenModule(); - @Deprecated - private boolean handleFields = true, handleMethods = true; + private SerializerConfig serializerConfig = SimpleSerializerConfig.DEFAULT; - private PropertyHandling propertyHandling = PropertyHandling.ALL; + @Deprecated private boolean handleFields = true, handleMethods = true; - private boolean useFieldTypes = false; + private PropertyHandling propertyHandling = PropertyHandling.ALL; - @Nullable - private File targetFolder; + private boolean useFieldTypes = false; - @Nullable - private TypeFactory typeFactory; + @Nullable private File targetFolder; - private final List annotationHelpers = new ArrayList<>(); + @Nullable private TypeFactory typeFactory; - @Nullable - private TypeMappings typeMappings; + private final List annotationHelpers = new ArrayList<>(); - @Nullable - private QueryTypeFactory queryTypeFactory; + @Nullable private TypeMappings typeMappings; - @Nullable - private Class serializerClass; + @Nullable private QueryTypeFactory queryTypeFactory; - private final Charset charset; + @Nullable private Class serializerClass; - private final ClassLoader classLoader; + private final Charset charset; - private Set generatedFiles = new HashSet(); + private final ClassLoader classLoader; - private boolean strictMode; + private Set generatedFiles = new HashSet(); + private boolean strictMode; - /** - * Create a GenericExporter instance using the given classloader and charset for serializing - * source files - * - * @param classLoader classloader to use - * @param charset charset of target sources - */ - public GenericExporter(ClassLoader classLoader, Charset charset) { - this.classLoader = classLoader; - this.charset = charset; - stopClasses.add(Object.class); - stopClasses.add(Enum.class); - } + /** + * Create a GenericExporter instance using the given classloader and charset for serializing + * source files + * + * @param classLoader classloader to use + * @param charset charset of target sources + */ + public GenericExporter(ClassLoader classLoader, Charset charset) { + this.classLoader = classLoader; + this.charset = charset; + stopClasses.add(Object.class); + stopClasses.add(Enum.class); + } - /** - * Create a GenericExporter instance using the given classloader and default charset - * - * @param classLoader classloader to use - */ - public GenericExporter(ClassLoader classLoader) { - this(classLoader, Charset.defaultCharset()); - } + /** + * Create a GenericExporter instance using the given classloader and default charset + * + * @param classLoader classloader to use + */ + public GenericExporter(ClassLoader classLoader) { + this(classLoader, Charset.defaultCharset()); + } - /** - * Create a GenericExporter instance using the context classloader and the given charset - * - * @param charset charset of target sources - */ - public GenericExporter(Charset charset) { - this(Thread.currentThread().getContextClassLoader(), charset); - } + /** + * Create a GenericExporter instance using the context classloader and the given charset + * + * @param charset charset of target sources + */ + public GenericExporter(Charset charset) { + this(Thread.currentThread().getContextClassLoader(), charset); + } - /** - * Create a GenericExporter instance using the context classloader and default charset - */ - public GenericExporter() { - this(Thread.currentThread().getContextClassLoader(), Charset.defaultCharset()); - } + /** Create a GenericExporter instance using the context classloader and default charset */ + public GenericExporter() { + this(Thread.currentThread().getContextClassLoader(), Charset.defaultCharset()); + } - /** - * Export the given packages - * - * @param packages packages to be scanned - */ - public void export(Package... packages) { - String[] pkgs = new String[packages.length]; - for (int i = 0; i < packages.length; i++) { - pkgs[i] = packages[i].getName(); - } - export(pkgs); - } - - /** - * Export the given packages - * - * @param packages packages to be scanned - */ - public void export(String... packages) { - scanPackages(packages); - innerExport(); - } - - /** - * Export the given classes - * - * @param classes classes to be scanned - */ - public void export(Class...classes) { - for (Class cl : classes) { - handleClass(cl); - } - innerExport(); + /** + * Export the given packages + * + * @param packages packages to be scanned + */ + public void export(Package... packages) { + String[] pkgs = new String[packages.length]; + for (int i = 0; i < packages.length; i++) { + pkgs[i] = packages[i].getName(); } + export(pkgs); + } - @SuppressWarnings("unchecked") - private void innerExport() { - typeMappings = codegenModule.get(TypeMappings.class); - queryTypeFactory = codegenModule.get(QueryTypeFactory.class); - typeFactory = new TypeFactory(Arrays.asList(entityAnnotation, supertypeAnnotation, embeddableAnnotation), codegenModule.get(Function.class, CodegenModule.VARIABLE_NAME_FUNCTION_CLASS)); - - // copy annotations helpers to typeFactory - for (AnnotationHelper helper : annotationHelpers) { - typeFactory.addAnnotationHelper(helper); - } - - // process supertypes - for (Class cl : superTypes.keySet()) { - createEntityType(cl, superTypes); - } - - // process embeddables - for (Class cl : embeddableTypes.keySet()) { - createEntityType(cl, embeddableTypes); - } - - // process entities - for (Class cl : entityTypes.keySet()) { - createEntityType(cl, entityTypes); - } + /** + * Export the given packages + * + * @param packages packages to be scanned + */ + public void export(String... packages) { + scanPackages(packages); + innerExport(); + } - // process projections - for (Class cl : projectionTypes.keySet()) { - createEntityType(cl, projectionTypes); - } - - // add constructors and properties - for (Map, EntityType> entries : Arrays.asList(superTypes, embeddableTypes, entityTypes, projectionTypes)) { - for (Map.Entry, EntityType> entry : new HashSet<>(entries.entrySet())) { - addConstructors(entry.getKey(), entry.getValue()); - addProperties(entry.getKey(), entry.getValue()); - } - } - - // merge supertype fields into subtypes - Set handled = new HashSet(); - for (EntityType type : superTypes.values()) { - addSupertypeFields(type, allTypes, handled); - } - for (EntityType type : entityTypes.values()) { - addSupertypeFields(type, allTypes, handled); - } - for (EntityType type : embeddableTypes.values()) { - addSupertypeFields(type, allTypes, handled); - } - - // extend types - typeFactory.extendTypes(); - - try { - Serializer supertypeSerializer, entitySerializer, embeddableSerializer, projectionSerializer; - - if (serializerClass != null) { - Serializer serializer = codegenModule.get(serializerClass); - supertypeSerializer = serializer; - entitySerializer = serializer; - embeddableSerializer = serializer; - projectionSerializer = serializer; - } else { - supertypeSerializer = codegenModule.get(SupertypeSerializer.class); - entitySerializer = codegenModule.get(EntitySerializer.class); - embeddableSerializer = codegenModule.get(EmbeddableSerializer.class); - projectionSerializer = codegenModule.get(ProjectionSerializer.class); - } - - // serialize super types - serialize(supertypeSerializer, superTypes); - - // serialize entity types - serialize(entitySerializer, entityTypes); - - // serialize embeddable types - serialize(embeddableSerializer, embeddableTypes); - - // serialize projection types - serialize(projectionSerializer, projectionTypes); - - } catch (IOException e) { - throw new QueryException(e); - } - - } - - private void addSupertypeFields(EntityType model, Map superTypes, - Set handled) { - if (handled.add(model)) { - for (Supertype supertype : model.getSuperTypes()) { - EntityType entityType = superTypes.get(supertype.getType().getFullName()); - if (entityType == null) { - if (supertype.getType().getPackageName().startsWith("java.")) { - // skip internal supertypes - continue; - } - // FIXME this misses the generics - Class cl = supertype.getType().getJavaClass(); - typeFactory.addEmbeddableType(cl); - entityType = createEntityType(cl, new HashMap, EntityType>()); - addProperties(cl, entityType); - - } - addSupertypeFields(entityType, superTypes, handled); - supertype.setEntityType(entityType); - model.include(supertype); - } - } + /** + * Export the given classes + * + * @param classes classes to be scanned + */ + public void export(Class... classes) { + for (Class cl : classes) { + handleClass(cl); } + innerExport(); + } - private boolean containsAny(Class clazz, Class... annotations) { - for (Class annType : annotations) { - if (clazz.isAnnotationPresent(annType)) { - return true; + @SuppressWarnings("unchecked") + private void innerExport() { + typeMappings = codegenModule.get(TypeMappings.class); + queryTypeFactory = codegenModule.get(QueryTypeFactory.class); + typeFactory = + new TypeFactory( + Arrays.asList(entityAnnotation, supertypeAnnotation, embeddableAnnotation), + codegenModule.get(Function.class, CodegenModule.VARIABLE_NAME_FUNCTION_CLASS)); + + // copy annotations helpers to typeFactory + for (AnnotationHelper helper : annotationHelpers) { + typeFactory.addAnnotationHelper(helper); + } + + // process supertypes + for (Class cl : superTypes.keySet()) { + createEntityType(cl, superTypes); + } + + // process embeddables + for (Class cl : embeddableTypes.keySet()) { + createEntityType(cl, embeddableTypes); + } + + // process entities + for (Class cl : entityTypes.keySet()) { + createEntityType(cl, entityTypes); + } + + // process projections + for (Class cl : projectionTypes.keySet()) { + createEntityType(cl, projectionTypes); + } + + // add constructors and properties + for (Map, EntityType> entries : + Arrays.asList(superTypes, embeddableTypes, entityTypes, projectionTypes)) { + for (Map.Entry, EntityType> entry : new HashSet<>(entries.entrySet())) { + addConstructors(entry.getKey(), entry.getValue()); + addProperties(entry.getKey(), entry.getValue()); + } + } + + // merge supertype fields into subtypes + Set handled = new HashSet(); + for (EntityType type : superTypes.values()) { + addSupertypeFields(type, allTypes, handled); + } + for (EntityType type : entityTypes.values()) { + addSupertypeFields(type, allTypes, handled); + } + for (EntityType type : embeddableTypes.values()) { + addSupertypeFields(type, allTypes, handled); + } + + // extend types + typeFactory.extendTypes(); + + try { + Serializer supertypeSerializer, entitySerializer, embeddableSerializer, projectionSerializer; + + if (serializerClass != null) { + Serializer serializer = codegenModule.get(serializerClass); + supertypeSerializer = serializer; + entitySerializer = serializer; + embeddableSerializer = serializer; + projectionSerializer = serializer; + } else { + supertypeSerializer = codegenModule.get(SupertypeSerializer.class); + entitySerializer = codegenModule.get(EntitySerializer.class); + embeddableSerializer = codegenModule.get(EmbeddableSerializer.class); + projectionSerializer = codegenModule.get(ProjectionSerializer.class); + } + + // serialize super types + serialize(supertypeSerializer, superTypes); + + // serialize entity types + serialize(entitySerializer, entityTypes); + + // serialize embeddable types + serialize(embeddableSerializer, embeddableTypes); + + // serialize projection types + serialize(projectionSerializer, projectionTypes); + + } catch (IOException e) { + throw new QueryException(e); + } + } + + private void addSupertypeFields( + EntityType model, Map superTypes, Set handled) { + if (handled.add(model)) { + for (Supertype supertype : model.getSuperTypes()) { + EntityType entityType = superTypes.get(supertype.getType().getFullName()); + if (entityType == null) { + if (supertype.getType().getPackageName().startsWith("java.")) { + // skip internal supertypes + continue; + } + // FIXME this misses the generics + Class cl = supertype.getType().getJavaClass(); + typeFactory.addEmbeddableType(cl); + entityType = createEntityType(cl, new HashMap, EntityType>()); + addProperties(cl, entityType); + } + addSupertypeFields(entityType, superTypes, handled); + supertype.setEntityType(entityType); + model.include(supertype); + } + } + } + + private boolean containsAny(Class clazz, Class... annotations) { + for (Class annType : annotations) { + if (clazz.isAnnotationPresent(annType)) { + return true; + } + } + return false; + } + + private EntityType createEntityType(Class cl, Map, EntityType> types) { + if (types.get(cl) != null) { + return types.get(cl); + } else { + EntityType type = allTypes.get(ClassUtils.getFullName(cl)); + if (type == null) { + type = typeFactory.getEntityType(cl); + } + types.put(cl, type); + String fullName = ClassUtils.getFullName(cl); + if (!allTypes.containsKey(fullName)) { + allTypes.put(fullName, type); + } + + typeMappings.register(type, queryTypeFactory.create(type)); + + if (strictMode && cl.getSuperclass() != null) { + @SuppressWarnings("unchecked") + Class[] annotations = + (Class[]) + new Class[] {entityAnnotation, supertypeAnnotation, embeddableAnnotation}; + if (!containsAny(cl.getSuperclass(), annotations)) { + // skip supertype handling + return type; + } + } + + if (cl.getSuperclass() != null + && !stopClasses.contains(cl.getSuperclass()) + && !cl.getSuperclass().isAnnotationPresent(QueryExclude.class)) { + type.addSupertype( + new Supertype(typeFactory.get(cl.getSuperclass(), cl.getGenericSuperclass()))); + } + if (cl.isInterface()) { + for (Class iface : cl.getInterfaces()) { + if (!stopClasses.contains(iface) && !iface.isAnnotationPresent(QueryExclude.class)) { + type.addSupertype(new Supertype(typeFactory.get(iface))); + } + } + } + + return type; + } + } + + private void addConstructors(Class cl, EntityType type) { + for (Constructor constructor : cl.getConstructors()) { + if (constructor.isAnnotationPresent(QueryProjection.class)) { + List parameters = new ArrayList<>(); + for (int i = 0; i < constructor.getParameterTypes().length; i++) { + Type parameterType = + typeFactory.get( + constructor.getParameterTypes()[i], constructor.getGenericParameterTypes()[i]); + for (Annotation annotation : constructor.getParameterAnnotations()[i]) { + if (annotation.annotationType().equals(QueryType.class)) { + QueryType queryType = (QueryType) annotation; + parameterType = parameterType.as(TypeCategory.valueOf(queryType.value().name())); } - } - return false; - } - - private EntityType createEntityType(Class cl, Map, EntityType> types) { - if (types.get(cl) != null) { - return types.get(cl); - } else { - EntityType type = allTypes.get(ClassUtils.getFullName(cl)); - if (type == null) { - type = typeFactory.getEntityType(cl); - } - types.put(cl, type); - String fullName = ClassUtils.getFullName(cl); - if (!allTypes.containsKey(fullName)) { - allTypes.put(fullName, type); - } - - typeMappings.register(type, queryTypeFactory.create(type)); - - if (strictMode && cl.getSuperclass() != null) { - @SuppressWarnings("unchecked") - Class[] annotations = - (Class[]) new Class[] {entityAnnotation, supertypeAnnotation, embeddableAnnotation}; - if (!containsAny(cl.getSuperclass(), annotations)) { - // skip supertype handling - return type; - } - } - - if (cl.getSuperclass() != null && !stopClasses.contains(cl.getSuperclass()) - && !cl.getSuperclass().isAnnotationPresent(QueryExclude.class)) { - type.addSupertype(new Supertype(typeFactory.get(cl.getSuperclass(), cl.getGenericSuperclass()))); - } - if (cl.isInterface()) { - for (Class iface : cl.getInterfaces()) { - if (!stopClasses.contains(iface) && !iface.isAnnotationPresent(QueryExclude.class)) { - type.addSupertype(new Supertype(typeFactory.get(iface))); - } - } - } - - return type; - } - } - - private void addConstructors(Class cl, EntityType type) { - for (Constructor constructor : cl.getConstructors()) { - if (constructor.isAnnotationPresent(QueryProjection.class)) { - List parameters = new ArrayList<>(); - for (int i = 0; i < constructor.getParameterTypes().length; i++) { - Type parameterType = typeFactory.get( - constructor.getParameterTypes()[i], - constructor.getGenericParameterTypes()[i]); - for (Annotation annotation : constructor.getParameterAnnotations()[i]) { - if (annotation.annotationType().equals(QueryType.class)) { - QueryType queryType = (QueryType) annotation; - parameterType = parameterType.as(TypeCategory.valueOf(queryType.value().name())); - } - } - parameters.add(new Parameter("param" + i, parameterType)); - } - type.addConstructor(new com.querydsl.codegen.utils.model.Constructor(parameters)); - } - } - } - - private void addProperties(Class cl, EntityType type) { - Map types = new HashMap<>(); - Map annotations = new HashMap<>(); - - PropertyHandling.Config config = propertyHandling.getConfig(cl); - - // fields - if (config.isFields()) { - for (Field field : cl.getDeclaredFields()) { - if (!Modifier.isStatic(field.getModifiers())) { - if (Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(QueryType.class)) { - continue; - } - AnnotatedElement annotated = ReflectionUtils.getAnnotatedElement(cl, field.getName(), field.getType()); - Type propertyType = getPropertyType(cl, annotated, field.getType(), field.getGenericType()); - Annotations ann = new Annotations(field); - types.put(field.getName(), propertyType); - annotations.put(field.getName(), ann); - } - } - } - - // getters - if (config.isMethods()) { - for (Method method : cl.getDeclaredMethods()) { - String name = method.getName(); - if (method.getParameterTypes().length == 0 - && !Modifier.isStatic(method.getModifiers()) - && !method.isBridge() - && ((name.startsWith("get") && name.length() > 3) - || (name.startsWith("is") && name.length() > 2))) { - String propertyName; - if (name.startsWith("get")) { - propertyName = BeanUtils.uncapitalize(name.substring(3)); - } else { - propertyName = BeanUtils.uncapitalize(name.substring(2)); - } - Type propertyType = getPropertyType(cl, method, method.getReturnType(), method.getGenericReturnType()); - if (!types.containsKey(propertyName) || !useFieldTypes) { - types.put(propertyName, propertyType); - } - Annotations ann = annotations.get(propertyName); - if (ann == null) { - ann = new Annotations(); - annotations.put(propertyName, ann); - } - ann.addAnnotations(method); - } - } - } - - for (Map.Entry entry : types.entrySet()) { - Annotations ann = annotations.get(entry.getKey()); - Property property = createProperty(type, entry.getKey(), entry.getValue(), ann); - if (property != null) { - type.addProperty(property); - } - } - } - - private Type getPropertyType(Class cl, AnnotatedElement annotated, Class type, - java.lang.reflect.Type genericType) { - Type propertyType = null; - if (annotated.isAnnotationPresent(embeddedAnnotation)) { - Class embeddableType = type; - if (Collection.class.isAssignableFrom(type)) { - embeddableType = ReflectionUtils.getTypeParameterAsClass(genericType, 0); - } else if (Map.class.isAssignableFrom(type)) { - embeddableType = ReflectionUtils.getTypeParameterAsClass(genericType, 1); - } - if (!embeddableType.getName().startsWith("java.")) { - typeFactory.addEmbeddableType(embeddableType); - if (!embeddableTypes.containsKey(embeddableType) - && !entityTypes.containsKey(embeddableType) - && !superTypes.containsKey(embeddableType)) { - EntityType entityType = createEntityType(embeddableType, embeddableTypes); - addProperties(embeddableType, entityType); - if (embeddableType == type) { - propertyType = entityType; - } - } - } - } - if (propertyType == null) { - propertyType = typeFactory.get(type, annotated, genericType); - if (propertyType instanceof EntityType && !allTypes.containsKey(ClassUtils.getFullName(type))) { - String fullName = ClassUtils.getFullName(type); - if (!allTypes.containsKey(fullName)) { - allTypes.put(fullName, (EntityType) propertyType); - } - } - } - return propertyType; - } - - @Nullable - private Property createProperty(EntityType entityType, String propertyName, Type propertyType, - AnnotatedElement annotated) { - List inits = Collections.emptyList(); - if (annotated.isAnnotationPresent(skipAnnotation) - && !annotated.isAnnotationPresent(QueryType.class)) { - return null; - } - if (annotated.isAnnotationPresent(QueryInit.class)) { - inits = Arrays.asList(annotated.getAnnotation(QueryInit.class).value()); - } - if (annotated.isAnnotationPresent(QueryType.class)) { - QueryType queryType = annotated.getAnnotation(QueryType.class); - if (queryType.value().equals(PropertyType.NONE)) { - return null; - } - propertyType = propertyType.as(TypeCategory.valueOf(queryType.value().name())); - } - return new Property(entityType, propertyName, propertyType, inits); - } - - private void scanPackages(String... packages) { - if (packages == null) { - return; - } - for (String pkg : packages) { - try { - for (Class cl : ClassPathUtils.scanPackage(classLoader, pkg)) { - handleClass(cl); - } - } catch (IOException e) { - throw new QueryException(e); - } - } - } - - private void handleClass(Class cl) { - if (stopClasses.contains(cl) || cl.isAnnotationPresent(QueryExclude.class)) { - return; - } else if (cl.isAnnotationPresent(entityAnnotation)) { - entityTypes.put(cl, null); - } else if (cl.isAnnotationPresent(embeddableAnnotation)) { - embeddableTypes.put(cl, null); - } else if (cl.isAnnotationPresent(supertypeAnnotation)) { - superTypes.put(cl, null); - } else { - for (Constructor constructor : cl.getConstructors()) { - if (constructor.isAnnotationPresent(QueryProjection.class)) { - projectionTypes.put(cl, null); - break; - } - } - } - } - - private void serialize(Serializer serializer, Map, EntityType> types) throws IOException { - for (Map.Entry, EntityType> entityType : types.entrySet()) { - Type type = typeMappings.getPathType(entityType.getValue(), entityType.getValue(), true); - String packageName = type.getPackageName(); - String className = packageName.length() > 0 ? (packageName + "." + type.getSimpleName()) : type.getSimpleName(); - SerializerConfig config = serializerConfig; - if (entityType.getKey().isAnnotationPresent(Config.class)) { - config = SimpleSerializerConfig.getConfig(entityType.getKey().getAnnotation(Config.class)); - } - String fileSuffix = createScalaSources ? ".scala" : ".java"; - write(serializer, className.replace('.', '/') + fileSuffix, config, entityType.getValue()); - } - } - - private void write(Serializer serializer, String path, SerializerConfig serializerConfig, - EntityType type) throws IOException { - File targetFile = new File(targetFolder, path); - generatedFiles.add(targetFile); - try (Writer w = writerFor(targetFile)) { - CodeWriter writer = createScalaSources ? new ScalaWriter(w) : new JavaWriter(w); - serializer.serialize(type, serializerConfig, writer); - } - } - - private Writer writerFor(File file) { - if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { - System.err.println("Folder " + file.getParent() + " could not be created"); - } - try { - return new OutputStreamWriter(new FileOutputStream(file), charset); - } catch (FileNotFoundException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - - /** - * Return the set of generated files - * - * @return a set of generated files - */ - public Set getGeneratedFiles() { - return generatedFiles; - } - - /** - * Set the entity annotation - * - * @param entityAnnotation entity annotation - */ - public void setEntityAnnotation(Class entityAnnotation) { - this.entityAnnotation = entityAnnotation; - } - - /** - * Set the supertype annotation - * - * @param supertypeAnnotation supertype annotation - */ - public void setSupertypeAnnotation( - Class supertypeAnnotation) { - this.supertypeAnnotation = supertypeAnnotation; - } - - /** - * Set the embeddable annotation - * - * @param embeddableAnnotation embeddable annotation - */ - public void setEmbeddableAnnotation( - Class embeddableAnnotation) { - this.embeddableAnnotation = embeddableAnnotation; - } - - /** - * Set the embedded annotation - * - * @param embeddedAnnotation embedded annotation - */ - public void setEmbeddedAnnotation(Class embeddedAnnotation) { - this.embeddedAnnotation = embeddedAnnotation; - } - - /** - * Set the skip annotation - * - * @param skipAnnotation skip annotation - */ - public void setSkipAnnotation(Class skipAnnotation) { - this.skipAnnotation = skipAnnotation; - } - - /** - * Set the target folder for generated sources - * - * @param targetFolder - */ - public void setTargetFolder(File targetFolder) { - this.targetFolder = targetFolder; - } - - /** - * Set the serializer class to be used - * - * @param serializerClass - */ - public void setSerializerClass(Class serializerClass) { - codegenModule.bind(serializerClass); - this.serializerClass = serializerClass; - } - - /** - * Set the typemappings class to be used - * - * @param typeMappingsClass - */ - public void setTypeMappingsClass(Class typeMappingsClass) { - codegenModule.bind(TypeMappings.class, typeMappingsClass); - } - - /** - * Set whether Scala sources are generated - * - * @param createScalaSources - */ - public void setCreateScalaSources(boolean createScalaSources) { - this.createScalaSources = createScalaSources; - } - - /** - * Set the keywords to be used - * - * @param keywords - */ - public void setKeywords(Collection keywords) { - codegenModule.bind(CodegenModule.KEYWORDS, keywords); - } - - /** - * Set the name prefix - * - * @param prefix - */ - public void setNamePrefix(String prefix) { - codegenModule.bind(CodegenModule.PREFIX, prefix); - } - - /** - * Set the name suffix - * - * @param suffix - */ - public void setNameSuffix(String suffix) { - codegenModule.bind(CodegenModule.SUFFIX, suffix); - } - - /** - * Set the package suffix - * - * @param suffix - */ - public void setPackageSuffix(String suffix) { - codegenModule.bind(CodegenModule.PACKAGE_SUFFIX, suffix); - } - - /** - * Set whether fields are handled (default true) - * - * @param b - * @deprecated Use {@link #setPropertyHandling(PropertyHandling)} instead - */ - @Deprecated - public void setHandleFields(boolean b) { - handleFields = b; - setPropertyHandling(); - } - - /** - * Set whether methods are handled (default true) - * - * @param b - * @deprecated Use {@link #setPropertyHandling(PropertyHandling)} instead - */ - @Deprecated - public void setHandleMethods(boolean b) { - handleMethods = b; - setPropertyHandling(); - } - - private void setPropertyHandling() { - if (handleFields) { - propertyHandling = handleMethods ? PropertyHandling.ALL : PropertyHandling.FIELDS; - } else if (handleMethods) { - propertyHandling = PropertyHandling.METHODS; - } else { - propertyHandling = PropertyHandling.NONE; - } - } - - /** - * Set the property handling mode - * - * @param propertyHandling - */ - public void setPropertyHandling(PropertyHandling propertyHandling) { - this.propertyHandling = propertyHandling; - } - - /** - * Set whether field types should be used instead of getter return types (default false) - * - * @param b - */ - public void setUseFieldTypes(boolean b) { - useFieldTypes = b; - } - - /** - * Add a stop class to be used (default Object.class and Enum.class) - * - * @param cl - */ - public void addStopClass(Class cl) { - stopClasses.add(cl); - } - - /** - * Set whether annotationless superclasses are handled or not (default: true) - * - * @param s - */ - public void setStrictMode(boolean s) { - strictMode = s; - } - - /** - * Set the serializer configuration to use - * - * @param serializerConfig - */ - public void setSerializerConfig(SerializerConfig serializerConfig) { - this.serializerConfig = serializerConfig; - } - - /** - * Add a annotation helper object to process custom annotations - * - * @param annotationHelper - */ - public void addAnnotationHelper(AnnotationHelper annotationHelper) { - annotationHelpers.add(annotationHelper); - } - - /** - * Set the Generated annotation class. Will default to java {@code @Generated} - * - * @param generatedAnnotationClass the fully qualified class name of the Single-Element Annotation (with {@code String} element) to be used on - * the generated sources, or {@code null} (defaulting to {@code javax.annotation.Generated} or - * {@code javax.annotation.processing.Generated} depending on the java version). - * @see Single-Element Annotation - */ - public void setGeneratedAnnotationClass(@Nullable String generatedAnnotationClass) { - codegenModule.bindInstance(CodegenModule.GENERATED_ANNOTATION_CLASS, GeneratedAnnotationResolver.resolve(generatedAnnotationClass)); - } + } + parameters.add(new Parameter("param" + i, parameterType)); + } + type.addConstructor(new com.querydsl.codegen.utils.model.Constructor(parameters)); + } + } + } + + private void addProperties(Class cl, EntityType type) { + Map types = new HashMap<>(); + Map annotations = new HashMap<>(); + + PropertyHandling.Config config = propertyHandling.getConfig(cl); + + // fields + if (config.isFields()) { + for (Field field : cl.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers())) { + if (Modifier.isTransient(field.getModifiers()) + && !field.isAnnotationPresent(QueryType.class)) { + continue; + } + AnnotatedElement annotated = + ReflectionUtils.getAnnotatedElement(cl, field.getName(), field.getType()); + Type propertyType = + getPropertyType(cl, annotated, field.getType(), field.getGenericType()); + Annotations ann = new Annotations(field); + types.put(field.getName(), propertyType); + annotations.put(field.getName(), ann); + } + } + } + + // getters + if (config.isMethods()) { + for (Method method : cl.getDeclaredMethods()) { + String name = method.getName(); + if (method.getParameterTypes().length == 0 + && !Modifier.isStatic(method.getModifiers()) + && !method.isBridge() + && ((name.startsWith("get") && name.length() > 3) + || (name.startsWith("is") && name.length() > 2))) { + String propertyName; + if (name.startsWith("get")) { + propertyName = BeanUtils.uncapitalize(name.substring(3)); + } else { + propertyName = BeanUtils.uncapitalize(name.substring(2)); + } + Type propertyType = + getPropertyType(cl, method, method.getReturnType(), method.getGenericReturnType()); + if (!types.containsKey(propertyName) || !useFieldTypes) { + types.put(propertyName, propertyType); + } + Annotations ann = annotations.get(propertyName); + if (ann == null) { + ann = new Annotations(); + annotations.put(propertyName, ann); + } + ann.addAnnotations(method); + } + } + } + + for (Map.Entry entry : types.entrySet()) { + Annotations ann = annotations.get(entry.getKey()); + Property property = createProperty(type, entry.getKey(), entry.getValue(), ann); + if (property != null) { + type.addProperty(property); + } + } + } + + private Type getPropertyType( + Class cl, AnnotatedElement annotated, Class type, java.lang.reflect.Type genericType) { + Type propertyType = null; + if (annotated.isAnnotationPresent(embeddedAnnotation)) { + Class embeddableType = type; + if (Collection.class.isAssignableFrom(type)) { + embeddableType = ReflectionUtils.getTypeParameterAsClass(genericType, 0); + } else if (Map.class.isAssignableFrom(type)) { + embeddableType = ReflectionUtils.getTypeParameterAsClass(genericType, 1); + } + if (!embeddableType.getName().startsWith("java.")) { + typeFactory.addEmbeddableType(embeddableType); + if (!embeddableTypes.containsKey(embeddableType) + && !entityTypes.containsKey(embeddableType) + && !superTypes.containsKey(embeddableType)) { + EntityType entityType = createEntityType(embeddableType, embeddableTypes); + addProperties(embeddableType, entityType); + if (embeddableType == type) { + propertyType = entityType; + } + } + } + } + if (propertyType == null) { + propertyType = typeFactory.get(type, annotated, genericType); + if (propertyType instanceof EntityType + && !allTypes.containsKey(ClassUtils.getFullName(type))) { + String fullName = ClassUtils.getFullName(type); + if (!allTypes.containsKey(fullName)) { + allTypes.put(fullName, (EntityType) propertyType); + } + } + } + return propertyType; + } + + @Nullable + private Property createProperty( + EntityType entityType, String propertyName, Type propertyType, AnnotatedElement annotated) { + List inits = Collections.emptyList(); + if (annotated.isAnnotationPresent(skipAnnotation) + && !annotated.isAnnotationPresent(QueryType.class)) { + return null; + } + if (annotated.isAnnotationPresent(QueryInit.class)) { + inits = Arrays.asList(annotated.getAnnotation(QueryInit.class).value()); + } + if (annotated.isAnnotationPresent(QueryType.class)) { + QueryType queryType = annotated.getAnnotation(QueryType.class); + if (queryType.value().equals(PropertyType.NONE)) { + return null; + } + propertyType = propertyType.as(TypeCategory.valueOf(queryType.value().name())); + } + return new Property(entityType, propertyName, propertyType, inits); + } + + private void scanPackages(String... packages) { + if (packages == null) { + return; + } + for (String pkg : packages) { + try { + for (Class cl : ClassPathUtils.scanPackage(classLoader, pkg)) { + handleClass(cl); + } + } catch (IOException e) { + throw new QueryException(e); + } + } + } + + private void handleClass(Class cl) { + if (stopClasses.contains(cl) || cl.isAnnotationPresent(QueryExclude.class)) { + return; + } else if (cl.isAnnotationPresent(entityAnnotation)) { + entityTypes.put(cl, null); + } else if (cl.isAnnotationPresent(embeddableAnnotation)) { + embeddableTypes.put(cl, null); + } else if (cl.isAnnotationPresent(supertypeAnnotation)) { + superTypes.put(cl, null); + } else { + for (Constructor constructor : cl.getConstructors()) { + if (constructor.isAnnotationPresent(QueryProjection.class)) { + projectionTypes.put(cl, null); + break; + } + } + } + } + + private void serialize(Serializer serializer, Map, EntityType> types) + throws IOException { + for (Map.Entry, EntityType> entityType : types.entrySet()) { + Type type = typeMappings.getPathType(entityType.getValue(), entityType.getValue(), true); + String packageName = type.getPackageName(); + String className = + packageName.length() > 0 + ? (packageName + "." + type.getSimpleName()) + : type.getSimpleName(); + SerializerConfig config = serializerConfig; + if (entityType.getKey().isAnnotationPresent(Config.class)) { + config = SimpleSerializerConfig.getConfig(entityType.getKey().getAnnotation(Config.class)); + } + String fileSuffix = createScalaSources ? ".scala" : ".java"; + write(serializer, className.replace('.', '/') + fileSuffix, config, entityType.getValue()); + } + } + + private void write( + Serializer serializer, String path, SerializerConfig serializerConfig, EntityType type) + throws IOException { + File targetFile = new File(targetFolder, path); + generatedFiles.add(targetFile); + try (Writer w = writerFor(targetFile)) { + CodeWriter writer = createScalaSources ? new ScalaWriter(w) : new JavaWriter(w); + serializer.serialize(type, serializerConfig, writer); + } + } + + private Writer writerFor(File file) { + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { + System.err.println("Folder " + file.getParent() + " could not be created"); + } + try { + return new OutputStreamWriter(new FileOutputStream(file), charset); + } catch (FileNotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + /** + * Return the set of generated files + * + * @return a set of generated files + */ + public Set getGeneratedFiles() { + return generatedFiles; + } + + /** + * Set the entity annotation + * + * @param entityAnnotation entity annotation + */ + public void setEntityAnnotation(Class entityAnnotation) { + this.entityAnnotation = entityAnnotation; + } + + /** + * Set the supertype annotation + * + * @param supertypeAnnotation supertype annotation + */ + public void setSupertypeAnnotation(Class supertypeAnnotation) { + this.supertypeAnnotation = supertypeAnnotation; + } + + /** + * Set the embeddable annotation + * + * @param embeddableAnnotation embeddable annotation + */ + public void setEmbeddableAnnotation(Class embeddableAnnotation) { + this.embeddableAnnotation = embeddableAnnotation; + } + + /** + * Set the embedded annotation + * + * @param embeddedAnnotation embedded annotation + */ + public void setEmbeddedAnnotation(Class embeddedAnnotation) { + this.embeddedAnnotation = embeddedAnnotation; + } + + /** + * Set the skip annotation + * + * @param skipAnnotation skip annotation + */ + public void setSkipAnnotation(Class skipAnnotation) { + this.skipAnnotation = skipAnnotation; + } + + /** + * Set the target folder for generated sources + * + * @param targetFolder + */ + public void setTargetFolder(File targetFolder) { + this.targetFolder = targetFolder; + } + + /** + * Set the serializer class to be used + * + * @param serializerClass + */ + public void setSerializerClass(Class serializerClass) { + codegenModule.bind(serializerClass); + this.serializerClass = serializerClass; + } + + /** + * Set the typemappings class to be used + * + * @param typeMappingsClass + */ + public void setTypeMappingsClass(Class typeMappingsClass) { + codegenModule.bind(TypeMappings.class, typeMappingsClass); + } + + /** + * Set whether Scala sources are generated + * + * @param createScalaSources + */ + public void setCreateScalaSources(boolean createScalaSources) { + this.createScalaSources = createScalaSources; + } + + /** + * Set the keywords to be used + * + * @param keywords + */ + public void setKeywords(Collection keywords) { + codegenModule.bind(CodegenModule.KEYWORDS, keywords); + } + + /** + * Set the name prefix + * + * @param prefix + */ + public void setNamePrefix(String prefix) { + codegenModule.bind(CodegenModule.PREFIX, prefix); + } + + /** + * Set the name suffix + * + * @param suffix + */ + public void setNameSuffix(String suffix) { + codegenModule.bind(CodegenModule.SUFFIX, suffix); + } + + /** + * Set the package suffix + * + * @param suffix + */ + public void setPackageSuffix(String suffix) { + codegenModule.bind(CodegenModule.PACKAGE_SUFFIX, suffix); + } + + /** + * Set whether fields are handled (default true) + * + * @param b + * @deprecated Use {@link #setPropertyHandling(PropertyHandling)} instead + */ + @Deprecated + public void setHandleFields(boolean b) { + handleFields = b; + setPropertyHandling(); + } + + /** + * Set whether methods are handled (default true) + * + * @param b + * @deprecated Use {@link #setPropertyHandling(PropertyHandling)} instead + */ + @Deprecated + public void setHandleMethods(boolean b) { + handleMethods = b; + setPropertyHandling(); + } + + private void setPropertyHandling() { + if (handleFields) { + propertyHandling = handleMethods ? PropertyHandling.ALL : PropertyHandling.FIELDS; + } else if (handleMethods) { + propertyHandling = PropertyHandling.METHODS; + } else { + propertyHandling = PropertyHandling.NONE; + } + } + + /** + * Set the property handling mode + * + * @param propertyHandling + */ + public void setPropertyHandling(PropertyHandling propertyHandling) { + this.propertyHandling = propertyHandling; + } + + /** + * Set whether field types should be used instead of getter return types (default false) + * + * @param b + */ + public void setUseFieldTypes(boolean b) { + useFieldTypes = b; + } + + /** + * Add a stop class to be used (default Object.class and Enum.class) + * + * @param cl + */ + public void addStopClass(Class cl) { + stopClasses.add(cl); + } + + /** + * Set whether annotationless superclasses are handled or not (default: true) + * + * @param s + */ + public void setStrictMode(boolean s) { + strictMode = s; + } + + /** + * Set the serializer configuration to use + * + * @param serializerConfig + */ + public void setSerializerConfig(SerializerConfig serializerConfig) { + this.serializerConfig = serializerConfig; + } + + /** + * Add a annotation helper object to process custom annotations + * + * @param annotationHelper + */ + public void addAnnotationHelper(AnnotationHelper annotationHelper) { + annotationHelpers.add(annotationHelper); + } + + /** + * Set the Generated annotation class. Will default to java {@code @Generated} + * + * @param generatedAnnotationClass the fully qualified class name of the Single-Element + * Annotation (with {@code String} element) to be used on the generated sources, or + * {@code null} (defaulting to {@code javax.annotation.Generated} or {@code + * javax.annotation.processing.Generated} depending on the java version). + * @see Single-Element + * Annotation + */ + public void setGeneratedAnnotationClass(@Nullable String generatedAnnotationClass) { + codegenModule.bindInstance( + CodegenModule.GENERATED_ANNOTATION_CLASS, + GeneratedAnnotationResolver.resolve(generatedAnnotationClass)); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/GroovyBeanSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/GroovyBeanSerializer.java index 057ff1f0aa..50ef54ab5b 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/GroovyBeanSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/GroovyBeanSerializer.java @@ -13,144 +13,139 @@ */ package com.querydsl.codegen; +import com.querydsl.codegen.utils.CodeWriter; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.*; -import com.querydsl.codegen.utils.CodeWriter; - /** - * {@code GroovyBeanSerializer} is a {@link Serializer} implementation which serializes {@link EntityType} - * instances into Groovy classes + * {@code GroovyBeanSerializer} is a {@link Serializer} implementation which serializes {@link + * EntityType} instances into Groovy classes * * @author tiwe - * */ public class GroovyBeanSerializer implements Serializer { - private final boolean propertyAnnotations; - - private final String javadocSuffix; - - private boolean printSupertype = false; - - /** - * Create a new {@code GroovyBeanSerializer} instance - */ - public GroovyBeanSerializer() { - this(true, " is a Querydsl bean type"); + private final boolean propertyAnnotations; + + private final String javadocSuffix; + + private boolean printSupertype = false; + + /** Create a new {@code GroovyBeanSerializer} instance */ + public GroovyBeanSerializer() { + this(true, " is a Querydsl bean type"); + } + + /** + * Create a new {@code GroovyBeanSerializer} instance + * + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + */ + public GroovyBeanSerializer(String javadocSuffix) { + this(true, javadocSuffix); + } + + /** + * Create a new {@code GroovyBeanSerializer} instance + * + * @param propertyAnnotations true, to serialize property annotations + */ + public GroovyBeanSerializer(boolean propertyAnnotations) { + this(propertyAnnotations, " is a Querydsl bean type"); + } + + /** + * Create a new {@code GroovyBeanSerializer} instance + * + * @param propertyAnnotations true, to serialize property annotations + * @param javadocSuffix suffix to be used after the simple name in class level javadoc + */ + public GroovyBeanSerializer(boolean propertyAnnotations, String javadocSuffix) { + this.propertyAnnotations = propertyAnnotations; + this.javadocSuffix = javadocSuffix; + } + + @Override + public void serialize(EntityType model, SerializerConfig serializerConfig, CodeWriter writer) + throws IOException { + String simpleName = model.getSimpleName(); + + // package + if (!model.getPackageName().isEmpty()) { + writer.packageDecl(model.getPackageName()); } - /** - * Create a new {@code GroovyBeanSerializer} instance - * - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - */ - public GroovyBeanSerializer(String javadocSuffix) { - this(true, javadocSuffix); + // imports + Set importedClasses = getAnnotationTypes(model); + if (model.hasLists()) { + importedClasses.add(List.class.getName()); } - - /** - * Create a new {@code GroovyBeanSerializer} instance - * - * @param propertyAnnotations true, to serialize property annotations - */ - public GroovyBeanSerializer(boolean propertyAnnotations) { - this(propertyAnnotations, " is a Querydsl bean type"); + if (model.hasCollections()) { + importedClasses.add(Collection.class.getName()); } - - /** - * Create a new {@code GroovyBeanSerializer} instance - * - * @param propertyAnnotations true, to serialize property annotations - * @param javadocSuffix suffix to be used after the simple name in class level javadoc - */ - public GroovyBeanSerializer(boolean propertyAnnotations, String javadocSuffix) { - this.propertyAnnotations = propertyAnnotations; - this.javadocSuffix = javadocSuffix; + if (model.hasSets()) { + importedClasses.add(Set.class.getName()); } + if (model.hasMaps()) { + importedClasses.add(Map.class.getName()); + } + writer.importClasses(importedClasses.toArray(new String[0])); - @Override - public void serialize(EntityType model, SerializerConfig serializerConfig, - CodeWriter writer) throws IOException { - String simpleName = model.getSimpleName(); + // javadoc + writer.javadoc(simpleName + javadocSuffix); - // package - if (!model.getPackageName().isEmpty()) { - writer.packageDecl(model.getPackageName()); - } - - // imports - Set importedClasses = getAnnotationTypes(model); - if (model.hasLists()) { - importedClasses.add(List.class.getName()); - } - if (model.hasCollections()) { - importedClasses.add(Collection.class.getName()); - } - if (model.hasSets()) { - importedClasses.add(Set.class.getName()); - } - if (model.hasMaps()) { - importedClasses.add(Map.class.getName()); - } - writer.importClasses(importedClasses.toArray(new String[0])); + // header + for (Annotation annotation : model.getAnnotations()) { + writer.annotation(annotation); + } + if (printSupertype && model.getSuperType() != null) { + writer.beginClass(model, model.getSuperType().getType()); + } else { + writer.beginClass(model); + } - // javadoc - writer.javadoc(simpleName + javadocSuffix); + bodyStart(model, writer); - // header - for (Annotation annotation : model.getAnnotations()) { - writer.annotation(annotation); + // fields + for (Property property : model.getProperties()) { + if (propertyAnnotations) { + for (Annotation annotation : property.getAnnotations()) { + writer.annotation(annotation); } - if (printSupertype && model.getSuperType() != null) { - writer.beginClass(model, model.getSuperType().getType()); - } else { - writer.beginClass(model); - } - - bodyStart(model, writer); + } + writer.field(property.getType(), property.getEscapedName()); + } - // fields - for (Property property : model.getProperties()) { - if (propertyAnnotations) { - for (Annotation annotation : property.getAnnotations()) { - writer.annotation(annotation); - } - } - writer.field(property.getType(), property.getEscapedName()); - } + bodyEnd(model, writer); - bodyEnd(model, writer); + writer.end(); + } - writer.end(); - } + protected void bodyStart(EntityType model, CodeWriter writer) throws IOException { + // template method + } - protected void bodyStart(EntityType model, CodeWriter writer) throws IOException { - // template method - } + protected void bodyEnd(EntityType model, CodeWriter writer) throws IOException { + // template method + } - protected void bodyEnd(EntityType model, CodeWriter writer) throws IOException { - // template method + private Set getAnnotationTypes(EntityType model) { + Set imports = new HashSet(); + for (Annotation annotation : model.getAnnotations()) { + imports.add(annotation.annotationType().getName()); } - - private Set getAnnotationTypes(EntityType model) { - Set imports = new HashSet(); - for (Annotation annotation : model.getAnnotations()) { - imports.add(annotation.annotationType().getName()); + if (propertyAnnotations) { + for (Property property : model.getProperties()) { + for (Annotation annotation : property.getAnnotations()) { + imports.add(annotation.annotationType().getName()); } - if (propertyAnnotations) { - for (Property property : model.getProperties()) { - for (Annotation annotation : property.getAnnotations()) { - imports.add(annotation.annotationType().getName()); - } - } - } - return imports; - } - - public void setPrintSupertype(boolean printSupertype) { - this.printSupertype = printSupertype; + } } + return imports; + } + public void setPrintSupertype(boolean printSupertype) { + this.printSupertype = printSupertype; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/JavaTypeMappings.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/JavaTypeMappings.java index d15b4e7b50..a05a976436 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/JavaTypeMappings.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/JavaTypeMappings.java @@ -19,33 +19,40 @@ import com.querydsl.core.types.dsl.*; /** - * {@code JavaTypeMappings} defines mappings from {@link TypeCategory} instances to {@link Expression} types + * {@code JavaTypeMappings} defines mappings from {@link TypeCategory} instances to {@link + * Expression} types * * @author tiwe - * */ public class JavaTypeMappings extends TypeMappings { - public JavaTypeMappings() { - register(TypeCategory.STRING, StringExpression.class, StringPath.class, StringTemplate.class); - register(TypeCategory.BOOLEAN, BooleanExpression.class, BooleanPath.class, BooleanTemplate.class); - register(TypeCategory.COMPARABLE, ComparableExpression.class, ComparablePath.class, ComparableTemplate.class); - register(TypeCategory.ENUM, EnumExpression.class, EnumPath.class, EnumTemplate.class); - register(TypeCategory.DATE, TemporalExpression.class, DatePath.class, DateTemplate.class); - register(TypeCategory.DATETIME, TemporalExpression.class, DateTimePath.class, DateTimeTemplate.class); - register(TypeCategory.TIME, TemporalExpression.class, TimePath.class, TimeTemplate.class); - register(TypeCategory.NUMERIC, NumberExpression.class, NumberPath.class, NumberTemplate.class); - register(TypeCategory.SIMPLE, SimpleExpression.class, SimplePath.class, SimpleTemplate.class); - - register(TypeCategory.ARRAY, Expression.class, SimplePath.class, SimpleTemplate.class); - register(TypeCategory.COLLECTION, Expression.class, SimplePath.class, SimpleTemplate.class); - register(TypeCategory.SET, Expression.class, SimplePath.class, SimpleTemplate.class); - register(TypeCategory.LIST, Expression.class, SimplePath.class, SimpleTemplate.class); - register(TypeCategory.MAP, Expression.class, SimplePath.class, SimpleTemplate.class); - - register(TypeCategory.CUSTOM, Expression.class, Path.class, SimpleTemplate.class); - register(TypeCategory.ENTITY, Expression.class, Path.class, SimpleTemplate.class); - } + public JavaTypeMappings() { + register(TypeCategory.STRING, StringExpression.class, StringPath.class, StringTemplate.class); + register( + TypeCategory.BOOLEAN, BooleanExpression.class, BooleanPath.class, BooleanTemplate.class); + register( + TypeCategory.COMPARABLE, + ComparableExpression.class, + ComparablePath.class, + ComparableTemplate.class); + register(TypeCategory.ENUM, EnumExpression.class, EnumPath.class, EnumTemplate.class); + register(TypeCategory.DATE, TemporalExpression.class, DatePath.class, DateTemplate.class); + register( + TypeCategory.DATETIME, + TemporalExpression.class, + DateTimePath.class, + DateTimeTemplate.class); + register(TypeCategory.TIME, TemporalExpression.class, TimePath.class, TimeTemplate.class); + register(TypeCategory.NUMERIC, NumberExpression.class, NumberPath.class, NumberTemplate.class); + register(TypeCategory.SIMPLE, SimpleExpression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.ARRAY, Expression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.COLLECTION, Expression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.SET, Expression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.LIST, Expression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.MAP, Expression.class, SimplePath.class, SimpleTemplate.class); + register(TypeCategory.CUSTOM, Expression.class, Path.class, SimpleTemplate.class); + register(TypeCategory.ENTITY, Expression.class, Path.class, SimpleTemplate.class); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Keywords.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Keywords.java index ed78f227f4..83d8579b39 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Keywords.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Keywords.java @@ -18,39 +18,124 @@ import java.util.Collections; /** - * {@code Keywords} provides keywords sets in capitalized form to - * be used in {@link GenericExporter} and the APT processors + * {@code Keywords} provides keywords sets in capitalized form to be used in {@link GenericExporter} + * and the APT processors * * @author tiwe - * */ public final class Keywords { - private Keywords() { } - - public static final Collection JPA = Collections.unmodifiableList(Arrays.asList( - "ABS", "ALL", "AND", "ANY", "AS", "ASC", "AVG", "BETWEEN", - "BIT_LENGTH[51]", "BOTH", "BY", "CASE", "CHAR_LENGTH", - "CHARACTER_LENGTH", "CLASS", - "COALESCE", "CONCAT", "COUNT", "CURRENT_DATE", "CURRENT_TIME", - "CURRENT_TIMESTAMP", - "DELETE", "DESC", "DISTINCT", "ELSE", "EMPTY", "END", "ENTRY", - "ESCAPE", "EXISTS", "FALSE", "FETCH", - "FROM", "GROUP", "HAVING", "IN", "INDEX", "INNER", "IS", "JOIN", - "KEY", "LEADING", "LEFT", "LENGTH", "LIKE", - "LOCATE", "LOWER", "MAX", "MEMBER", "MIN", "MOD", "NEW", "NOT", - "NULL", "NULLIF", "OBJECT", "OF", "OR", - "ORDER", "OUTER", "POSITION", "SELECT", "SET", "SIZE", "SOME", - "SQRT", "SUBSTRING", "SUM", "THEN", - "TRAILING", "TRIM", "TRUE", "TYPE", "UNKNOWN", "UPDATE", "UPPER", - "VALUE", "WHEN", "WHERE")); + private Keywords() {} - public static final Collection JDO = Collections.unmodifiableList(Arrays.asList( - "AS","ASC", "ASCENDING","AVG", - "BY","COUNT", "DESC","DESCENDING", - "DISTINCT","EXCLUDE", "FROM","GROUP", - "HAVING","INTO","MAX","MIN", - "ORDER","PARAMETERS","RANGE","SELECT", - "SUBCLASSES","SUM","UNIQUE","VARIABLES","WHERE")); + public static final Collection JPA = + Collections.unmodifiableList( + Arrays.asList( + "ABS", + "ALL", + "AND", + "ANY", + "AS", + "ASC", + "AVG", + "BETWEEN", + "BIT_LENGTH[51]", + "BOTH", + "BY", + "CASE", + "CHAR_LENGTH", + "CHARACTER_LENGTH", + "CLASS", + "COALESCE", + "CONCAT", + "COUNT", + "CURRENT_DATE", + "CURRENT_TIME", + "CURRENT_TIMESTAMP", + "DELETE", + "DESC", + "DISTINCT", + "ELSE", + "EMPTY", + "END", + "ENTRY", + "ESCAPE", + "EXISTS", + "FALSE", + "FETCH", + "FROM", + "GROUP", + "HAVING", + "IN", + "INDEX", + "INNER", + "IS", + "JOIN", + "KEY", + "LEADING", + "LEFT", + "LENGTH", + "LIKE", + "LOCATE", + "LOWER", + "MAX", + "MEMBER", + "MIN", + "MOD", + "NEW", + "NOT", + "NULL", + "NULLIF", + "OBJECT", + "OF", + "OR", + "ORDER", + "OUTER", + "POSITION", + "SELECT", + "SET", + "SIZE", + "SOME", + "SQRT", + "SUBSTRING", + "SUM", + "THEN", + "TRAILING", + "TRIM", + "TRUE", + "TYPE", + "UNKNOWN", + "UPDATE", + "UPPER", + "VALUE", + "WHEN", + "WHERE")); + public static final Collection JDO = + Collections.unmodifiableList( + Arrays.asList( + "AS", + "ASC", + "ASCENDING", + "AVG", + "BY", + "COUNT", + "DESC", + "DESCENDING", + "DISTINCT", + "EXCLUDE", + "FROM", + "GROUP", + "HAVING", + "INTO", + "MAX", + "MIN", + "ORDER", + "PARAMETERS", + "RANGE", + "SELECT", + "SUBCLASSES", + "SUM", + "UNIQUE", + "VARIABLES", + "WHERE")); } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/NamingFunction.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/NamingFunction.java index 6aee3f4028..da308d35f2 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/NamingFunction.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/NamingFunction.java @@ -22,5 +22,4 @@ * * @author Shredder121 */ -public interface NamingFunction extends Function { -} +public interface NamingFunction extends Function {} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/ParameterizedTypeImpl.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/ParameterizedTypeImpl.java index 81cc0dda14..ff55e7d77f 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/ParameterizedTypeImpl.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/ParameterizedTypeImpl.java @@ -18,53 +18,51 @@ import java.util.Arrays; /** - * {@code ParameterizedTypeImpl} provides an implementation of the {@link ParameterizedType} interface + * {@code ParameterizedTypeImpl} provides an implementation of the {@link ParameterizedType} + * interface * * @author tiwe - * */ public class ParameterizedTypeImpl implements ParameterizedType { - private final Type rawType; + private final Type rawType; - private final Type[] arguments; + private final Type[] arguments; - public ParameterizedTypeImpl(Type rawType, Type[] arguments) { - this.rawType = rawType; - this.arguments = arguments; - } + public ParameterizedTypeImpl(Type rawType, Type[] arguments) { + this.rawType = rawType; + this.arguments = arguments; + } - @Override - public Type[] getActualTypeArguments() { - return arguments; - } + @Override + public Type[] getActualTypeArguments() { + return arguments; + } - @Override - public Type getRawType() { - return rawType; - } + @Override + public Type getRawType() { + return rawType; + } - @Override - public Type getOwnerType() { - return rawType; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof ParameterizedTypeImpl) { - ParameterizedTypeImpl other = (ParameterizedTypeImpl) o; - return other.rawType.equals(rawType) - && Arrays.equals(other.arguments, arguments); - } else { - return false; - } - } + @Override + public Type getOwnerType() { + return rawType; + } - @Override - public int hashCode() { - return rawType.hashCode(); + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof ParameterizedTypeImpl) { + ParameterizedTypeImpl other = (ParameterizedTypeImpl) o; + return other.rawType.equals(rawType) && Arrays.equals(other.arguments, arguments); + } else { + return false; } + } + @Override + public int hashCode() { + return rawType.hashCode(); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/ProjectionSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/ProjectionSerializer.java index f0571ff5ef..64901cd24b 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/ProjectionSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/ProjectionSerializer.java @@ -17,7 +17,5 @@ * {@code ProjectionSerializer} is a {@link Serializer} for projection types * * @author f43nd1r - * */ -public interface ProjectionSerializer extends Serializer { -} +public interface ProjectionSerializer extends Serializer {} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Property.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Property.java index 79f8dea6d8..318dc5e19a 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Property.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Property.java @@ -13,13 +13,11 @@ */ package com.querydsl.codegen; +import com.querydsl.codegen.utils.model.Type; import java.lang.annotation.Annotation; import java.util.*; - import javax.lang.model.SourceVersion; -import com.querydsl.codegen.utils.model.Type; - /** * {@code Property} represents a property in a query domain type. * @@ -27,140 +25,144 @@ */ public final class Property implements Comparable { - private final EntityType declaringType; - - private final boolean inherited; - - private final List inits; - - private final String name, escapedName; - - private final Map,Annotation> annotations = new HashMap,Annotation>(); - - private final Map data = new HashMap(); - - private final Type type; - - public Property(EntityType declaringType, String name, Type type) { - this(declaringType, name, type, Collections.emptyList(), false); - } - - public Property(EntityType declaringType, String name, Type type, List inits) { - this(declaringType, name, type, inits, false); - } - - public Property(EntityType declaringType, String name, Type type, List inits, - boolean inherited) { - this(declaringType, name, escapeName(name), type, inits, inherited); - } - - public Property(EntityType declaringType, String name, String escapedName, Type type, - List inits, boolean inherited) { - this.declaringType = declaringType; - this.name = name; - this.escapedName = escapedName; - this.type = type; - this.inits = inits; - this.inherited = inherited; - } - - private static String escapeName(String name) { - if (SourceVersion.isKeyword(name)) { - name = name + "$"; - } else if (!Character.isJavaIdentifierStart(name.charAt(0))) { - name = "_" + name; - } - return name; - } - - public void addAnnotation(Annotation annotation) { - annotations.put(annotation.annotationType(), annotation); - } - - @Override - public int compareTo(Property o) { - int rv = name.compareToIgnoreCase(o.getName()); - if (rv == 0) { - return name.compareTo(o.getName()); - } else { - return rv; - } - } - - public Property createCopy(EntityType targetModel) { - if (!declaringType.getParameters().isEmpty()) { - Type newType = TypeResolver.resolve(type, declaringType, targetModel); - if (!newType.equals(type) || !newType.getClass().equals(type.getClass())) { - return new Property(targetModel, name, newType, inits, false); - } else { - return new Property(targetModel, name, type, inits, targetModel.getSuperType() != null); - } - } else { - return new Property(targetModel, name, type, inits, targetModel.getSuperType() != null); - } - } - - @SuppressWarnings("unchecked") - public T getAnnotation(Class type) { - return (T) annotations.get(type); - } - - public Collection getAnnotations() { - return Collections.unmodifiableCollection(annotations.values()); - } - - @Override - public int hashCode() { - return Objects.hash(name, type); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Property) { - Property p = (Property) o; - return p.name.equals(name) && p.type.equals(type); - } else { - return false; - } - } - - public EntityType getDeclaringType() { - return declaringType; - } - - public String getEscapedName() { - return escapedName; - } - - public List getInits() { - return inits; - } - - public String getName() { - return name; - } - - public Type getParameter(int i) { - return type.getParameters().get(i); - } - - public Map getData() { - return data; - } - - public Type getType() { - return type; - } - - public boolean isInherited() { - return inherited; - } - - @Override - public String toString() { - return declaringType.getFullName() + "." + name; - } - + private final EntityType declaringType; + + private final boolean inherited; + + private final List inits; + + private final String name, escapedName; + + private final Map, Annotation> annotations = new HashMap, Annotation>(); + + private final Map data = new HashMap(); + + private final Type type; + + public Property(EntityType declaringType, String name, Type type) { + this(declaringType, name, type, Collections.emptyList(), false); + } + + public Property(EntityType declaringType, String name, Type type, List inits) { + this(declaringType, name, type, inits, false); + } + + public Property( + EntityType declaringType, String name, Type type, List inits, boolean inherited) { + this(declaringType, name, escapeName(name), type, inits, inherited); + } + + public Property( + EntityType declaringType, + String name, + String escapedName, + Type type, + List inits, + boolean inherited) { + this.declaringType = declaringType; + this.name = name; + this.escapedName = escapedName; + this.type = type; + this.inits = inits; + this.inherited = inherited; + } + + private static String escapeName(String name) { + if (SourceVersion.isKeyword(name)) { + name = name + "$"; + } else if (!Character.isJavaIdentifierStart(name.charAt(0))) { + name = "_" + name; + } + return name; + } + + public void addAnnotation(Annotation annotation) { + annotations.put(annotation.annotationType(), annotation); + } + + @Override + public int compareTo(Property o) { + int rv = name.compareToIgnoreCase(o.getName()); + if (rv == 0) { + return name.compareTo(o.getName()); + } else { + return rv; + } + } + + public Property createCopy(EntityType targetModel) { + if (!declaringType.getParameters().isEmpty()) { + Type newType = TypeResolver.resolve(type, declaringType, targetModel); + if (!newType.equals(type) || !newType.getClass().equals(type.getClass())) { + return new Property(targetModel, name, newType, inits, false); + } else { + return new Property(targetModel, name, type, inits, targetModel.getSuperType() != null); + } + } else { + return new Property(targetModel, name, type, inits, targetModel.getSuperType() != null); + } + } + + @SuppressWarnings("unchecked") + public T getAnnotation(Class type) { + return (T) annotations.get(type); + } + + public Collection getAnnotations() { + return Collections.unmodifiableCollection(annotations.values()); + } + + @Override + public int hashCode() { + return Objects.hash(name, type); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Property) { + Property p = (Property) o; + return p.name.equals(name) && p.type.equals(type); + } else { + return false; + } + } + + public EntityType getDeclaringType() { + return declaringType; + } + + public String getEscapedName() { + return escapedName; + } + + public List getInits() { + return inits; + } + + public String getName() { + return name; + } + + public Type getParameter(int i) { + return type.getParameters().get(i); + } + + public Map getData() { + return data; + } + + public Type getType() { + return type; + } + + public boolean isInherited() { + return inherited; + } + + @Override + public String toString() { + return declaringType.getFullName() + "." + name; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/PropertyHandling.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/PropertyHandling.java index 6257cc9b4a..770c9cd34c 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/PropertyHandling.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/PropertyHandling.java @@ -13,137 +13,119 @@ */ package com.querydsl.codegen; +import com.querydsl.core.annotations.QueryInit; +import com.querydsl.core.annotations.QueryType; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; -import com.querydsl.core.annotations.QueryInit; -import com.querydsl.core.annotations.QueryType; - -/** - * Defines handling of fields and getters in property extractions - */ +/** Defines handling of fields and getters in property extractions */ public enum PropertyHandling { - /** - * Inspect fields and methods - */ - ALL { - @Override - public Config getConfig(Class type) { - return Config.ALL; - } - }, - /** - * Inspect fields only - */ - FIELDS { - @Override - public Config getConfig(Class type) { - return Config.FIELDS; - } - }, - /** - * Inspect methods only - */ - METHODS { - @Override - public Config getConfig(Class type) { - return Config.METHODS; - } - }, - /** - * No member inspection - */ - NONE { - @Override - public Config getConfig(Class type) { - return Config.NONE; - } - }, - /** - * JDO compatibility - */ - JDO { - @Override - public Config getConfig(Class type) { - boolean fields = false; - boolean methods = false; - for (Field field : type.getDeclaredFields()) { - fields |= hasAnnotations(field, "javax.jdo.annotations."); - } - for (Method method : type.getDeclaredMethods()) { - methods |= hasAnnotations(method, "javax.jdo.annotations."); - } - return Config.of(fields, methods, Config.FIELDS); - } - }, - /** - * JPA compatibility - */ - JPA { - @Override - public Config getConfig(Class type) { - boolean fields = false; - boolean methods = false; - for (Field field : type.getDeclaredFields()) { - fields |= hasAnnotations(field, "javax.persistence."); - fields |= hasAnnotations(field, "jakarta.persistence."); - } - for (Method method : type.getDeclaredMethods()) { - methods |= hasAnnotations(method, "javax.persistence."); - methods |= hasAnnotations(method, "jakarta.persistence."); - } - return Config.of(fields, methods, Config.ALL); - } - }; - - private static boolean hasAnnotations(AnnotatedElement element, String packagePrefix) { - for (Annotation ann : element.getAnnotations()) { - if (ann.annotationType().getName().startsWith(packagePrefix)) { - return true; - } - } - return element.isAnnotationPresent(QueryType.class) - || element.isAnnotationPresent(QueryInit.class); + /** Inspect fields and methods */ + ALL { + @Override + public Config getConfig(Class type) { + return Config.ALL; + } + }, + /** Inspect fields only */ + FIELDS { + @Override + public Config getConfig(Class type) { + return Config.FIELDS; } + }, + /** Inspect methods only */ + METHODS { + @Override + public Config getConfig(Class type) { + return Config.METHODS; + } + }, + /** No member inspection */ + NONE { + @Override + public Config getConfig(Class type) { + return Config.NONE; + } + }, + /** JDO compatibility */ + JDO { + @Override + public Config getConfig(Class type) { + boolean fields = false; + boolean methods = false; + for (Field field : type.getDeclaredFields()) { + fields |= hasAnnotations(field, "javax.jdo.annotations."); + } + for (Method method : type.getDeclaredMethods()) { + methods |= hasAnnotations(method, "javax.jdo.annotations."); + } + return Config.of(fields, methods, Config.FIELDS); + } + }, + /** JPA compatibility */ + JPA { + @Override + public Config getConfig(Class type) { + boolean fields = false; + boolean methods = false; + for (Field field : type.getDeclaredFields()) { + fields |= hasAnnotations(field, "javax.persistence."); + fields |= hasAnnotations(field, "jakarta.persistence."); + } + for (Method method : type.getDeclaredMethods()) { + methods |= hasAnnotations(method, "javax.persistence."); + methods |= hasAnnotations(method, "jakarta.persistence."); + } + return Config.of(fields, methods, Config.ALL); + } + }; - public abstract Config getConfig(Class type); + private static boolean hasAnnotations(AnnotatedElement element, String packagePrefix) { + for (Annotation ann : element.getAnnotations()) { + if (ann.annotationType().getName().startsWith(packagePrefix)) { + return true; + } + } + return element.isAnnotationPresent(QueryType.class) + || element.isAnnotationPresent(QueryInit.class); + } - /** - * Property handling options - */ - public enum Config { - ALL(true, true), - FIELDS(true, false), - METHODS(false, true), - NONE(false, false); + public abstract Config getConfig(Class type); - private final boolean fields, methods; + /** Property handling options */ + public enum Config { + ALL(true, true), + FIELDS(true, false), + METHODS(false, true), + NONE(false, false); + private final boolean fields, methods; - Config(boolean fields, boolean methods) { - this.fields = fields; - this.methods = methods; - } + Config(boolean fields, boolean methods) { + this.fields = fields; + this.methods = methods; + } - public boolean isFields() { - return fields; - } + public boolean isFields() { + return fields; + } - public boolean isMethods() { - return methods; - } + public boolean isMethods() { + return methods; + } - public static Config of(boolean fields, boolean methods, Config defaultConfig) { - if (fields && methods) { - return ALL; - } else if (fields) { - return FIELDS; - } else if (methods) { - return METHODS; - } else { - return defaultConfig; - } - } + public static Config of(boolean fields, boolean methods, Config defaultConfig) { + if (fields && methods) { + return ALL; + } else if (fields) { + return FIELDS; + } else if (methods) { + return METHODS; + } else { + return defaultConfig; + } } + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactory.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactory.java index 5990a3703f..b2eb6efeb7 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactory.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactory.java @@ -16,19 +16,18 @@ import com.querydsl.codegen.utils.model.Type; /** - * {@code QueryTypeFactory} defines an interface for mapping domain types to Querydsl expression types + * {@code QueryTypeFactory} defines an interface for mapping domain types to Querydsl expression + * types * * @author tiwe - * */ public interface QueryTypeFactory { - /** - * Create an expression type based on the given actual type - * - * @param type actual type - * @return expression type - */ - Type create(Type type); - -} \ No newline at end of file + /** + * Create an expression type based on the given actual type + * + * @param type actual type + * @return expression type + */ + Type create(Type type); +} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactoryImpl.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactoryImpl.java index b82a79c881..bbce936a10 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactoryImpl.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/QueryTypeFactoryImpl.java @@ -13,59 +13,55 @@ */ package com.querydsl.codegen; -import javax.inject.Inject; -import javax.inject.Named; - import com.querydsl.codegen.utils.model.SimpleType; import com.querydsl.codegen.utils.model.Type; +import javax.inject.Inject; +import javax.inject.Named; /** - * {@code QueryTypeFactoryImpl} is the default implementation of the {@link QueryTypeFactory} interface + * {@code QueryTypeFactoryImpl} is the default implementation of the {@link QueryTypeFactory} + * interface * * @author tiwe - * */ public class QueryTypeFactoryImpl implements QueryTypeFactory { - private final String prefix, suffix, packageSuffix; + private final String prefix, suffix, packageSuffix; - @Inject - public QueryTypeFactoryImpl( - @Named(CodegenModule.PREFIX) String prefix, - @Named(CodegenModule.SUFFIX) String suffix, - @Named(CodegenModule.PACKAGE_SUFFIX) String packageSuffix) { - this.prefix = prefix; - this.suffix = suffix; - this.packageSuffix = packageSuffix; - } - - @Override - public Type create(Type type) { - if (type.getPackageName().isEmpty()) { - return createWithoutPackage(type); - } else { - return createWithPackage(type); - } - } + @Inject + public QueryTypeFactoryImpl( + @Named(CodegenModule.PREFIX) String prefix, + @Named(CodegenModule.SUFFIX) String suffix, + @Named(CodegenModule.PACKAGE_SUFFIX) String packageSuffix) { + this.prefix = prefix; + this.suffix = suffix; + this.packageSuffix = packageSuffix; + } - private Type createWithPackage(Type type) { - String packageName = type.getPackageName(); - String simpleName = prefix + normalizeName(type.getFullName() - .substring(packageName.length() + 1)) + suffix; - packageName = (packageName.startsWith("java") ? "ext." : "") - + packageName + packageSuffix; - return new SimpleType(type.getCategory(), packageName + "." + simpleName, - packageName, simpleName, false, false); + @Override + public Type create(Type type) { + if (type.getPackageName().isEmpty()) { + return createWithoutPackage(type); + } else { + return createWithPackage(type); } + } - private Type createWithoutPackage(Type type) { - String simpleName = prefix + normalizeName(type.getFullName()) + suffix; - return new SimpleType(type.getCategory(), simpleName, "", simpleName, false, false); - } - - private String normalizeName(String name) { - return name.replace('.', '_').replace('$', '_'); - } + private Type createWithPackage(Type type) { + String packageName = type.getPackageName(); + String simpleName = + prefix + normalizeName(type.getFullName().substring(packageName.length() + 1)) + suffix; + packageName = (packageName.startsWith("java") ? "ext." : "") + packageName + packageSuffix; + return new SimpleType( + type.getCategory(), packageName + "." + simpleName, packageName, simpleName, false, false); + } + private Type createWithoutPackage(Type type) { + String simpleName = prefix + normalizeName(type.getFullName()) + suffix; + return new SimpleType(type.getCategory(), simpleName, "", simpleName, false, false); + } + private String normalizeName(String name) { + return name.replace('.', '_').replace('$', '_'); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Serializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Serializer.java index 139f213ce4..9a0d466fdc 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Serializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Serializer.java @@ -13,26 +13,24 @@ */ package com.querydsl.codegen; -import java.io.IOException; - import com.querydsl.codegen.utils.CodeWriter; +import java.io.IOException; /** * {@code Serializer} defines a common interface for {@link EntityType} serializers * * @author tiwe - * */ public interface Serializer { - /** - * Serialize the given {@link EntityType} - * - * @param type EntityType to serialize - * @param serializerConfig serializer configuration - * @param writer serialization target - * @throws IOException - */ - void serialize(EntityType type, SerializerConfig serializerConfig, CodeWriter writer) throws IOException; - + /** + * Serialize the given {@link EntityType} + * + * @param type EntityType to serialize + * @param serializerConfig serializer configuration + * @param writer serialization target + * @throws IOException + */ + void serialize(EntityType type, SerializerConfig serializerConfig, CodeWriter writer) + throws IOException; } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/SerializerConfig.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/SerializerConfig.java index eb912bdc9b..6d0c6d990c 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/SerializerConfig.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/SerializerConfig.java @@ -17,42 +17,41 @@ * {@code SerializerConfig} defines serialization options to be used in the {@link Serializer} * * @author tiwe - * */ public interface SerializerConfig { - /** - * accessors are used for entity fields - * - * @return if accessors are used for entity fields - */ - boolean useEntityAccessors(); + /** + * accessors are used for entity fields + * + * @return if accessors are used for entity fields + */ + boolean useEntityAccessors(); - /** - * indexed list accessors are used - * - * @return if indexed list accessors are used - */ - boolean useListAccessors(); + /** + * indexed list accessors are used + * + * @return if indexed list accessors are used + */ + boolean useListAccessors(); - /** - * keyed map accessors are used - * - * @return if keyed map accessors are used - */ - boolean useMapAccessors(); + /** + * keyed map accessors are used + * + * @return if keyed map accessors are used + */ + boolean useMapAccessors(); - /** - * the default variable is created - * - * @return if the default variable is created - */ - boolean createDefaultVariable(); + /** + * the default variable is created + * + * @return if the default variable is created + */ + boolean createDefaultVariable(); - /** - * the name of the default variable - * - * @return the name of the default variable - */ - String defaultVariableName(); + /** + * the name of the default variable + * + * @return the name of the default variable + */ + String defaultVariableName(); } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/SimpleSerializerConfig.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/SimpleSerializerConfig.java index 3c600ee221..fd146703b6 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/SimpleSerializerConfig.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/SimpleSerializerConfig.java @@ -16,63 +16,64 @@ import com.querydsl.core.annotations.Config; /** - * {@code SimpleSerializerConfig} is the default implementation of the {@link SerializerConfig} interface + * {@code SimpleSerializerConfig} is the default implementation of the {@link SerializerConfig} + * interface * * @author tiwe - * */ public final class SimpleSerializerConfig implements SerializerConfig { - public static final SerializerConfig DEFAULT = new SimpleSerializerConfig(false, false, false, true, ""); + public static final SerializerConfig DEFAULT = + new SimpleSerializerConfig(false, false, false, true, ""); - public static SerializerConfig getConfig(Config annotation) { - return new SimpleSerializerConfig( - annotation.entityAccessors(), - annotation.listAccessors(), - annotation.mapAccessors(), - annotation.createDefaultVariable(), - annotation.defaultVariableName()); - } + public static SerializerConfig getConfig(Config annotation) { + return new SimpleSerializerConfig( + annotation.entityAccessors(), + annotation.listAccessors(), + annotation.mapAccessors(), + annotation.createDefaultVariable(), + annotation.defaultVariableName()); + } - private final boolean entityAccessors, listAccessors, mapAccessors, createDefaultVariable; + private final boolean entityAccessors, listAccessors, mapAccessors, createDefaultVariable; - private final String defaultVariableName; + private final String defaultVariableName; - public SimpleSerializerConfig( - boolean entityAccessors, - boolean listAccessors, - boolean mapAccessors, - boolean createDefaultVariable, - String defaultVariableName) { - this.entityAccessors = entityAccessors; - this.listAccessors = listAccessors; - this.mapAccessors = mapAccessors; - this.createDefaultVariable = createDefaultVariable; - this.defaultVariableName = defaultVariableName; - } + public SimpleSerializerConfig( + boolean entityAccessors, + boolean listAccessors, + boolean mapAccessors, + boolean createDefaultVariable, + String defaultVariableName) { + this.entityAccessors = entityAccessors; + this.listAccessors = listAccessors; + this.mapAccessors = mapAccessors; + this.createDefaultVariable = createDefaultVariable; + this.defaultVariableName = defaultVariableName; + } - @Override - public boolean useEntityAccessors() { - return entityAccessors; - } + @Override + public boolean useEntityAccessors() { + return entityAccessors; + } - @Override - public boolean useListAccessors() { - return listAccessors; - } + @Override + public boolean useListAccessors() { + return listAccessors; + } - @Override - public boolean useMapAccessors() { - return mapAccessors; - } + @Override + public boolean useMapAccessors() { + return mapAccessors; + } - @Override - public boolean createDefaultVariable() { - return createDefaultVariable; - } + @Override + public boolean createDefaultVariable() { + return createDefaultVariable; + } - @Override - public String defaultVariableName() { - return defaultVariableName; - } + @Override + public String defaultVariableName() { + return defaultVariableName; + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/Supertype.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/Supertype.java index 3bce3dd95e..82c744cda5 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/Supertype.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/Supertype.java @@ -13,65 +13,61 @@ */ package com.querydsl.codegen; -import org.jetbrains.annotations.Nullable; - import com.querydsl.codegen.utils.model.Type; +import org.jetbrains.annotations.Nullable; /** - * {@code Supertype} defines a tuple of a {@link Type} and an optional {@link EntityType} instance used for - * supertype references in {@link EntityType} instances + * {@code Supertype} defines a tuple of a {@link Type} and an optional {@link EntityType} instance + * used for supertype references in {@link EntityType} instances * * @author tiwe - * */ public class Supertype { - @Nullable - private EntityType entityType; - - private final Type type; + @Nullable private EntityType entityType; - public Supertype(Type type) { - this.type = type; - } + private final Type type; - public Supertype(Type type, EntityType entityType) { - this.type = type; - this.entityType = entityType; - } + public Supertype(Type type) { + this.type = type; + } - @Nullable - public EntityType getEntityType() { - return entityType; - } + public Supertype(Type type, EntityType entityType) { + this.type = type; + this.entityType = entityType; + } - public Type getType() { - return type; - } + @Nullable + public EntityType getEntityType() { + return entityType; + } - public void setEntityType(EntityType entityType) { - this.entityType = entityType; - } + public Type getType() { + return type; + } - @Override - public int hashCode() { - return type.hashCode(); - } + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof Supertype) { - return ((Supertype) o).type.equals(type); - } else { - return false; - } - } + @Override + public int hashCode() { + return type.hashCode(); + } - @Override - public String toString() { - return type.toString(); + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Supertype) { + return ((Supertype) o).type.equals(type); + } else { + return false; } + } + @Override + public String toString() { + return type.toString(); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/SupertypeSerializer.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/SupertypeSerializer.java index 0316405521..59c42ccb23 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/SupertypeSerializer.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/SupertypeSerializer.java @@ -17,7 +17,5 @@ * {@code SupertypeSerializer} is a {@link Serializer} for supertypes * * @author tiwe - * */ -public interface SupertypeSerializer extends EntitySerializer { -} +public interface SupertypeSerializer extends EntitySerializer {} diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeFactory.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeFactory.java index 60e928ee6c..b5f7f4ed37 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeFactory.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeFactory.java @@ -22,7 +22,6 @@ import com.querydsl.codegen.utils.model.Types; import com.querydsl.core.util.PrimitiveUtils; import com.querydsl.core.util.ReflectionUtils; - import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; @@ -42,251 +41,266 @@ * {@code TypeFactory} is a factory class for {@link Type} instances * * @author tiwe - * */ public final class TypeFactory { - private static final Type ANY = new TypeExtends(Types.OBJECT); + private static final Type ANY = new TypeExtends(Types.OBJECT); - private final Map, Type> cache = new HashMap<>(); + private final Map, Type> cache = new HashMap<>(); - private final List> entityAnnotations; + private final List> entityAnnotations; - private final List annotationHelpers = new ArrayList<>(); + private final List annotationHelpers = new ArrayList<>(); - private final Set> embeddableTypes = new HashSet<>(); + private final Set> embeddableTypes = new HashSet<>(); - private boolean unknownAsEntity = false; + private boolean unknownAsEntity = false; - private Function variableNameFunction; + private Function variableNameFunction; - public TypeFactory() { - this(new ArrayList<>(), DefaultVariableNameFunction.INSTANCE); - } + public TypeFactory() { + this(new ArrayList<>(), DefaultVariableNameFunction.INSTANCE); + } - public TypeFactory(List> entityAnnotations) { - this(entityAnnotations, DefaultVariableNameFunction.INSTANCE); - } + public TypeFactory(List> entityAnnotations) { + this(entityAnnotations, DefaultVariableNameFunction.INSTANCE); + } - public TypeFactory(List> entityAnnotations, Function variableNameFunction) { - this.entityAnnotations = entityAnnotations; - this.variableNameFunction = variableNameFunction; - } + public TypeFactory( + List> entityAnnotations, + Function variableNameFunction) { + this.entityAnnotations = entityAnnotations; + this.variableNameFunction = variableNameFunction; + } - public EntityType getEntityType(Class cl) { - java.lang.reflect.Type generic = cl; - if (cl.getTypeParameters().length > 0) { - generic = new ParameterizedTypeImpl(cl, cl.getTypeParameters()); + public EntityType getEntityType(Class cl) { + java.lang.reflect.Type generic = cl; + if (cl.getTypeParameters().length > 0) { + generic = new ParameterizedTypeImpl(cl, cl.getTypeParameters()); + } + return (EntityType) get(true, cl, null, generic); + } + + public Type get(Class cl) { + return get(cl, cl); + } + + public Type get(Class cl, java.lang.reflect.Type genericType) { + return get(isEntityClass(cl), cl, null, genericType); + } + + public Type get(Class cl, AnnotatedElement annotated, java.lang.reflect.Type genericType) { + return get(isEntityClass(cl), cl, annotated, genericType); + } + + public Type get(boolean entity, Class cl, java.lang.reflect.Type genericType) { + return get(entity, cl, null, genericType); + } + + public Type get( + boolean entity, Class cl, AnnotatedElement annotated, java.lang.reflect.Type genericType) { + List key = new ArrayList<>(); + key.add(genericType); + AnnotationHelper annotationHelper = null; + Annotation selectedAnnotation = null; + if (annotated != null) { + for (Annotation annotation : annotated.getDeclaredAnnotations()) { + for (AnnotationHelper helper : annotationHelpers) { + if (helper.isSupported(annotation.annotationType())) { + key.add(annotation.annotationType()); + selectedAnnotation = annotated.getAnnotation(annotation.annotationType()); + annotationHelper = helper; + key.add(helper.getCustomKey(selectedAnnotation)); + break; + } } - return (EntityType) get(true, cl, null, generic); + } } - - public Type get(Class cl) { - return get(cl, cl); + key = Collections.unmodifiableList(key); + if (cache.containsKey(key)) { + Type value = cache.get(key); + if (entity && !(value instanceof EntityType)) { + value = new EntityType(value, variableNameFunction); + cache.put(key, value); + } + return value; + + } else { + Type value = create(entity, cl, annotationHelper, selectedAnnotation, genericType, key); + cache.put(key, value); + return value; } - - public Type get(Class cl, java.lang.reflect.Type genericType) { - return get(isEntityClass(cl), cl, null, genericType); + } + + private Type create( + boolean entity, + Class cl, + AnnotationHelper annotationHelper, + Annotation annotation, + java.lang.reflect.Type genericType, + List key) { + if (cl.isPrimitive()) { + cl = PrimitiveUtils.wrap(cl); } - - public Type get(Class cl, AnnotatedElement annotated, java.lang.reflect.Type genericType) { - return get(isEntityClass(cl), cl, annotated, genericType); + Type value; + Type[] tempParams = + (Type[]) Array.newInstance(Type.class, ReflectionUtils.getTypeParameterCount(genericType)); + cache.put(key, new ClassType(cl, tempParams)); + Type[] parameters = getParameters(cl, genericType); + + if (cl.isArray()) { + Type componentType = get(cl.getComponentType()); + if (cl.getComponentType().isPrimitive()) { + componentType = Types.PRIMITIVES.get(componentType); + } + value = componentType.asArrayType(); + } else if (cl.isEnum()) { + value = new ClassType(TypeCategory.ENUM, cl); + } else if (Number.class.isAssignableFrom(cl) && Comparable.class.isAssignableFrom(cl)) { + value = new ClassType(TypeCategory.NUMERIC, cl, parameters); + } else if (entity) { + value = createOther(cl, entity, annotationHelper, annotation, parameters); + } else if (Map.class.isAssignableFrom(cl)) { + value = new SimpleType(Types.MAP, parameters[0], asGeneric(parameters[1])); + } else if (List.class.isAssignableFrom(cl)) { + value = new SimpleType(Types.LIST, asGeneric(parameters[0])); + } else if (Set.class.isAssignableFrom(cl)) { + value = new SimpleType(Types.SET, asGeneric(parameters[0])); + } else if (Collection.class.isAssignableFrom(cl)) { + value = new SimpleType(Types.COLLECTION, asGeneric(parameters[0])); + } else { + value = createOther(cl, entity, annotationHelper, annotation, parameters); } - public Type get(boolean entity, Class cl, java.lang.reflect.Type genericType) { - return get(entity, cl, null, genericType); + if (genericType instanceof TypeVariable) { + TypeVariable tv = (TypeVariable) genericType; + if (tv.getBounds().length == 1 && tv.getBounds()[0].equals(Object.class)) { + value = new TypeSuper(tv.getName(), value); + } else { + value = new TypeExtends(tv.getName(), value); + } } - public Type get(boolean entity, Class cl, AnnotatedElement annotated, java.lang.reflect.Type genericType) { - List key = new ArrayList<>(); - key.add(genericType); - AnnotationHelper annotationHelper = null; - Annotation selectedAnnotation = null; - if (annotated != null) { - for (Annotation annotation : annotated.getDeclaredAnnotations()) { - for (AnnotationHelper helper : annotationHelpers) { - if (helper.isSupported(annotation.annotationType())) { - key.add(annotation.annotationType()); - selectedAnnotation = annotated.getAnnotation(annotation.annotationType()); - annotationHelper = helper; - key.add(helper.getCustomKey(selectedAnnotation)); - break; - } - } - } - } - key = Collections.unmodifiableList(key); - if (cache.containsKey(key)) { - Type value = cache.get(key); - if (entity && !(value instanceof EntityType)) { - value = new EntityType(value, variableNameFunction); - cache.put(key, value); - } - return value; - - } else { - Type value = create(entity, cl, annotationHelper, selectedAnnotation, genericType, key); - cache.put(key, value); - return value; - } + if (entity && !(value instanceof EntityType)) { + value = new EntityType(value, variableNameFunction); } - - private Type create(boolean entity, Class cl, AnnotationHelper annotationHelper, Annotation annotation, java.lang.reflect.Type genericType, - List key) { - if (cl.isPrimitive()) { - cl = PrimitiveUtils.wrap(cl); - } - Type value; - Type[] tempParams = (Type[]) Array.newInstance(Type.class, - ReflectionUtils.getTypeParameterCount(genericType)); - cache.put(key, new ClassType(cl, tempParams)); - Type[] parameters = getParameters(cl, genericType); - - if (cl.isArray()) { - Type componentType = get(cl.getComponentType()); - if (cl.getComponentType().isPrimitive()) { - componentType = Types.PRIMITIVES.get(componentType); - } - value = componentType.asArrayType(); - } else if (cl.isEnum()) { - value = new ClassType(TypeCategory.ENUM, cl); - } else if (Number.class.isAssignableFrom(cl) && Comparable.class.isAssignableFrom(cl)) { - value = new ClassType(TypeCategory.NUMERIC, cl, parameters); - } else if (entity) { - value = createOther(cl, entity, annotationHelper, annotation, parameters); - } else if (Map.class.isAssignableFrom(cl)) { - value = new SimpleType(Types.MAP, parameters[0], asGeneric(parameters[1])); - } else if (List.class.isAssignableFrom(cl)) { - value = new SimpleType(Types.LIST, asGeneric(parameters[0])); - } else if (Set.class.isAssignableFrom(cl)) { - value = new SimpleType(Types.SET, asGeneric(parameters[0])); - } else if (Collection.class.isAssignableFrom(cl)) { - value = new SimpleType(Types.COLLECTION, asGeneric(parameters[0])); - } else { - value = createOther(cl, entity, annotationHelper, annotation, parameters); - } - - if (genericType instanceof TypeVariable) { - TypeVariable tv = (TypeVariable) genericType; - if (tv.getBounds().length == 1 && tv.getBounds()[0].equals(Object.class)) { - value = new TypeSuper(tv.getName(), value); - } else { - value = new TypeExtends(tv.getName(), value); - } - } - - if (entity && !(value instanceof EntityType)) { - value = new EntityType(value, variableNameFunction); - } - return value; - } - - private Type asGeneric(Type type) { - if (type.getParameters().size() == 0) { - int count = type.getJavaClass().getTypeParameters().length; - if (count > 0) { - return new SimpleType(type, new Type[count]); - } - } - return type; + return value; + } + + private Type asGeneric(Type type) { + if (type.getParameters().size() == 0) { + int count = type.getJavaClass().getTypeParameters().length; + if (count > 0) { + return new SimpleType(type, new Type[count]); + } } - - private Type createOther(Class cl, boolean entity, AnnotationHelper annotationHelper, Annotation annotation, Type[] parameters) { - TypeCategory typeCategory = TypeCategory.get(cl.getName()); - if (annotationHelper != null) { - typeCategory = annotationHelper.getTypeByAnnotation(cl, annotation); - } else if (embeddableTypes.contains(cl)) { - typeCategory = TypeCategory.CUSTOM; - } else if (unknownAsEntity && typeCategory == TypeCategory.SIMPLE && !cl.getName().startsWith("java")) { - typeCategory = TypeCategory.CUSTOM; - } else if (typeCategory == TypeCategory.SIMPLE && entity) { - typeCategory = TypeCategory.ENTITY; - } else if (!typeCategory.isSubCategoryOf(TypeCategory.COMPARABLE) && Comparable.class.isAssignableFrom(cl) - && !cl.equals(Comparable.class)) { - typeCategory = TypeCategory.COMPARABLE; - } - - return new ClassType(typeCategory, cl, parameters); + return type; + } + + private Type createOther( + Class cl, + boolean entity, + AnnotationHelper annotationHelper, + Annotation annotation, + Type[] parameters) { + TypeCategory typeCategory = TypeCategory.get(cl.getName()); + if (annotationHelper != null) { + typeCategory = annotationHelper.getTypeByAnnotation(cl, annotation); + } else if (embeddableTypes.contains(cl)) { + typeCategory = TypeCategory.CUSTOM; + } else if (unknownAsEntity + && typeCategory == TypeCategory.SIMPLE + && !cl.getName().startsWith("java")) { + typeCategory = TypeCategory.CUSTOM; + } else if (typeCategory == TypeCategory.SIMPLE && entity) { + typeCategory = TypeCategory.ENTITY; + } else if (!typeCategory.isSubCategoryOf(TypeCategory.COMPARABLE) + && Comparable.class.isAssignableFrom(cl) + && !cl.equals(Comparable.class)) { + typeCategory = TypeCategory.COMPARABLE; } - private Type[] getParameters(Class cl, java.lang.reflect.Type genericType) { - int parameterCount = ReflectionUtils.getTypeParameterCount(genericType); - if (parameterCount > 0) { - return getGenericParameters(cl, genericType, parameterCount); - } else if (Map.class.isAssignableFrom(cl)) { - return new Type[]{Types.OBJECT, Types.OBJECT}; - } else if (Collection.class.isAssignableFrom(cl)) { - return new Type[]{Types.OBJECT}; - } else { - return new Type[0]; - } + return new ClassType(typeCategory, cl, parameters); + } + + private Type[] getParameters(Class cl, java.lang.reflect.Type genericType) { + int parameterCount = ReflectionUtils.getTypeParameterCount(genericType); + if (parameterCount > 0) { + return getGenericParameters(cl, genericType, parameterCount); + } else if (Map.class.isAssignableFrom(cl)) { + return new Type[] {Types.OBJECT, Types.OBJECT}; + } else if (Collection.class.isAssignableFrom(cl)) { + return new Type[] {Types.OBJECT}; + } else { + return new Type[0]; } + } - private Type[] getGenericParameters(Class cl, java.lang.reflect.Type genericType, - int parameterCount) { - Type[] types = new Type[parameterCount]; - for (int i = 0; i < types.length; i++) { - types[i] = getGenericParameter(cl, genericType, i); - } - return types; + private Type[] getGenericParameters( + Class cl, java.lang.reflect.Type genericType, int parameterCount) { + Type[] types = new Type[parameterCount]; + for (int i = 0; i < types.length; i++) { + types[i] = getGenericParameter(cl, genericType, i); } - - @SuppressWarnings("rawtypes") - private Type getGenericParameter(Class cl, java.lang.reflect.Type genericType, int i) { - java.lang.reflect.Type parameter = ReflectionUtils.getTypeParameter(genericType, i); - if (parameter instanceof TypeVariable) { - TypeVariable variable = (TypeVariable) parameter; - Type rv = get(ReflectionUtils.getTypeParameterAsClass(genericType, i), null, parameter); - return new TypeExtends(variable.getName(), rv); - } else if (parameter instanceof WildcardType - && ((WildcardType) parameter).getUpperBounds()[0].equals(Object.class) - && ((WildcardType) parameter).getLowerBounds().length == 0) { - return ANY; - } else { - Type rv = get(ReflectionUtils.getTypeParameterAsClass(genericType, i), null, parameter); - if (parameter instanceof WildcardType) { - rv = new TypeExtends(rv); - } - return rv; - } + return types; + } + + @SuppressWarnings("rawtypes") + private Type getGenericParameter(Class cl, java.lang.reflect.Type genericType, int i) { + java.lang.reflect.Type parameter = ReflectionUtils.getTypeParameter(genericType, i); + if (parameter instanceof TypeVariable) { + TypeVariable variable = (TypeVariable) parameter; + Type rv = get(ReflectionUtils.getTypeParameterAsClass(genericType, i), null, parameter); + return new TypeExtends(variable.getName(), rv); + } else if (parameter instanceof WildcardType + && ((WildcardType) parameter).getUpperBounds()[0].equals(Object.class) + && ((WildcardType) parameter).getLowerBounds().length == 0) { + return ANY; + } else { + Type rv = get(ReflectionUtils.getTypeParameterAsClass(genericType, i), null, parameter); + if (parameter instanceof WildcardType) { + rv = new TypeExtends(rv); + } + return rv; } + } - private boolean isEntityClass(Class cl) { - for (Class clazz : entityAnnotations) { - if (cl.isAnnotationPresent(clazz)) { - return true; - } - } - return embeddableTypes.contains(cl); + private boolean isEntityClass(Class cl) { + for (Class clazz : entityAnnotations) { + if (cl.isAnnotationPresent(clazz)) { + return true; + } } - - public void extendTypes() { - for (Map.Entry, Type> entry : cache.entrySet()) { - if (entry.getValue() instanceof EntityType) { - EntityType entityType = (EntityType) entry.getValue(); - if (entityType.getProperties().isEmpty()) { - for (Type type : cache.values()) { - if (type.getFullName().equals(entityType.getFullName()) && type instanceof EntityType) { - EntityType base = (EntityType) type; - for (Property property : base.getProperties()) { - entityType.addProperty(property); - } - } - } - } + return embeddableTypes.contains(cl); + } + + public void extendTypes() { + for (Map.Entry, Type> entry : cache.entrySet()) { + if (entry.getValue() instanceof EntityType) { + EntityType entityType = (EntityType) entry.getValue(); + if (entityType.getProperties().isEmpty()) { + for (Type type : cache.values()) { + if (type.getFullName().equals(entityType.getFullName()) && type instanceof EntityType) { + EntityType base = (EntityType) type; + for (Property property : base.getProperties()) { + entityType.addProperty(property); + } } + } } + } } + } - public void setUnknownAsEntity(boolean unknownAsEntity) { - this.unknownAsEntity = unknownAsEntity; - } + public void setUnknownAsEntity(boolean unknownAsEntity) { + this.unknownAsEntity = unknownAsEntity; + } - public void addEmbeddableType(Class cl) { - embeddableTypes.add(cl); - } + public void addEmbeddableType(Class cl) { + embeddableTypes.add(cl); + } - public void addAnnotationHelper(AnnotationHelper annotationHelper) { - annotationHelpers.add(annotationHelper); - } + public void addAnnotationHelper(AnnotationHelper annotationHelper) { + annotationHelpers.add(annotationHelper); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeMappings.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeMappings.java index 1dac1e5d94..222739f703 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeMappings.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeMappings.java @@ -13,125 +13,134 @@ */ package com.querydsl.codegen; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import org.jetbrains.annotations.Nullable; - import com.querydsl.codegen.utils.model.*; import com.querydsl.core.types.Expression; import com.querydsl.core.types.Path; import com.querydsl.core.types.TemplateExpression; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import org.jetbrains.annotations.Nullable; /** * {@code TypeMappings} defines mappings from Java types to {@link Expression}, {@link Path} and * {@link TemplateExpression} types * * @author tiwe - * */ public abstract class TypeMappings { - private final Map genericQueryTypes = new HashMap(); + private final Map genericQueryTypes = new HashMap(); - private final Map queryTypes = new HashMap(); + private final Map queryTypes = new HashMap(); - private final Map exprTypes - = new EnumMap(TypeCategory.class); + private final Map exprTypes = + new EnumMap(TypeCategory.class); - private final Map pathTypes - = new EnumMap(TypeCategory.class); + private final Map pathTypes = + new EnumMap(TypeCategory.class); - private final Map templateTypes - = new EnumMap(TypeCategory.class); + private final Map templateTypes = + new EnumMap(TypeCategory.class); - public Type getTemplateType(Type type, EntityType model, boolean raw) { - return getTemplateType(type, model, raw, false, false); - } + public Type getTemplateType(Type type, EntityType model, boolean raw) { + return getTemplateType(type, model, raw, false, false); + } - public Type getTemplateType(Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { - return getQueryType(templateTypes, type, model, raw, rawParameters, extend); - } + public Type getTemplateType( + Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { + return getQueryType(templateTypes, type, model, raw, rawParameters, extend); + } - public Type getExprType(Type type, EntityType model, boolean raw) { - return getExprType(type, model, raw, false, false); - } + public Type getExprType(Type type, EntityType model, boolean raw) { + return getExprType(type, model, raw, false, false); + } - public Type getExprType(Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { - if (genericQueryTypes.containsKey(type)) { - return genericQueryTypes.get(type); - } else if (queryTypes.containsKey(type.getFullName())) { - return queryTypes.get(type.getFullName()); - } else { - return getQueryType(exprTypes, type, model, raw, rawParameters, extend); - } + public Type getExprType( + Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { + if (genericQueryTypes.containsKey(type)) { + return genericQueryTypes.get(type); + } else if (queryTypes.containsKey(type.getFullName())) { + return queryTypes.get(type.getFullName()); + } else { + return getQueryType(exprTypes, type, model, raw, rawParameters, extend); } - - public Type getPathType(Type type, EntityType model, boolean raw) { - return getPathType(type, model, raw, false, false); + } + + public Type getPathType(Type type, EntityType model, boolean raw) { + return getPathType(type, model, raw, false, false); + } + + public Type getPathType( + Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { + if (genericQueryTypes.containsKey(type)) { + return genericQueryTypes.get(type); + } else if (queryTypes.containsKey(type.getFullName())) { + return queryTypes.get(type.getFullName()); + } else { + return getQueryType(pathTypes, type, model, raw, rawParameters, extend); } - - public Type getPathType(Type type, EntityType model, boolean raw, boolean rawParameters, boolean extend) { - if (genericQueryTypes.containsKey(type)) { - return genericQueryTypes.get(type); - } else if (queryTypes.containsKey(type.getFullName())) { - return queryTypes.get(type.getFullName()); - } else { - return getQueryType(pathTypes, type, model, raw, rawParameters, extend); - } + } + + private Type getQueryType( + Map types, + Type type, + EntityType model, + boolean raw, + boolean rawParameters, + boolean extend) { + Type exprType = types.get(type.getCategory()); + return getQueryType(type, model, exprType, raw, rawParameters, extend); + } + + public Type getQueryType( + Type type, + EntityType model, + Type exprType, + boolean raw, + boolean rawParameters, + boolean extend) { + TypeCategory category = type.getCategory(); + if (raw && category != TypeCategory.ENTITY && category != TypeCategory.CUSTOM) { + return exprType; + + } else if (category == TypeCategory.STRING || category == TypeCategory.BOOLEAN) { + return exprType; + + } else { + if (rawParameters) { + type = new SimpleType(type); + } + if (!type.isFinal() && extend) { + type = new TypeExtends(type); + } + return new SimpleType(exprType, type); } - - private Type getQueryType(Map types, Type type, EntityType model, boolean raw, - boolean rawParameters, boolean extend) { - Type exprType = types.get(type.getCategory()); - return getQueryType(type, model, exprType, raw, rawParameters, extend); + } + + @SuppressWarnings("rawtypes") + public void register( + TypeCategory category, + @Nullable Class expr, + @Nullable Class path, + @Nullable Class template) { + if (expr != null) { + exprTypes.put(category, new ClassType(expr)); } - - public Type getQueryType(Type type, EntityType model, Type exprType, boolean raw, - boolean rawParameters, boolean extend) { - TypeCategory category = type.getCategory(); - if (raw && category != TypeCategory.ENTITY && category != TypeCategory.CUSTOM) { - return exprType; - - } else if (category == TypeCategory.STRING || category == TypeCategory.BOOLEAN) { - return exprType; - - } else { - if (rawParameters) { - type = new SimpleType(type); - } - if (!type.isFinal() && extend) { - type = new TypeExtends(type); - } - return new SimpleType(exprType, type); - - } + if (path != null) { + pathTypes.put(category, new ClassType(path)); } - - @SuppressWarnings("rawtypes") - public void register(TypeCategory category, - @Nullable Class expr, - @Nullable Class path, - @Nullable Class template) { - if (expr != null) { - exprTypes.put(category, new ClassType(expr)); - } - if (path != null) { - pathTypes.put(category, new ClassType(path)); - } - if (template != null) { - templateTypes.put(category, new ClassType(template)); - } + if (template != null) { + templateTypes.put(category, new ClassType(template)); } + } - public void register(Type type, Type queryType) { - queryTypes.put(type.getFullName(), queryType); - genericQueryTypes.put(type, queryType); - } - - public boolean isRegistered(Type type) { - return queryTypes.containsKey(type.getFullName()); - } + public void register(Type type, Type queryType) { + queryTypes.put(type.getFullName(), queryType); + genericQueryTypes.put(type, queryType); + } + public boolean isRegistered(Type type) { + return queryTypes.containsKey(type.getFullName()); + } } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeResolver.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeResolver.java index 5bed50c757..4a4142a654 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeResolver.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/TypeResolver.java @@ -17,112 +17,111 @@ import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeExtends; import com.querydsl.codegen.utils.model.TypeSuper; - import java.util.Objects; /** - * {@code TypeResolver} provides type resolving functionality for resolving generic type variables to - * concrete types + * {@code TypeResolver} provides type resolving functionality for resolving generic type variables + * to concrete types * * @author tiwe - * */ final class TypeResolver { - /** - * Resolve type declared in declaringType for context - * - * @param type type to be resolved - * @param declaringType declaration context of type - * @param context target context of type - * @return resolved type - */ - public static Type resolve(Type type, Type declaringType, EntityType context) { - Type resolved = unwrap(type); + /** + * Resolve type declared in declaringType for context + * + * @param type type to be resolved + * @param declaringType declaration context of type + * @param context target context of type + * @return resolved type + */ + public static Type resolve(Type type, Type declaringType, EntityType context) { + Type resolved = unwrap(type); - String varName = getVarName(resolved); - if (varName != null) { - resolved = resolveVar(resolved, varName, declaringType, context); - } else if (!resolved.getParameters().isEmpty()) { - resolved = resolveWithParameters(resolved, declaringType, context); - } - - // rewrap entity type - if (type instanceof EntityType) { - if (!unwrap(type).equals(resolved)) { - resolved = new EntityType(resolved, ((EntityType) type).getSuperTypes()); - } else { - // reset to original type - resolved = type; - } - } + String varName = getVarName(resolved); + if (varName != null) { + resolved = resolveVar(resolved, varName, declaringType, context); + } else if (!resolved.getParameters().isEmpty()) { + resolved = resolveWithParameters(resolved, declaringType, context); + } - return resolved; + // rewrap entity type + if (type instanceof EntityType) { + if (!unwrap(type).equals(resolved)) { + resolved = new EntityType(resolved, ((EntityType) type).getSuperTypes()); + } else { + // reset to original type + resolved = type; + } } - private static Type resolveVar(Type resolved, String varName, Type declaringType, EntityType context) { - // get parameter index of var in declaring type - int index = -1; - for (int i = 0; i < declaringType.getParameters().size(); i++) { - Type param = unwrap(declaringType.getParameters().get(i)); - if (Objects.equals(getVarName(param), varName)) { - index = i; - } - } + return resolved; + } - if (index == -1) { - throw new IllegalStateException("Did not find type " + varName - + " in " + declaringType + " for " + context); - } + private static Type resolveVar( + Type resolved, String varName, Type declaringType, EntityType context) { + // get parameter index of var in declaring type + int index = -1; + for (int i = 0; i < declaringType.getParameters().size(); i++) { + Type param = unwrap(declaringType.getParameters().get(i)); + if (Objects.equals(getVarName(param), varName)) { + index = i; + } + } - Supertype type = context.getSuperType(); - while (!type.getEntityType().equals(declaringType)) { - type = type.getEntityType().getSuperType(); - } - if (!type.getType().getParameters().isEmpty()) { - return type.getType().getParameters().get(index); - } else { - // raw type - return resolved; - } + if (index == -1) { + throw new IllegalStateException( + "Did not find type " + varName + " in " + declaringType + " for " + context); } - private static Type resolveWithParameters(Type type, Type declaringType, EntityType context) { - Type[] params = new Type[type.getParameters().size()]; - boolean transformed = false; - for (int i = 0; i < type.getParameters().size(); i++) { - Type param = type.getParameters().get(i); - if (param != null && !param.getFullName().equals(type.getFullName())) { - params[i] = resolve(param, declaringType, context); - if (!params[i].equals(param)) { - transformed = true; - } - } - } - if (transformed) { - return new SimpleType(type, params); - } else { - return type; - } + Supertype type = context.getSuperType(); + while (!type.getEntityType().equals(declaringType)) { + type = type.getEntityType().getSuperType(); + } + if (!type.getType().getParameters().isEmpty()) { + return type.getType().getParameters().get(index); + } else { + // raw type + return resolved; } + } - private static String getVarName(Type type) { - if (type instanceof TypeExtends) { - return ((TypeExtends) type).getVarName(); - } else if (type instanceof TypeSuper) { - return ((TypeSuper) type).getVarName(); - } else { - return null; + private static Type resolveWithParameters(Type type, Type declaringType, EntityType context) { + Type[] params = new Type[type.getParameters().size()]; + boolean transformed = false; + for (int i = 0; i < type.getParameters().size(); i++) { + Type param = type.getParameters().get(i); + if (param != null && !param.getFullName().equals(type.getFullName())) { + params[i] = resolve(param, declaringType, context); + if (!params[i].equals(param)) { + transformed = true; } + } } + if (transformed) { + return new SimpleType(type, params); + } else { + return type; + } + } - private static Type unwrap(Type type) { - if (type instanceof EntityType) { - return ((EntityType) type).getInnerType(); - } else { - return type; - } + private static String getVarName(Type type) { + if (type instanceof TypeExtends) { + return ((TypeExtends) type).getVarName(); + } else if (type instanceof TypeSuper) { + return ((TypeSuper) type).getVarName(); + } else { + return null; + } + } + + private static Type unwrap(Type type) { + if (type instanceof EntityType) { + return ((EntityType) type).getInnerType(); + } else { + return type; } + } - private TypeResolver() { } + private TypeResolver() {} } diff --git a/querydsl-codegen/src/main/java/com/querydsl/codegen/package-info.java b/querydsl-codegen/src/main/java/com/querydsl/codegen/package-info.java index ea768ab1e4..f3809a7237 100644 --- a/querydsl-codegen/src/main/java/com/querydsl/codegen/package-info.java +++ b/querydsl-codegen/src/main/java/com/querydsl/codegen/package-info.java @@ -12,7 +12,5 @@ * limitations under the License. */ -/** - * Code generations models and serializers - */ +/** Code generations models and serializers */ package com.querydsl.codegen; diff --git a/querydsl-codegen/src/test/java/Entity.java b/querydsl-codegen/src/test/java/Entity.java index fba51de198..4547065098 100644 --- a/querydsl-codegen/src/test/java/Entity.java +++ b/querydsl-codegen/src/test/java/Entity.java @@ -1,17 +1,16 @@ - public class Entity { - private String name; + private String name; - public static String test(Object o) { - return null; - } + public static String test(Object o) { + return null; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/querydsl-codegen/src/test/java/Entity2.java b/querydsl-codegen/src/test/java/Entity2.java index 6c355cec1c..76fc92aa94 100644 --- a/querydsl-codegen/src/test/java/Entity2.java +++ b/querydsl-codegen/src/test/java/Entity2.java @@ -1,13 +1,12 @@ - public class Entity2 { - private String name; + private String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/querydsl-codegen/src/test/java/com/SomeClass.java b/querydsl-codegen/src/test/java/com/SomeClass.java index a9b89077d5..5f9a2975b4 100644 --- a/querydsl-codegen/src/test/java/com/SomeClass.java +++ b/querydsl-codegen/src/test/java/com/SomeClass.java @@ -13,6 +13,4 @@ */ package com; -public class SomeClass { - -} +public class SomeClass {} diff --git a/querydsl-codegen/src/test/java/com/applejuice/ShouldBeLoaded.java b/querydsl-codegen/src/test/java/com/applejuice/ShouldBeLoaded.java index 8402147751..3b6037618c 100644 --- a/querydsl-codegen/src/test/java/com/applejuice/ShouldBeLoaded.java +++ b/querydsl-codegen/src/test/java/com/applejuice/ShouldBeLoaded.java @@ -1,4 +1,3 @@ package com.applejuice; -public class ShouldBeLoaded { -} +public class ShouldBeLoaded {} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/AbstractExporterTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/AbstractExporterTest.java index b7830e4939..841caea310 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/AbstractExporterTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/AbstractExporterTest.java @@ -1,16 +1,14 @@ package com.querydsl.codegen; import java.io.File; - import org.junit.Test; public abstract class AbstractExporterTest { - @Test - public void test() { - GenericExporter exporter = new GenericExporter(); - exporter.setTargetFolder(new File("target/" + getClass().getSimpleName())); - exporter.export(getClass().getClasses()); - } - + @Test + public void test() { + GenericExporter exporter = new GenericExporter(); + exporter.setTargetFolder(new File("target/" + getClass().getSimpleName())); + exporter.export(getClass().getClasses()); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/BeanSerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/BeanSerializerTest.java index afa7945288..2f8cc8fbd3 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/BeanSerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/BeanSerializerTest.java @@ -13,6 +13,11 @@ */ package com.querydsl.codegen; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + import com.querydsl.codegen.utils.JavaWriter; import com.querydsl.codegen.utils.StringUtils; import com.querydsl.codegen.utils.model.ClassType; @@ -21,186 +26,206 @@ import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.codegen.utils.model.Types; import com.querydsl.core.annotations.Generated; -import org.junit.Before; -import org.junit.Test; - import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.Arrays; import java.util.Date; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; public class BeanSerializerTest { - private Type typeModel; - - private EntityType type; - - private final Writer writer = new StringWriter(); - - @Before - public void setUp() { - typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - type = new EntityType(typeModel); - } - - @Test - public void annotations() throws IOException { - type.addAnnotation(new QueryEntityImpl()); - - BeanSerializer serializer = new BeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String str = writer.toString(); - - assertTrue(str.contains("import com.querydsl.core.annotations.QueryEntity;")); - assertTrue(str.contains("@QueryEntity")); - } - - @Test - public void annotated_property() throws IOException { - Property property = new Property(type, "entityField", type); - property.addAnnotation(new QueryEntityImpl()); - type.addProperty(property); - - BeanSerializer serializer = new BeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String str = writer.toString(); - - assertTrue(str.contains("import com.querydsl.core.annotations.QueryEntity;")); - assertTrue(str.contains("@QueryEntity")); - } - - @Test - public void annotated_property_not_serialized() throws IOException { - Property property = new Property(type, "entityField", type); - property.addAnnotation(new QueryEntityImpl()); - type.addProperty(property); - - BeanSerializer serializer = new BeanSerializer(false); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String str = writer.toString(); - - assertFalse(str.contains("import com.querydsl.core.annotations.QueryEntity;")); - assertFalse(str.contains("@QueryEntity")); - } - - @Test - public void capitalization() throws IOException { - // property - type.addProperty(new Property(type, "cId", type)); - - BeanSerializer serializer = new BeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public DomainClass getcId() {")); - } - - @Test - public void interfaces() throws IOException { - BeanSerializer serializer = new BeanSerializer(); - serializer.addInterface(new ClassType(Serializable.class)); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class DomainClass implements Serializable {")); + private Type typeModel; + + private EntityType type; + + private final Writer writer = new StringWriter(); + + @Before + public void setUp() { + typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + type = new EntityType(typeModel); + } + + @Test + public void annotations() throws IOException { + type.addAnnotation(new QueryEntityImpl()); + + BeanSerializer serializer = new BeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String str = writer.toString(); + + assertTrue(str.contains("import com.querydsl.core.annotations.QueryEntity;")); + assertTrue(str.contains("@QueryEntity")); + } + + @Test + public void annotated_property() throws IOException { + Property property = new Property(type, "entityField", type); + property.addAnnotation(new QueryEntityImpl()); + type.addProperty(property); + + BeanSerializer serializer = new BeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String str = writer.toString(); + + assertTrue(str.contains("import com.querydsl.core.annotations.QueryEntity;")); + assertTrue(str.contains("@QueryEntity")); + } + + @Test + public void annotated_property_not_serialized() throws IOException { + Property property = new Property(type, "entityField", type); + property.addAnnotation(new QueryEntityImpl()); + type.addProperty(property); + + BeanSerializer serializer = new BeanSerializer(false); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String str = writer.toString(); + + assertFalse(str.contains("import com.querydsl.core.annotations.QueryEntity;")); + assertFalse(str.contains("@QueryEntity")); + } + + @Test + public void capitalization() throws IOException { + // property + type.addProperty(new Property(type, "cId", type)); + + BeanSerializer serializer = new BeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public DomainClass getcId() {")); + } + + @Test + public void interfaces() throws IOException { + BeanSerializer serializer = new BeanSerializer(); + serializer.addInterface(new ClassType(Serializable.class)); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class DomainClass implements Serializable {")); + } + + @Test + public void interfaces2() throws IOException { + BeanSerializer serializer = new BeanSerializer(); + serializer.addInterface(Serializable.class); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class DomainClass implements Serializable {")); + } + + @Test + public void toString_() throws IOException { + // property + type.addProperty(new Property(type, "entityField", type)); + type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); + type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); + type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); + type.addProperty( + new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); + type.addProperty( + new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); + + BeanSerializer serializer = new BeanSerializer(); + serializer.setAddToString(true); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(String.valueOf(writer).contains(" @Override\n" + " public String toString()")); + } + + @Test + public void fullConstructor() throws IOException { + // property + type.addProperty(new Property(type, "entityField", type)); + type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); + type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); + type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); + type.addProperty( + new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); + type.addProperty( + new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); + + BeanSerializer serializer = new BeanSerializer(); + serializer.setAddFullConstructor(true); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + // System.out.println(writer.toString()); + } + + @Test + public void properties() throws IOException { + // property + type.addProperty(new Property(type, "entityField", type)); + type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); + type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); + type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); + type.addProperty( + new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); + type.addProperty( + new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); + + for (Class cl : + Arrays.>asList( + Boolean.class, + Comparable.class, + Integer.class, + Date.class, + java.sql.Date.class, + java.sql.Time.class)) { + Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); + type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); } - @Test - public void interfaces2() throws IOException { - BeanSerializer serializer = new BeanSerializer(); - serializer.addInterface(Serializable.class); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class DomainClass implements Serializable {")); + BeanSerializer serializer = new BeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String str = writer.toString(); + // System.err.println(str); + for (String prop : + Arrays.asList( + "String[] arrayField;", + "Boolean boolean$;", + "Collection collection;", + "Comparable comparable;", + "java.util.Date date;", + "DomainClass entityField;", + "Integer integer;", + "List listField;", + "Map mapField;", + "Set setField;", + "java.sql.Time time;")) { + assertTrue(prop + " was not contained", str.contains(prop)); } - - @Test - public void toString_() throws IOException { - // property - type.addProperty(new Property(type, "entityField", type)); - type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); - type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); - type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); - type.addProperty(new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); - type.addProperty(new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); - - BeanSerializer serializer = new BeanSerializer(); - serializer.setAddToString(true); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(String.valueOf(writer).contains( - " @Override\n" - + " public String toString()")); - } - - @Test - public void fullConstructor() throws IOException { - // property - type.addProperty(new Property(type, "entityField", type)); - type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); - type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); - type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); - type.addProperty(new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); - type.addProperty(new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); - - BeanSerializer serializer = new BeanSerializer(); - serializer.setAddFullConstructor(true); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - //System.out.println(writer.toString()); - } - - @Test - public void properties() throws IOException { - // property - type.addProperty(new Property(type, "entityField", type)); - type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); - type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); - type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); - type.addProperty(new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); - type.addProperty(new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); - - for (Class cl : Arrays.>asList(Boolean.class, Comparable.class, Integer.class, Date.class, java.sql.Date.class, java.sql.Time.class)) { - Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); - type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); - } - - BeanSerializer serializer = new BeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String str = writer.toString(); - //System.err.println(str); - for (String prop : Arrays.asList( - "String[] arrayField;", - "Boolean boolean$;", - "Collection collection;", - "Comparable comparable;", - "java.util.Date date;", - "DomainClass entityField;", - "Integer integer;", - "List listField;", - "Map mapField;", - "Set setField;", - "java.sql.Time time;")) { - assertTrue(prop + " was not contained", str.contains(prop)); - } - } - - @Test - public void defaultsGeneratedAnnotation() throws IOException { - Serializer serializer = new BeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSource = String.valueOf(writer); - assertThat(generatedSource, containsString(String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); - assertThat(generatedSource, containsString("@Generated(\"com.querydsl.codegen.BeanSerializer\")\npublic class")); - } - - @Test - public void customGeneratedAnnotation() throws IOException { - Serializer serializer = new BeanSerializer(BeanSerializer.DEFAULT_JAVADOC_SUFFIX, Generated.class); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSource = String.valueOf(writer); - assertThat(generatedSource, containsString("import com.querydsl.core.annotations.Generated;")); - assertThat(generatedSource, containsString("@Generated(\"com.querydsl.codegen.BeanSerializer\")\npublic class")); - } - + } + + @Test + public void defaultsGeneratedAnnotation() throws IOException { + Serializer serializer = new BeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSource = String.valueOf(writer); + assertThat( + generatedSource, + containsString( + String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); + assertThat( + generatedSource, + containsString("@Generated(\"com.querydsl.codegen.BeanSerializer\")\npublic class")); + } + + @Test + public void customGeneratedAnnotation() throws IOException { + Serializer serializer = + new BeanSerializer(BeanSerializer.DEFAULT_JAVADOC_SUFFIX, Generated.class); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSource = String.valueOf(writer); + assertThat(generatedSource, containsString("import com.querydsl.core.annotations.Generated;")); + assertThat( + generatedSource, + containsString("@Generated(\"com.querydsl.codegen.BeanSerializer\")\npublic class")); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ClassPathUtilsTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ClassPathUtilsTest.java index 910219fe77..7a5bbfc2dc 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ClassPathUtilsTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ClassPathUtilsTest.java @@ -15,39 +15,36 @@ import static org.junit.Assert.*; +import com.SomeClass; import java.io.IOException; import java.util.Set; - import org.junit.Test; -import com.SomeClass; - public class ClassPathUtilsTest { - @Test - public void scanPackage() throws IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Set> classes = ClassPathUtils.scanPackage(classLoader, SomeClass.class.getPackage()); - assertFalse(classes.isEmpty()); - } - - @Test - public void scanPackage_check_initialized() throws IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Set> classes = ClassPathUtils.scanPackage(classLoader, getClass().getPackage()); - assertFalse(classes.isEmpty()); - assertEquals("XXX", SomeOtherClass2.property); - } - - @Test - public void safeClassForName() { - assertNull(safeForName("com.sun.nio.file.ExtendedOpenOption")); - assertNotNull(safeForName("com.suntanning.ShouldBeLoaded")); - assertNotNull(safeForName("com.applejuice.ShouldBeLoaded")); - } - - private Class safeForName(String className) { - return ClassPathUtils.safeClassForName(ClassPathUtilsTest.class.getClassLoader(), className); - } - + @Test + public void scanPackage() throws IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Set> classes = ClassPathUtils.scanPackage(classLoader, SomeClass.class.getPackage()); + assertFalse(classes.isEmpty()); + } + + @Test + public void scanPackage_check_initialized() throws IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Set> classes = ClassPathUtils.scanPackage(classLoader, getClass().getPackage()); + assertFalse(classes.isEmpty()); + assertEquals("XXX", SomeOtherClass2.property); + } + + @Test + public void safeClassForName() { + assertNull(safeForName("com.sun.nio.file.ExtendedOpenOption")); + assertNotNull(safeForName("com.suntanning.ShouldBeLoaded")); + assertNotNull(safeForName("com.applejuice.ShouldBeLoaded")); + } + + private Class safeForName(String className) { + return ClassPathUtils.safeClassForName(ClassPathUtilsTest.class.getClassLoader(), className); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/CodegenModuleTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/CodegenModuleTest.java index 14a1e31d4e..b3fd98c050 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/CodegenModuleTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/CodegenModuleTest.java @@ -16,39 +16,38 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.Test; - import java.lang.annotation.Annotation; +import org.junit.Test; public class CodegenModuleTest { - private final CodegenModule module = new CodegenModule(); - - @Test - public void defaultPrefix() { - assertEquals("Q", module.get(String.class, CodegenModule.PREFIX)); - } - - @Test - public void typeMappings() { - assertNotNull(module.get(TypeMappings.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void get_with_unknown_key() { - module.get(String.class, "XXX"); - } - - @Test - public void defaultGeneratedClass() { - Class o = module.get(Class.class, CodegenModule.GENERATED_ANNOTATION_CLASS); - assertEquals(o, GeneratedAnnotationResolver.resolveDefault()); - } - - @Test - public void javadocSuffixForBeanSerializerOverloadedConstructorInjection() { - String o = module.get(String.class, CodegenModule.JAVADOC_SUFFIX); - assertEquals(o, BeanSerializer.DEFAULT_JAVADOC_SUFFIX); - } - + private final CodegenModule module = new CodegenModule(); + + @Test + public void defaultPrefix() { + assertEquals("Q", module.get(String.class, CodegenModule.PREFIX)); + } + + @Test + public void typeMappings() { + assertNotNull(module.get(TypeMappings.class)); + } + + @Test(expected = IllegalArgumentException.class) + public void get_with_unknown_key() { + module.get(String.class, "XXX"); + } + + @Test + public void defaultGeneratedClass() { + Class o = + module.get(Class.class, CodegenModule.GENERATED_ANNOTATION_CLASS); + assertEquals(o, GeneratedAnnotationResolver.resolveDefault()); + } + + @Test + public void javadocSuffixForBeanSerializerOverloadedConstructorInjection() { + String o = module.get(String.class, CodegenModule.JAVADOC_SUFFIX); + assertEquals(o, BeanSerializer.DEFAULT_JAVADOC_SUFFIX); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/CompileUtils.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/CompileUtils.java index 04b80eab41..356930ab41 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/CompileUtils.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/CompileUtils.java @@ -1,40 +1,42 @@ package com.querydsl.codegen; +import com.querydsl.codegen.utils.MemFileManager; +import com.querydsl.codegen.utils.MemSourceFileObject; +import com.querydsl.codegen.utils.SimpleCompiler; import java.io.StringWriter; import java.io.Writer; import java.util.Arrays; import java.util.Collections; import java.util.List; - import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; - import org.junit.Assert; -import com.querydsl.codegen.utils.MemFileManager; -import com.querydsl.codegen.utils.MemSourceFileObject; -import com.querydsl.codegen.utils.SimpleCompiler; - public final class CompileUtils { - private CompileUtils() { } - - public static void assertCompiles(String name, String source) { - ClassLoader parent = CompileUtils.class.getClassLoader(); - SimpleCompiler compiler = new SimpleCompiler(); - MemFileManager fileManager = new MemFileManager(parent, compiler.getStandardFileManager(null, null, null)); - String classpath = SimpleCompiler.getClassPath(parent); - List compilationOptions = Arrays.asList("-classpath", classpath, "-g:none"); - - // compile - SimpleJavaFileObject javaFileObject = new MemSourceFileObject(name, source); - Writer out = new StringWriter(); - JavaCompiler.CompilationTask task = compiler.getTask(out, fileManager, null, compilationOptions, null, - Collections.singletonList(javaFileObject)); - if (!task.call()) { - Assert.fail("Compilation of " + source + " failed.\n" + out.toString()); - } - + private CompileUtils() {} + + public static void assertCompiles(String name, String source) { + ClassLoader parent = CompileUtils.class.getClassLoader(); + SimpleCompiler compiler = new SimpleCompiler(); + MemFileManager fileManager = + new MemFileManager(parent, compiler.getStandardFileManager(null, null, null)); + String classpath = SimpleCompiler.getClassPath(parent); + List compilationOptions = Arrays.asList("-classpath", classpath, "-g:none"); + + // compile + SimpleJavaFileObject javaFileObject = new MemSourceFileObject(name, source); + Writer out = new StringWriter(); + JavaCompiler.CompilationTask task = + compiler.getTask( + out, + fileManager, + null, + compilationOptions, + null, + Collections.singletonList(javaFileObject)); + if (!task.call()) { + Assert.fail("Compilation of " + source + " failed.\n" + out.toString()); } - + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/CustomTypeTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/CustomTypeTest.java index 25f8f241b3..2f0c3df5dc 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/CustomTypeTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/CustomTypeTest.java @@ -15,40 +15,41 @@ import static org.junit.Assert.assertTrue; -import java.io.IOException; -import java.io.StringWriter; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.codegen.utils.JavaWriter; import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.SimpleType; import com.querydsl.codegen.utils.model.TypeCategory; +import java.io.IOException; +import java.io.StringWriter; +import java.util.Collections; +import org.junit.Test; public class CustomTypeTest { - private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); - - private final TypeMappings typeMappings = new JavaTypeMappings(); + private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); - private final EntitySerializer serializer = new DefaultEntitySerializer(typeMappings, Collections.emptySet()); + private final TypeMappings typeMappings = new JavaTypeMappings(); - private final StringWriter writer = new StringWriter(); + private final EntitySerializer serializer = + new DefaultEntitySerializer(typeMappings, Collections.emptySet()); - @Test - public void customType() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "property", new ClassType(Double[].class))); - typeMappings.register(new ClassType(Double[].class), new ClassType(Point.class)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - assertTrue(typeMappings.isRegistered(entityType.getProperties().iterator().next().getType())); + private final StringWriter writer = new StringWriter(); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains( - "public final com.querydsl.codegen.Point property = " + - "new com.querydsl.codegen.Point(forProperty(\"property\"));")); - } + @Test + public void customType() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty(new Property(entityType, "property", new ClassType(Double[].class))); + typeMappings.register(new ClassType(Double[].class), new ClassType(Point.class)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + assertTrue(typeMappings.isRegistered(entityType.getProperties().iterator().next().getType())); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue( + writer + .toString() + .contains( + "public final com.querydsl.codegen.Point property = " + + "new com.querydsl.codegen.Point(forProperty(\"property\"));")); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/DelegateTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/DelegateTest.java index 373ca5cffa..e66714c006 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/DelegateTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/DelegateTest.java @@ -16,27 +16,48 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.codegen.utils.model.Parameter; import com.querydsl.codegen.utils.model.Types; +import java.util.Collections; +import org.junit.Test; public class DelegateTest { - @Test - public void equals_object() { - Delegate delegate = new Delegate(Types.STRING, Types.STRING, "delegate", Collections.emptyList(), Types.STRING); - Delegate delegate2 = new Delegate(Types.STRING, Types.STRING, "delegate", Collections.emptyList(), Types.STRING); - assertEquals(delegate, delegate2); - } - - @Test - public void not_equals_object() { - Delegate delegate = new Delegate(Types.STRING, Types.STRING, "delegate", Collections.emptyList(), Types.STRING); - Delegate delegate2 = new Delegate(Types.STRING, Types.STRING, "delegate2", Collections.emptyList(), Types.STRING); - assertFalse(delegate.equals(delegate2)); - } - + @Test + public void equals_object() { + Delegate delegate = + new Delegate( + Types.STRING, + Types.STRING, + "delegate", + Collections.emptyList(), + Types.STRING); + Delegate delegate2 = + new Delegate( + Types.STRING, + Types.STRING, + "delegate", + Collections.emptyList(), + Types.STRING); + assertEquals(delegate, delegate2); + } + + @Test + public void not_equals_object() { + Delegate delegate = + new Delegate( + Types.STRING, + Types.STRING, + "delegate", + Collections.emptyList(), + Types.STRING); + Delegate delegate2 = + new Delegate( + Types.STRING, + Types.STRING, + "delegate2", + Collections.emptyList(), + Types.STRING); + assertFalse(delegate.equals(delegate2)); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddableSerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddableSerializerTest.java index bae7f3edef..5d5dca5943 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddableSerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddableSerializerTest.java @@ -17,6 +17,9 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.JavaWriter; +import com.querydsl.codegen.utils.model.*; +import com.querydsl.core.annotations.PropertyType; import java.io.IOException; import java.io.StringWriter; import java.sql.Time; @@ -24,181 +27,215 @@ import java.util.Date; import java.util.EnumMap; import java.util.Map; - import org.junit.Test; -import com.querydsl.codegen.utils.JavaWriter; -import com.querydsl.codegen.utils.model.*; -import com.querydsl.core.annotations.PropertyType; - public class EmbeddableSerializerTest { - private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); - - private final TypeMappings typeMappings = new JavaTypeMappings(); - - private final EntitySerializer serializer = new DefaultEmbeddableSerializer(typeMappings, Collections.emptySet()); - - private final StringWriter writer = new StringWriter(); - - @Test - public void properties() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); - entityType.addProperty(new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); - //entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); - entityType.addProperty(new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); - entityType.addProperty(new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); - entityType.addProperty(new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); - entityType.addProperty(new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void originalCategory() throws IOException { - Map categoryToSuperClass - = new EnumMap(TypeCategory.class); - categoryToSuperClass.put(TypeCategory.COMPARABLE, "ComparablePath"); - categoryToSuperClass.put(TypeCategory.ENUM, "EnumPath"); - categoryToSuperClass.put(TypeCategory.DATE, "DatePath"); - categoryToSuperClass.put(TypeCategory.DATETIME, "DateTimePath"); - categoryToSuperClass.put(TypeCategory.TIME, "TimePath"); - categoryToSuperClass.put(TypeCategory.NUMERIC, "NumberPath"); - categoryToSuperClass.put(TypeCategory.STRING, "StringPath"); - categoryToSuperClass.put(TypeCategory.BOOLEAN, "BooleanPath"); - - for (Map.Entry entry : categoryToSuperClass.entrySet()) { - StringWriter w = new StringWriter(); - SimpleType type = new SimpleType(entry.getKey(), "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(w)); - assertTrue(entry.getValue() + " is missing from " + w, w.toString().contains("public class QEntity extends " + entry.getValue() + " {")); - } - - } - - @Test - public void empty() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void no_package() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class QEntity extends BeanPath {")); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void correct_superclass() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "java.util.Locale", "java.util", "Locale",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class QLocale extends BeanPath {")); - CompileUtils.assertCompiles("QLocale", writer.toString()); - } - - @Test - public void primitive_array() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "bytes", new ClassType(byte[].class))); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - - assertTrue(writer.toString().contains("public final SimplePath bytes")); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void include() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); - entityType.addProperty(new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); - //entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); - entityType.addProperty(new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); - entityType.addProperty(new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); - entityType.addProperty(new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); - entityType.addProperty(new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); - - EntityType subType = new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2",false,false)); - subType.include(new Supertype(type,entityType)); - - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - typeMappings.register(subType, queryTypeFactory.create(subType)); - - serializer.serialize(subType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - CompileUtils.assertCompiles("QEntity2", writer.toString()); - } - - @Test - public void superType() throws IOException { - EntityType superType = new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2",false,false)); - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type, Collections.singleton(new Supertype(superType, superType))); - typeMappings.register(superType, queryTypeFactory.create(superType)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public final QEntity2 _super = new QEntity2(this);")); - //CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void delegates() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - Delegate delegate = new Delegate(type, type, "test", Collections.emptyList(), Types.STRING); - entityType.addDelegate(delegate); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("return Entity.test(this);")); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void defaultGeneratedAnnotation() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - final String generatedSource = writer.toString(); - assertThat(generatedSource, containsString(String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); - assertThat(generatedSource, containsString("@Generated(\"com.querydsl.codegen.DefaultEmbeddableSerializer\")\npublic class")); - CompileUtils.assertCompiles("QEntity", generatedSource); - } - - @Test - public void customGeneratedAnnotation() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - new DefaultEmbeddableSerializer(typeMappings, Collections.emptySet(), com.querydsl.core.annotations.Generated.class).serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSourceCode = writer.toString(); - assertThat(generatedSourceCode, containsString("@Generated(\"com.querydsl.codegen.DefaultEmbeddableSerializer\")\npublic class")); - CompileUtils.assertCompiles("QEntity", generatedSourceCode); + private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); + + private final TypeMappings typeMappings = new JavaTypeMappings(); + + private final EntitySerializer serializer = + new DefaultEmbeddableSerializer(typeMappings, Collections.emptySet()); + + private final StringWriter writer = new StringWriter(); + + @Test + public void properties() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty( + new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); + entityType.addProperty( + new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); + // entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, + // PropertyType.class))); + entityType.addProperty( + new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); + entityType.addProperty( + new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); + entityType.addProperty( + new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); + entityType.addProperty( + new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); + entityType.addProperty( + new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); + entityType.addProperty( + new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void originalCategory() throws IOException { + Map categoryToSuperClass = + new EnumMap(TypeCategory.class); + categoryToSuperClass.put(TypeCategory.COMPARABLE, "ComparablePath"); + categoryToSuperClass.put(TypeCategory.ENUM, "EnumPath"); + categoryToSuperClass.put(TypeCategory.DATE, "DatePath"); + categoryToSuperClass.put(TypeCategory.DATETIME, "DateTimePath"); + categoryToSuperClass.put(TypeCategory.TIME, "TimePath"); + categoryToSuperClass.put(TypeCategory.NUMERIC, "NumberPath"); + categoryToSuperClass.put(TypeCategory.STRING, "StringPath"); + categoryToSuperClass.put(TypeCategory.BOOLEAN, "BooleanPath"); + + for (Map.Entry entry : categoryToSuperClass.entrySet()) { + StringWriter w = new StringWriter(); + SimpleType type = new SimpleType(entry.getKey(), "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(w)); + assertTrue( + entry.getValue() + " is missing from " + w, + w.toString().contains("public class QEntity extends " + entry.getValue() + " {")); } + } + + @Test + public void empty() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void no_package() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class QEntity extends BeanPath {")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void correct_superclass() throws IOException { + SimpleType type = + new SimpleType( + TypeCategory.ENTITY, "java.util.Locale", "java.util", "Locale", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class QLocale extends BeanPath {")); + CompileUtils.assertCompiles("QLocale", writer.toString()); + } + + @Test + public void primitive_array() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty(new Property(entityType, "bytes", new ClassType(byte[].class))); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + + assertTrue(writer.toString().contains("public final SimplePath bytes")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void include() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty( + new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); + entityType.addProperty( + new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); + // entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, + // PropertyType.class))); + entityType.addProperty( + new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); + entityType.addProperty( + new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); + entityType.addProperty( + new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); + entityType.addProperty( + new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); + entityType.addProperty( + new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); + entityType.addProperty( + new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); + + EntityType subType = + new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2", false, false)); + subType.include(new Supertype(type, entityType)); + + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + typeMappings.register(subType, queryTypeFactory.create(subType)); + + serializer.serialize(subType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + CompileUtils.assertCompiles("QEntity2", writer.toString()); + } + + @Test + public void superType() throws IOException { + EntityType superType = + new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2", false, false)); + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = + new EntityType(type, Collections.singleton(new Supertype(superType, superType))); + typeMappings.register(superType, queryTypeFactory.create(superType)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public final QEntity2 _super = new QEntity2(this);")); + // CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void delegates() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + Delegate delegate = + new Delegate(type, type, "test", Collections.emptyList(), Types.STRING); + entityType.addDelegate(delegate); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("return Entity.test(this);")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void defaultGeneratedAnnotation() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + final String generatedSource = writer.toString(); + assertThat( + generatedSource, + containsString( + String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); + assertThat( + generatedSource, + containsString( + "@Generated(\"com.querydsl.codegen.DefaultEmbeddableSerializer\")\npublic class")); + CompileUtils.assertCompiles("QEntity", generatedSource); + } + + @Test + public void customGeneratedAnnotation() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + new DefaultEmbeddableSerializer( + typeMappings, + Collections.emptySet(), + com.querydsl.core.annotations.Generated.class) + .serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSourceCode = writer.toString(); + assertThat( + generatedSourceCode, + containsString( + "@Generated(\"com.querydsl.codegen.DefaultEmbeddableSerializer\")\npublic class")); + CompileUtils.assertCompiles("QEntity", generatedSourceCode); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Embedded2Test.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Embedded2Test.java index c9d7de9ff2..f4ef28403d 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Embedded2Test.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Embedded2Test.java @@ -13,61 +13,49 @@ */ package com.querydsl.codegen; -import java.io.Serializable; - import com.querydsl.core.annotations.QueryEmbeddable; import com.querydsl.core.annotations.QueryEmbedded; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QuerySupertype; +import java.io.Serializable; public class Embedded2Test extends AbstractExporterTest { - @QuerySupertype - public static class EntityCode { - - public String code; - - } - - @QuerySupertype - public abstract static class AbstractEntity { - - @QueryEmbedded - public C code; - - } - - @QuerySupertype - public static class AbstractMultilingualEntity extends AbstractEntity { - - } - - @QuerySupertype - public abstract static class AbstractNamedEntity extends AbstractMultilingualEntity { - - public String nameEn; + @QuerySupertype + public static class EntityCode { - public String nameNl; + public String code; + } - } + @QuerySupertype + public abstract static class AbstractEntity { - @QueryEntity - public static class Brand extends AbstractNamedEntity { + @QueryEmbedded public C code; + } - public Long id; + @QuerySupertype + public static class AbstractMultilingualEntity extends AbstractEntity {} - } + @QuerySupertype + public abstract static class AbstractNamedEntity + extends AbstractMultilingualEntity { - public interface Entity extends Serializable { + public String nameEn; - boolean sameIdentityAs(T other); + public String nameNl; + } - } + @QueryEntity + public static class Brand extends AbstractNamedEntity { - @QueryEmbeddable - public static class BrandCode extends EntityCode { + public Long id; + } - } + public interface Entity extends Serializable { + boolean sameIdentityAs(T other); + } + @QueryEmbeddable + public static class BrandCode extends EntityCode {} } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddedTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddedTest.java index 5d502351da..5335da0086 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddedTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/EmbeddedTest.java @@ -7,30 +7,24 @@ public class EmbeddedTest extends AbstractExporterTest { - @QueryEntity - public static class EntityClass extends AbstractEntity { + @QueryEntity + public static class EntityClass extends AbstractEntity {} - } + @QuerySupertype + public abstract static class AbstractEntity { - @QuerySupertype - public abstract static class AbstractEntity { + @QueryEmbedded public C code; + } - @QueryEmbedded - public C code; - } + @QuerySupertype + public static class EntityCode { - @QuerySupertype - public static class EntityCode { + public String code; + } - public String code; + @QueryEmbeddable + public static class SubEntityCode extends EntityCode { - } - - @QueryEmbeddable - public static class SubEntityCode extends EntityCode { - - public String property; - - } - -} \ No newline at end of file + public String property; + } +} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityInheritanceTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityInheritanceTest.java index efdac87af0..47d5f08feb 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityInheritanceTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityInheritanceTest.java @@ -5,20 +5,17 @@ public class EntityInheritanceTest extends AbstractExporterTest { - @QuerySupertype - public static class TreeEntity> { + @QuerySupertype + public static class TreeEntity> { - public Integer id; + public Integer id; - public T parent; + public T parent; + } - } - - @QueryEntity - public static class TestEntity extends TreeEntity { - - public String name; - - } + @QueryEntity + public static class TestEntity extends TreeEntity { + public String name; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntitySerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntitySerializerTest.java index eb1801aadb..0c06c9a83a 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntitySerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntitySerializerTest.java @@ -15,6 +15,9 @@ import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.JavaWriter; +import com.querydsl.codegen.utils.model.*; +import com.querydsl.core.annotations.PropertyType; import java.io.IOException; import java.io.StringWriter; import java.sql.Time; @@ -22,196 +25,235 @@ import java.util.Date; import java.util.EnumMap; import java.util.Map; - import org.junit.Test; -import com.querydsl.codegen.utils.JavaWriter; -import com.querydsl.codegen.utils.model.*; -import com.querydsl.core.annotations.PropertyType; - public class EntitySerializerTest { - private QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); - - private final TypeMappings typeMappings = new JavaTypeMappings(); - - private final EntitySerializer serializer = new DefaultEntitySerializer(typeMappings, Collections.emptySet()); - - private final StringWriter writer = new StringWriter(); - - public static class Entity { - - } - - @Test - public void javadocs_for_innerClass() throws IOException { - EntityType entityType = new EntityType(new ClassType(Entity.class)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("QEntitySerializerTest_Entity is a Querydsl query type for Entity")); - CompileUtils.assertCompiles("QEntitySerializerTest_Entity", writer.toString()); - } - - @Test - public void different_package() throws IOException { - queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ".gen"); - - EntityType entityType = new EntityType(new ClassType(Entity.class)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class QEntitySerializerTest_Entity " + - "extends EntityPathBase")); - CompileUtils.assertCompiles("QEntitySerializerTest_Entity", writer.toString()); - } - - @Test - public void no_package() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class QEntity extends EntityPathBase {")); - CompileUtils.assertCompiles("QEntity", writer.toString()); + private QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ""); + + private final TypeMappings typeMappings = new JavaTypeMappings(); + + private final EntitySerializer serializer = + new DefaultEntitySerializer(typeMappings, Collections.emptySet()); + + private final StringWriter writer = new StringWriter(); + + public static class Entity {} + + @Test + public void javadocs_for_innerClass() throws IOException { + EntityType entityType = new EntityType(new ClassType(Entity.class)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue( + writer + .toString() + .contains("QEntitySerializerTest_Entity is a Querydsl query type for Entity")); + CompileUtils.assertCompiles("QEntitySerializerTest_Entity", writer.toString()); + } + + @Test + public void different_package() throws IOException { + queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ".gen"); + + EntityType entityType = new EntityType(new ClassType(Entity.class)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue( + writer + .toString() + .contains( + "public class QEntitySerializerTest_Entity " + + "extends EntityPathBase")); + CompileUtils.assertCompiles("QEntitySerializerTest_Entity", writer.toString()); + } + + @Test + public void no_package() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class QEntity extends EntityPathBase {")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void original_category() throws IOException { + Map categoryToSuperClass = + new EnumMap(TypeCategory.class); + categoryToSuperClass.put(TypeCategory.COMPARABLE, "ComparablePath"); + categoryToSuperClass.put(TypeCategory.ENUM, "EnumPath"); + categoryToSuperClass.put(TypeCategory.DATE, "DatePath"); + categoryToSuperClass.put(TypeCategory.DATETIME, "DateTimePath"); + categoryToSuperClass.put(TypeCategory.TIME, "TimePath"); + categoryToSuperClass.put(TypeCategory.NUMERIC, "NumberPath"); + categoryToSuperClass.put(TypeCategory.STRING, "StringPath"); + categoryToSuperClass.put(TypeCategory.BOOLEAN, "BooleanPath"); + + for (Map.Entry entry : categoryToSuperClass.entrySet()) { + SimpleType type = new SimpleType(entry.getKey(), "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue( + entry.toString(), + writer.toString().contains("public class QEntity extends " + entry.getValue() + " {")); } - - @Test - public void original_category() throws IOException { - Map categoryToSuperClass - = new EnumMap(TypeCategory.class); - categoryToSuperClass.put(TypeCategory.COMPARABLE, "ComparablePath"); - categoryToSuperClass.put(TypeCategory.ENUM, "EnumPath"); - categoryToSuperClass.put(TypeCategory.DATE, "DatePath"); - categoryToSuperClass.put(TypeCategory.DATETIME, "DateTimePath"); - categoryToSuperClass.put(TypeCategory.TIME, "TimePath"); - categoryToSuperClass.put(TypeCategory.NUMERIC, "NumberPath"); - categoryToSuperClass.put(TypeCategory.STRING, "StringPath"); - categoryToSuperClass.put(TypeCategory.BOOLEAN, "BooleanPath"); - - for (Map.Entry entry : categoryToSuperClass.entrySet()) { - SimpleType type = new SimpleType(entry.getKey(), "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(entry.toString(), writer.toString().contains("public class QEntity extends " + entry.getValue() + " {")); - } - - } - - @Test - public void correct_superclass() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "java.util.Locale", "java.util", "Locale",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public class QLocale extends EntityPathBase {")); - CompileUtils.assertCompiles("QLocale", writer.toString()); - } - - @Test - public void primitive_array() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "bytes", new ClassType(byte[].class))); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public final SimplePath bytes")); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void include() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); - entityType.addProperty(new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); - //entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); - entityType.addProperty(new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); - entityType.addProperty(new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); - entityType.addProperty(new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); - entityType.addProperty(new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); - - EntityType subType = new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2",false,false)); - subType.include(new Supertype(type, entityType)); - typeMappings.register(subType, queryTypeFactory.create(subType)); - - serializer.serialize(subType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - CompileUtils.assertCompiles("QEntity2", writer.toString()); - } - - @Test - public void properties() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - entityType.addProperty(new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); - entityType.addProperty(new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); - //entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); - entityType.addProperty(new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); - entityType.addProperty(new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); - entityType.addProperty(new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); - entityType.addProperty(new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); - entityType.addProperty(new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void superType() throws IOException { - EntityType superType = new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2",false,false)); - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type, Collections.singleton(new Supertype(superType, superType))); - typeMappings.register(superType, queryTypeFactory.create(superType)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("public final QEntity2 _super = new QEntity2(this);")); - //CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void delegates() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity",false,false); - EntityType entityType = new EntityType(type); - Delegate delegate = new Delegate(type, type, "test", Collections.emptyList(), Types.STRING); - entityType.addDelegate(delegate); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("return Entity.test(this);")); - CompileUtils.assertCompiles("QEntity", writer.toString()); - } - - @Test - public void defaultGeneratedAnnotation() throws IOException { - EntityType entityType = new EntityType(new ClassType(Entity.class)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSourceCode = writer.toString(); - assertTrue(generatedSourceCode.contains(String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); - assertTrue(generatedSourceCode.contains("@Generated(\"com.querydsl.codegen.DefaultEntitySerializer\")\npublic class")); - CompileUtils.assertCompiles("QEntitySerializerTest_Entity", generatedSourceCode); - } - - @Test - public void customGeneratedAnnotation() throws IOException { - EntityType entityType = new EntityType(new ClassType(Entity.class)); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); - - new DefaultEntitySerializer(typeMappings, Collections.emptySet(), com.querydsl.core.annotations.Generated.class).serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSourceCode = writer.toString(); - assertTrue(generatedSourceCode.contains("import " + com.querydsl.core.annotations.Generated.class.getName() + ";")); - assertTrue(generatedSourceCode.contains("@" + com.querydsl.core.annotations.Generated.class.getSimpleName() + "(\"com.querydsl.codegen.DefaultEntitySerializer\")\npublic class")); - CompileUtils.assertCompiles("QEntitySerializerTest_Entity", generatedSourceCode); - } - + } + + @Test + public void correct_superclass() throws IOException { + SimpleType type = + new SimpleType( + TypeCategory.ENTITY, "java.util.Locale", "java.util", "Locale", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public class QLocale extends EntityPathBase {")); + CompileUtils.assertCompiles("QLocale", writer.toString()); + } + + @Test + public void primitive_array() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty(new Property(entityType, "bytes", new ClassType(byte[].class))); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public final SimplePath bytes")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void include() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty( + new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); + entityType.addProperty( + new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); + // entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, + // PropertyType.class))); + entityType.addProperty( + new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); + entityType.addProperty( + new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); + entityType.addProperty( + new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); + entityType.addProperty( + new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); + entityType.addProperty( + new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); + entityType.addProperty( + new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); + + EntityType subType = + new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2", false, false)); + subType.include(new Supertype(type, entityType)); + typeMappings.register(subType, queryTypeFactory.create(subType)); + + serializer.serialize(subType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + CompileUtils.assertCompiles("QEntity2", writer.toString()); + } + + @Test + public void properties() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + entityType.addProperty( + new Property(entityType, "b", new ClassType(TypeCategory.BOOLEAN, Boolean.class))); + entityType.addProperty( + new Property(entityType, "c", new ClassType(TypeCategory.COMPARABLE, String.class))); + // entityType.addProperty(new Property(entityType, "cu", new ClassType(TypeCategory.CUSTOM, + // PropertyType.class))); + entityType.addProperty( + new Property(entityType, "d", new ClassType(TypeCategory.DATE, Date.class))); + entityType.addProperty( + new Property(entityType, "e", new ClassType(TypeCategory.ENUM, PropertyType.class))); + entityType.addProperty( + new Property(entityType, "dt", new ClassType(TypeCategory.DATETIME, Date.class))); + entityType.addProperty( + new Property(entityType, "i", new ClassType(TypeCategory.NUMERIC, Integer.class))); + entityType.addProperty( + new Property(entityType, "s", new ClassType(TypeCategory.STRING, String.class))); + entityType.addProperty( + new Property(entityType, "t", new ClassType(TypeCategory.TIME, Time.class))); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void superType() throws IOException { + EntityType superType = + new EntityType(new SimpleType(TypeCategory.ENTITY, "Entity2", "", "Entity2", false, false)); + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = + new EntityType(type, Collections.singleton(new Supertype(superType, superType))); + typeMappings.register(superType, queryTypeFactory.create(superType)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("public final QEntity2 _super = new QEntity2(this);")); + // CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void delegates() throws IOException { + SimpleType type = new SimpleType(TypeCategory.ENTITY, "Entity", "", "Entity", false, false); + EntityType entityType = new EntityType(type); + Delegate delegate = + new Delegate(type, type, "test", Collections.emptyList(), Types.STRING); + entityType.addDelegate(delegate); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("return Entity.test(this);")); + CompileUtils.assertCompiles("QEntity", writer.toString()); + } + + @Test + public void defaultGeneratedAnnotation() throws IOException { + EntityType entityType = new EntityType(new ClassType(Entity.class)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSourceCode = writer.toString(); + assertTrue( + generatedSourceCode.contains( + String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); + assertTrue( + generatedSourceCode.contains( + "@Generated(\"com.querydsl.codegen.DefaultEntitySerializer\")\npublic class")); + CompileUtils.assertCompiles("QEntitySerializerTest_Entity", generatedSourceCode); + } + + @Test + public void customGeneratedAnnotation() throws IOException { + EntityType entityType = new EntityType(new ClassType(Entity.class)); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + + new DefaultEntitySerializer( + typeMappings, + Collections.emptySet(), + com.querydsl.core.annotations.Generated.class) + .serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSourceCode = writer.toString(); + assertTrue( + generatedSourceCode.contains( + "import " + com.querydsl.core.annotations.Generated.class.getName() + ";")); + assertTrue( + generatedSourceCode.contains( + "@" + + com.querydsl.core.annotations.Generated.class.getSimpleName() + + "(\"com.querydsl.codegen.DefaultEntitySerializer\")\npublic class")); + CompileUtils.assertCompiles("QEntitySerializerTest_Entity", generatedSourceCode); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityTypeTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityTypeTest.java index ed5de491b8..302cf8c428 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityTypeTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/EntityTypeTest.java @@ -15,41 +15,39 @@ import static org.junit.Assert.assertEquals; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.TypeCategory; +import java.util.Collections; +import org.junit.Test; public class EntityTypeTest { - @Test - public void uncapSimpleName_escaped() { - ClassType typeModel = new ClassType(TypeCategory.ENTITY, Object.class); - EntityType entityModel = new EntityType(typeModel); - assertEquals("object", entityModel.getModifiedSimpleName()); - - entityModel.addProperty(new Property(entityModel, "object", typeModel)); - assertEquals("object1", entityModel.getModifiedSimpleName()); - } - - @Test - public void uncapSimpleName_escaped2() { - ClassType typeModel = new ClassType(TypeCategory.ENTITY, Object.class); - EntityType entityModel = new EntityType(typeModel); - assertEquals("object", entityModel.getModifiedSimpleName()); - - entityModel.addProperty(new Property(entityModel, "OBJECT", "object", typeModel, - Collections. emptyList(), false)); - assertEquals("object1", entityModel.getModifiedSimpleName()); - } - - @Test - public void uncapSimpleName_escaped3() { - ClassType typeModel = new ClassType(TypeCategory.ENTITY, Void.class); - EntityType entityModel = new EntityType(typeModel); - assertEquals("void$", entityModel.getModifiedSimpleName()); - } - + @Test + public void uncapSimpleName_escaped() { + ClassType typeModel = new ClassType(TypeCategory.ENTITY, Object.class); + EntityType entityModel = new EntityType(typeModel); + assertEquals("object", entityModel.getModifiedSimpleName()); + + entityModel.addProperty(new Property(entityModel, "object", typeModel)); + assertEquals("object1", entityModel.getModifiedSimpleName()); + } + + @Test + public void uncapSimpleName_escaped2() { + ClassType typeModel = new ClassType(TypeCategory.ENTITY, Object.class); + EntityType entityModel = new EntityType(typeModel); + assertEquals("object", entityModel.getModifiedSimpleName()); + + entityModel.addProperty( + new Property( + entityModel, "OBJECT", "object", typeModel, Collections.emptyList(), false)); + assertEquals("object1", entityModel.getModifiedSimpleName()); + } + + @Test + public void uncapSimpleName_escaped3() { + ClassType typeModel = new ClassType(TypeCategory.ENTITY, Void.class); + EntityType entityModel = new EntityType(typeModel); + assertEquals("void$", entityModel.getModifiedSimpleName()); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbeddable.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbeddable.java index 5593515f9b..d3a2055237 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbeddable.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbeddable.java @@ -18,16 +18,13 @@ @QueryEmbeddable public class ExampleEmbeddable { - private String property; - - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } - + private String property; + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbedded.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbedded.java index c85b5a7618..d1ebae9644 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbedded.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEmbedded.java @@ -15,14 +15,13 @@ public class ExampleEmbedded { - private String property; + private String property; - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntity.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntity.java index cb4c983e3d..b87d0d9842 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntity.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntity.java @@ -13,76 +13,71 @@ */ package com.querydsl.codegen; -import java.util.List; -import java.util.Map; - import com.querydsl.core.annotations.QueryEmbedded; import com.querydsl.core.annotations.QueryEntity; +import java.util.List; +import java.util.Map; @QueryEntity public class ExampleEntity extends ExampleSupertype { - private String name; - - private ExampleEntity mate; - - private List mates; - - private Map matesByName; + private String name; - private ExampleEmbeddable embeddable; + private ExampleEntity mate; - @QueryEmbedded - private ExampleEmbedded embedded; + private List mates; - public String getName() { - return name; - } + private Map matesByName; - public void setName(String name) { - this.name = name; - } + private ExampleEmbeddable embeddable; - public ExampleEntity getMate() { - return mate; - } + @QueryEmbedded private ExampleEmbedded embedded; - public void setMate(ExampleEntity mate) { - this.mate = mate; - } + public String getName() { + return name; + } - public ExampleEmbeddable getEmbeddable() { - return embeddable; - } + public void setName(String name) { + this.name = name; + } - public void setEmbeddable(ExampleEmbeddable embeddable) { - this.embeddable = embeddable; - } + public ExampleEntity getMate() { + return mate; + } - public List getMates() { - return mates; - } + public void setMate(ExampleEntity mate) { + this.mate = mate; + } - public void setMates(List mates) { - this.mates = mates; - } + public ExampleEmbeddable getEmbeddable() { + return embeddable; + } - public Map getMatesByName() { - return matesByName; - } + public void setEmbeddable(ExampleEmbeddable embeddable) { + this.embeddable = embeddable; + } - public void setMatesByName(Map matesByName) { - this.matesByName = matesByName; - } + public List getMates() { + return mates; + } - public ExampleEmbedded getEmbedded() { - return embedded; - } + public void setMates(List mates) { + this.mates = mates; + } - public void setEmbedded(ExampleEmbedded embedded) { - this.embedded = embedded; - } + public Map getMatesByName() { + return matesByName; + } + public void setMatesByName(Map matesByName) { + this.matesByName = matesByName; + } + public ExampleEmbedded getEmbedded() { + return embedded; + } + public void setEmbedded(ExampleEmbedded embedded) { + this.embedded = embedded; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntityInterface.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntityInterface.java index 377b4cab5c..5cc6ca7986 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntityInterface.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleEntityInterface.java @@ -16,6 +16,4 @@ import com.querydsl.core.annotations.QueryEntity; @QueryEntity -public interface ExampleEntityInterface { - -} +public interface ExampleEntityInterface {} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleSupertype.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleSupertype.java index 665902421a..19c49e44f0 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleSupertype.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExampleSupertype.java @@ -18,13 +18,13 @@ @QuerySupertype public class ExampleSupertype { - private int id; + private int id; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Examples.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Examples.java index 2dde5cee96..74341d43c8 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Examples.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Examples.java @@ -1,115 +1,97 @@ package com.querydsl.codegen; -import java.util.*; - import com.querydsl.core.DefaultQueryMetadata; import com.querydsl.core.annotations.QueryEmbedded; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.types.OrderSpecifier; - +import java.util.*; public class Examples { - public static class Supertype { + public static class Supertype { - public String supertypeProperty; - } + public String supertypeProperty; + } - @QueryEntity - public static class SimpleEntity extends Supertype { + @QueryEntity + public static class SimpleEntity extends Supertype {} - } + @QueryEntity + public abstract static class AbstractEntity { - @QueryEntity - public abstract static class AbstractEntity { + public Id id; - public Id id; + public String first; + } - public String first; + @QueryEntity + public static class SubEntity extends AbstractEntity { - } - - @QueryEntity - public static class SubEntity extends AbstractEntity { - - public String second; - - } + public String second; + } + @QueryEntity + public static class ComplexCollections { - @QueryEntity - public static class ComplexCollections { + @QueryEmbedded public List> list; - @QueryEmbedded - public List> list; + @QueryEmbedded public Map> map; - @QueryEmbedded - public Map> map; + @QueryEmbedded public Map> map2; - @QueryEmbedded - public Map> map2; + @QueryEmbedded public Map> map3; + } - @QueryEmbedded - public Map> map3; + public static class Complex> implements Comparable> { + public T a; + @Override + public int compareTo(Complex arg0) { + return 0; } - - public static class Complex> implements Comparable> { - - public T a; - - @Override - public int compareTo(Complex arg0) { - return 0; - } - - public boolean equals(Object o) { - return o == this; - } + public boolean equals(Object o) { + return o == this; } + } - @QueryEntity - public static class Reference { - - } + @QueryEntity + public static class Reference {} - @QueryEntity - public static class GenericRelations { - public Collection> col1; - public Collection> col2; - public Collection> col3; - public Collection> col4; - - public Set> set1; - public Set> set2; - public Set> set3; - public Set> set4; - - public Map> map1; - public Map,String> map2; - public Map> map3; - public Map,String> map4; - } + @QueryEntity + public static class GenericRelations { + public Collection> col1; + public Collection> col2; + public Collection> col3; + public Collection> col4; - @QueryEntity - public static class Subtype extends DefaultQueryMetadata { + public Set> set1; + public Set> set2; + public Set> set3; + public Set> set4; - private static final long serialVersionUID = -218949941713252847L; + public Map> map1; + public Map, String> map2; + public Map> map3; + public Map, String> map4; + } - } + @QueryEntity + public static class Subtype extends DefaultQueryMetadata { - @QueryEntity - public static class OrderBys { + private static final long serialVersionUID = -218949941713252847L; + } - List> orderBy = new ArrayList>(); + @QueryEntity + public static class OrderBys { - } + List> orderBy = new ArrayList>(); + } - @QueryEntity - public static class SimpleTypes { + @QueryEntity + public static class SimpleTypes { - List> classList5; - } + List> classList5; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExternalEmbeddableTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExternalEmbeddableTest.java index d0c608e502..539c611417 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ExternalEmbeddableTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ExternalEmbeddableTest.java @@ -1,20 +1,16 @@ package com.querydsl.codegen; -import org.junit.Ignore; - import com.querydsl.core.annotations.QueryEmbedded; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.domain.EmbeddableWithoutQType; +import org.junit.Ignore; @Ignore public class ExternalEmbeddableTest { - @QueryEntity - public static class EntityWithExternalEmbeddable { - - @QueryEmbedded - EmbeddableWithoutQType embeddable; - - } + @QueryEntity + public static class EntityWithExternalEmbeddable { + @QueryEmbedded EmbeddableWithoutQType embeddable; + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/GeneratedAnnotationResolverTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/GeneratedAnnotationResolverTest.java index 849fbf4f65..64fcce7408 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/GeneratedAnnotationResolverTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/GeneratedAnnotationResolverTest.java @@ -1,32 +1,33 @@ package com.querydsl.codegen; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; -import javax.annotation.Generated; import java.lang.annotation.Annotation; - -import static org.junit.Assert.assertNotNull; +import javax.annotation.Generated; +import org.junit.Test; public class GeneratedAnnotationResolverTest { - private static final String defaultGenerated = Generated.class.getName(); - - @Test - public void resolveCustom() { - String customClass = "some.random.Class"; - Class resolvedAnnotationClass = GeneratedAnnotationResolver.resolve(customClass); - assertNotNull(resolvedAnnotationClass); - } - - @Test - public void resolveNull() { - Class resolvedAnnotationClass = GeneratedAnnotationResolver.resolve(null); - assertNotNull(resolvedAnnotationClass); - } - - @Test - public void resolveDefault() { - Class resolvedAnnotationClass = GeneratedAnnotationResolver.resolveDefault(); - assertNotNull(resolvedAnnotationClass); - } + private static final String defaultGenerated = Generated.class.getName(); + + @Test + public void resolveCustom() { + String customClass = "some.random.Class"; + Class resolvedAnnotationClass = + GeneratedAnnotationResolver.resolve(customClass); + assertNotNull(resolvedAnnotationClass); + } + + @Test + public void resolveNull() { + Class resolvedAnnotationClass = GeneratedAnnotationResolver.resolve(null); + assertNotNull(resolvedAnnotationClass); + } + + @Test + public void resolveDefault() { + Class resolvedAnnotationClass = + GeneratedAnnotationResolver.resolveDefault(); + assertNotNull(resolvedAnnotationClass); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Generic2Test.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Generic2Test.java index 0e0bfc38af..f3b7af7cb7 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Generic2Test.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Generic2Test.java @@ -2,62 +2,65 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.codegen.utils.model.Type; +import com.querydsl.core.annotations.QueryEntity; import java.io.File; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Collections; import java.util.List; - import org.junit.Test; -import com.querydsl.codegen.utils.model.Type; -import com.querydsl.core.annotations.QueryEntity; - public class Generic2Test { - @QueryEntity - public static class AbstractCollectionAttribute> { - - T value; - - } - - @QueryEntity - public static class ListAttribute extends AbstractCollectionAttribute> { - - String name; - - } - - @QueryEntity - public static class Product { - - ListAttribute integerAttributes; - ListAttribute stringAttributes; - - } - - @Test - public void resolve() { - TypeFactory factory = new TypeFactory(Collections.>emptyList()); - Type type = factory.get(AbstractCollectionAttribute.class); - assertEquals("com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute", type.getGenericName(false)); - assertEquals("com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute", type.getGenericName(true)); - } - - @Test - public void resolve2() { - TypeFactory factory = new TypeFactory(Collections.>emptyList()); - Type type = factory.getEntityType(AbstractCollectionAttribute.class); - assertEquals("com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute>", type.getGenericName(false)); - assertEquals("com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute>", type.getGenericName(true)); - } - - - @Test - public void export() { - GenericExporter exporter = new GenericExporter(); - exporter.setTargetFolder(new File("target/Generic2Test")); - exporter.export(Generic2Test.class.getClasses()); - } + @QueryEntity + public static class AbstractCollectionAttribute> { + + T value; + } + + @QueryEntity + public static class ListAttribute extends AbstractCollectionAttribute> { + + String name; + } + + @QueryEntity + public static class Product { + + ListAttribute integerAttributes; + ListAttribute stringAttributes; + } + + @Test + public void resolve() { + TypeFactory factory = new TypeFactory(Collections.>emptyList()); + Type type = factory.get(AbstractCollectionAttribute.class); + assertEquals( + "com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute", + type.getGenericName(false)); + assertEquals( + "com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute", type.getGenericName(true)); + } + + @Test + public void resolve2() { + TypeFactory factory = new TypeFactory(Collections.>emptyList()); + Type type = factory.getEntityType(AbstractCollectionAttribute.class); + assertEquals( + "com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute>", + type.getGenericName(false)); + assertEquals( + "com.querydsl.codegen.Generic2Test.AbstractCollectionAttribute>", + type.getGenericName(true)); + } + + @Test + public void export() { + GenericExporter exporter = new GenericExporter(); + exporter.setTargetFolder(new File("target/Generic2Test")); + exporter.export(Generic2Test.class.getClasses()); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericExporterTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericExporterTest.java index c886a0f52f..2b907d4bd9 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericExporterTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericExporterTest.java @@ -16,152 +16,170 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.querydsl.core.domain.Cat; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import com.querydsl.core.domain.Cat; - public class GenericExporterTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - - private GenericExporter exporter; - - @Before - public void setUp() { - exporter = new GenericExporter(); - } - - @Test - public void export() { - exporter.setTargetFolder(folder.getRoot()); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + @Rule public TemporaryFolder folder = new TemporaryFolder(); + + private GenericExporter exporter; + + @Before + public void setUp() { + exporter = new GenericExporter(); + } + + @Test + public void export() { + exporter.setTargetFolder(folder.getRoot()); + exporter.export(getClass().getPackage()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + } + + @Test + public void export_with_keywords() throws IOException { + exporter.setKeywords(Keywords.JPA); + exporter.setTargetFolder(folder.getRoot()); + exporter.export(getClass().getPackage()); + String str = + new String( + Files.readAllBytes( + new File(folder.getRoot(), "com/querydsl/codegen/QGroup.java").toPath()), + StandardCharsets.UTF_8); + assertTrue(str.contains("QGroup group = new QGroup(\"group1\");")); + } + + @Test + public void export_with_stopClass() { + exporter.setTargetFolder(folder.getRoot()); + exporter.addStopClass(Examples.Supertype.class); + exporter.export(getClass().getPackage()); + assertFalse( + new File(folder.getRoot(), "com/querydsl/codegen/QExamples_Supertype.java").exists()); + } + + @Test + public void override_serializer() { + exporter.setTargetFolder(folder.getRoot()); + exporter.setSerializerClass(DefaultEntitySerializer.class); + exporter.export(getClass().getPackage()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + } + + @Test + public void export_package_as_string() { + exporter.setTargetFolder(folder.getRoot()); + exporter.export(getClass().getPackage().getName()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + } + + @Test + public void export_with_package_suffix() { + exporter.setTargetFolder(folder.getRoot()); + exporter.setPackageSuffix("types"); + exporter.export(getClass().getPackage()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEmbeddable.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEmbedded.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEntityInterface.java") + .exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/subtypes/QExampleEntity2.java").exists()); + } + + @Test + public void export_handle_no_methods_nor_fields() { + exporter.setTargetFolder(folder.getRoot()); + exporter.setHandleFields(false); + exporter.setHandleMethods(false); + exporter.export(getClass().getPackage()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + } + + @Test + public void export_domain_package() { + exporter.setTargetFolder(folder.getRoot()); + exporter.export(Cat.class.getPackage()); + } + + @Test + public void export_serializerConfig() { + exporter.setTargetFolder(folder.getRoot()); + exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); + exporter.export(getClass().getPackage()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + } + + @Test + public void export_useFieldTypes() { + exporter.setTargetFolder(folder.getRoot()); + exporter.setUseFieldTypes(true); + exporter.export(getClass().getPackage()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue( + new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); + } + + @Test + public void export_propertyHandling() throws IOException { + for (PropertyHandling ph : PropertyHandling.values()) { + File f = folder.newFolder(); + GenericExporter e = new GenericExporter(); + e.setTargetFolder(f); + e.setPropertyHandling(ph); + e.export(getClass().getPackage()); + assertTrue(new File(f, "com/querydsl/codegen/QExampleEmbeddable.java").exists()); + assertTrue(new File(f, "com/querydsl/codegen/QExampleEntity.java").exists()); + assertTrue(new File(f, "com/querydsl/codegen/QExampleEntityInterface.java").exists()); + assertTrue(new File(f, "com/querydsl/codegen/QExampleSupertype.java").exists()); + assertTrue(new File(f, "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); } - - @Test - public void export_with_keywords() throws IOException { - exporter.setKeywords(Keywords.JPA); - exporter.setTargetFolder(folder.getRoot()); - exporter.export(getClass().getPackage()); - String str = new String(Files.readAllBytes(new File(folder.getRoot(), "com/querydsl/codegen/QGroup.java").toPath()), StandardCharsets.UTF_8); - assertTrue(str.contains("QGroup group = new QGroup(\"group1\");")); - } - - @Test - public void export_with_stopClass() { - exporter.setTargetFolder(folder.getRoot()); - exporter.addStopClass(Examples.Supertype.class); - exporter.export(getClass().getPackage()); - assertFalse(new File(folder.getRoot(), "com/querydsl/codegen/QExamples_Supertype.java").exists()); - } - - @Test - public void override_serializer() { - exporter.setTargetFolder(folder.getRoot()); - exporter.setSerializerClass(DefaultEntitySerializer.class); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); - } - - @Test - public void export_package_as_string() { - exporter.setTargetFolder(folder.getRoot()); - exporter.export(getClass().getPackage().getName()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); - } - - @Test - public void export_with_package_suffix() { - exporter.setTargetFolder(folder.getRoot()); - exporter.setPackageSuffix("types"); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegentypes/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/subtypes/QExampleEntity2.java").exists()); - } - - @Test - public void export_handle_no_methods_nor_fields() { - exporter.setTargetFolder(folder.getRoot()); - exporter.setHandleFields(false); - exporter.setHandleMethods(false); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - } - - @Test - public void export_domain_package() { - exporter.setTargetFolder(folder.getRoot()); - exporter.export(Cat.class.getPackage()); - } - - @Test - public void export_serializerConfig() { - exporter.setTargetFolder(folder.getRoot()); - exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); - } - - @Test - public void export_useFieldTypes() { - exporter.setTargetFolder(folder.getRoot()); - exporter.setUseFieldTypes(true); - exporter.export(getClass().getPackage()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEmbedded.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(folder.getRoot(), "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); - } - - @Test - public void export_propertyHandling() throws IOException { - for (PropertyHandling ph : PropertyHandling.values()) { - File f = folder.newFolder(); - GenericExporter e = new GenericExporter(); - e.setTargetFolder(f); - e.setPropertyHandling(ph); - e.export(getClass().getPackage()); - assertTrue(new File(f, "com/querydsl/codegen/QExampleEmbeddable.java").exists()); - assertTrue(new File(f, "com/querydsl/codegen/QExampleEntity.java").exists()); - assertTrue(new File(f, "com/querydsl/codegen/QExampleEntityInterface.java").exists()); - assertTrue(new File(f, "com/querydsl/codegen/QExampleSupertype.java").exists()); - assertTrue(new File(f, "com/querydsl/codegen/sub/QExampleEntity2.java").exists()); - } - } - + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericTest.java index 6391c25ead..f97ff8f11d 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/GenericTest.java @@ -1,36 +1,29 @@ package com.querydsl.codegen; -import org.junit.Test; - import com.querydsl.codegen.utils.model.Type; - +import org.junit.Test; public class GenericTest { - public abstract static class CapiBCKeyedByGrundstueck { - - } - - public abstract static class HidaBez, G extends HidaBezGruppe> extends CapiBCKeyedByGrundstueck { - - } + public abstract static class CapiBCKeyedByGrundstueck {} - public abstract static class HidaBezGruppe, B extends HidaBez> extends - CapiBCKeyedByGrundstueck { - } + public abstract static class HidaBez, G extends HidaBezGruppe> + extends CapiBCKeyedByGrundstueck {} - private TypeFactory typeFactory = new TypeFactory(); + public abstract static class HidaBezGruppe, B extends HidaBez> + extends CapiBCKeyedByGrundstueck {} - @Test - public void hidaBez() { - Type type = typeFactory.getEntityType(HidaBez.class); - //System.out.println(type.getGenericName(true)); - } + private TypeFactory typeFactory = new TypeFactory(); - @Test - public void hidaBezGruppe() { - Type type = typeFactory.getEntityType(HidaBezGruppe.class); - //System.out.println(type.getGenericName(true)); - } + @Test + public void hidaBez() { + Type type = typeFactory.getEntityType(HidaBez.class); + // System.out.println(type.getGenericName(true)); + } + @Test + public void hidaBezGruppe() { + Type type = typeFactory.getEntityType(HidaBezGruppe.class); + // System.out.println(type.getGenericName(true)); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/GroovyBeanSerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/GroovyBeanSerializerTest.java index 7b3e14fb96..71781690a4 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/GroovyBeanSerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/GroovyBeanSerializerTest.java @@ -15,67 +15,80 @@ import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.JavaWriter; +import com.querydsl.codegen.utils.StringUtils; +import com.querydsl.codegen.utils.model.*; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Arrays; import java.util.Date; - import org.junit.Before; import org.junit.Test; -import com.querydsl.codegen.utils.JavaWriter; -import com.querydsl.codegen.utils.StringUtils; -import com.querydsl.codegen.utils.model.*; - public class GroovyBeanSerializerTest { - private Type typeModel; + private Type typeModel; - private EntityType type; + private EntityType type; - private final Writer writer = new StringWriter(); + private final Writer writer = new StringWriter(); - @Before - public void setUp() { - typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - type = new EntityType(typeModel); - } + @Before + public void setUp() { + typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + type = new EntityType(typeModel); + } - @Test - public void properties() throws IOException { - // property - type.addProperty(new Property(type, "entityField", type)); - type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); - type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); - type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); - type.addProperty(new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); - type.addProperty(new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); + @Test + public void properties() throws IOException { + // property + type.addProperty(new Property(type, "entityField", type)); + type.addProperty(new Property(type, "collection", new SimpleType(Types.COLLECTION, typeModel))); + type.addProperty(new Property(type, "listField", new SimpleType(Types.LIST, typeModel))); + type.addProperty(new Property(type, "setField", new SimpleType(Types.SET, typeModel))); + type.addProperty( + new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class))); + type.addProperty( + new Property(type, "mapField", new SimpleType(Types.MAP, typeModel, typeModel))); - for (Class cl : Arrays.>asList(Boolean.class, Comparable.class, Integer.class, - Date.class, java.sql.Date.class, java.sql.Time.class)) { - Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); - type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); - } - - GroovyBeanSerializer serializer = new GroovyBeanSerializer(); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String str = writer.toString(); - //System.err.println(str); - for (String prop : Arrays.asList( - "String[] arrayField;", - "Boolean boolean$;", - "Collection collection;", - "Comparable comparable;", - "java.util.Date date;", - "DomainClass entityField;", - "Integer integer;", - "List listField;", - "Map mapField;", - "Set setField;", - "java.sql.Time time;")) { - assertTrue(prop + " was not contained", str.contains(prop)); - } + for (Class cl : + Arrays.>asList( + Boolean.class, + Comparable.class, + Integer.class, + Date.class, + java.sql.Date.class, + java.sql.Time.class)) { + Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); + type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); } + GroovyBeanSerializer serializer = new GroovyBeanSerializer(); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String str = writer.toString(); + // System.err.println(str); + for (String prop : + Arrays.asList( + "String[] arrayField;", + "Boolean boolean$;", + "Collection collection;", + "Comparable comparable;", + "java.util.Date date;", + "DomainClass entityField;", + "Integer integer;", + "List listField;", + "Map mapField;", + "Set setField;", + "java.sql.Time time;")) { + assertTrue(prop + " was not contained", str.contains(prop)); + } + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Group.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Group.java index f654be2b02..234dfe123a 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Group.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Group.java @@ -3,6 +3,4 @@ import com.querydsl.core.annotations.QueryEntity; @QueryEntity -public class Group { - -} +public class Group {} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Inheritance2Test.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Inheritance2Test.java index dc6d24c7a3..45f10192a6 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Inheritance2Test.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Inheritance2Test.java @@ -3,71 +3,59 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import java.io.File; -import java.lang.reflect.Field; - -import org.junit.Test; - import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeExtends; import com.querydsl.core.annotations.QueryEntity; +import java.io.File; +import java.lang.reflect.Field; +import org.junit.Test; public class Inheritance2Test { - @QueryEntity - public abstract class Base> { - @SuppressWarnings("unchecked") - Base2 base; - Base2 base2; - } - - @QueryEntity - public abstract class Base2,U extends IFace> { - - } - - @QueryEntity - public abstract class BaseSub extends Base { - - } - - @QueryEntity - public abstract class BaseSub2> extends Base { - - } - - @QueryEntity - public abstract class Base2Sub extends Base2,T> { - - } - - public interface IFace { - - } - - @Test - public void base_base() throws SecurityException, NoSuchFieldException { - TypeFactory typeFactory = new TypeFactory(); - Field field = Base.class.getDeclaredField("base"); - Type type = typeFactory.get(field.getType(), field.getGenericType()); - assertEquals(0, type.getParameters().size()); - } - - @Test - public void base_base2() throws SecurityException, NoSuchFieldException { - TypeFactory typeFactory = new TypeFactory(); - Field field = Base.class.getDeclaredField("base2"); - Type type = typeFactory.get(field.getType(), field.getGenericType()); - assertEquals(2, type.getParameters().size()); - assertNull(((TypeExtends) type.getParameters().get(0)).getVarName()); - assertNull(((TypeExtends) type.getParameters().get(1)).getVarName()); - } - - @Test - public void test() { - GenericExporter exporter = new GenericExporter(); - exporter.setTargetFolder(new File("target/" + getClass().getSimpleName())); - exporter.export(getClass().getClasses()); - } - -} \ No newline at end of file + @QueryEntity + public abstract class Base> { + @SuppressWarnings("unchecked") + Base2 base; + + Base2 base2; + } + + @QueryEntity + public abstract class Base2, U extends IFace> {} + + @QueryEntity + public abstract class BaseSub extends Base {} + + @QueryEntity + public abstract class BaseSub2> extends Base {} + + @QueryEntity + public abstract class Base2Sub extends Base2, T> {} + + public interface IFace {} + + @Test + public void base_base() throws SecurityException, NoSuchFieldException { + TypeFactory typeFactory = new TypeFactory(); + Field field = Base.class.getDeclaredField("base"); + Type type = typeFactory.get(field.getType(), field.getGenericType()); + assertEquals(0, type.getParameters().size()); + } + + @Test + public void base_base2() throws SecurityException, NoSuchFieldException { + TypeFactory typeFactory = new TypeFactory(); + Field field = Base.class.getDeclaredField("base2"); + Type type = typeFactory.get(field.getType(), field.getGenericType()); + assertEquals(2, type.getParameters().size()); + assertNull(((TypeExtends) type.getParameters().get(0)).getVarName()); + assertNull(((TypeExtends) type.getParameters().get(1)).getVarName()); + } + + @Test + public void test() { + GenericExporter exporter = new GenericExporter(); + exporter.setTargetFolder(new File("target/" + getClass().getSimpleName())); + exporter.export(getClass().getClasses()); + } +} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/PackageSuffixTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/PackageSuffixTest.java index 153b2b8f79..c75aa23376 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/PackageSuffixTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/PackageSuffixTest.java @@ -15,35 +15,34 @@ import static org.junit.Assert.assertTrue; +import com.querydsl.codegen.utils.JavaWriter; +import com.querydsl.codegen.utils.model.SimpleType; +import com.querydsl.codegen.utils.model.TypeCategory; import java.io.IOException; import java.io.StringWriter; import java.util.Collections; - import org.junit.Test; -import com.querydsl.codegen.utils.JavaWriter; -import com.querydsl.codegen.utils.model.SimpleType; -import com.querydsl.codegen.utils.model.TypeCategory; - public class PackageSuffixTest { - private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ".query"); - - private final TypeMappings typeMappings = new JavaTypeMappings(); + private final QueryTypeFactory queryTypeFactory = new QueryTypeFactoryImpl("Q", "", ".query"); - private final EntitySerializer serializer = new DefaultEntitySerializer(typeMappings, Collections.emptySet()); + private final TypeMappings typeMappings = new JavaTypeMappings(); - private final StringWriter writer = new StringWriter(); + private final EntitySerializer serializer = + new DefaultEntitySerializer(typeMappings, Collections.emptySet()); - @Test - public void correct_imports() throws IOException { - SimpleType type = new SimpleType(TypeCategory.ENTITY, "test.Entity", "test", "Entity",false,false); - EntityType entityType = new EntityType(type); - typeMappings.register(entityType, queryTypeFactory.create(entityType)); + private final StringWriter writer = new StringWriter(); - serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("import test.Entity;")); - assertTrue(writer.toString().contains("public class QEntity extends EntityPathBase {")); - } + @Test + public void correct_imports() throws IOException { + SimpleType type = + new SimpleType(TypeCategory.ENTITY, "test.Entity", "test", "Entity", false, false); + EntityType entityType = new EntityType(type); + typeMappings.register(entityType, queryTypeFactory.create(entityType)); + serializer.serialize(entityType, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("import test.Entity;")); + assertTrue(writer.toString().contains("public class QEntity extends EntityPathBase {")); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/Point.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/Point.java index 282e5da357..7d4df0385c 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/Point.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/Point.java @@ -17,21 +17,19 @@ import com.querydsl.core.types.PathMetadata; import com.querydsl.core.types.dsl.ArrayPath; - public class Point extends ArrayPath { - private static final long serialVersionUID = 1776628530121566388L; - - public Point(String variable) { - super(Double[].class, variable); - } + private static final long serialVersionUID = 1776628530121566388L; - public Point(Path parent, String property) { - super(Double[].class, parent, property); - } + public Point(String variable) { + super(Double[].class, variable); + } - public Point(PathMetadata metadata) { - super(Double[].class, metadata); - } + public Point(Path parent, String property) { + super(Double[].class, parent, property); + } + public Point(PathMetadata metadata) { + super(Double[].class, metadata); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ProjectionSerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ProjectionSerializerTest.java index 69f86c8cf3..5966b08e39 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ProjectionSerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ProjectionSerializerTest.java @@ -13,6 +13,10 @@ */ package com.querydsl.codegen; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + import com.querydsl.codegen.utils.JavaWriter; import com.querydsl.codegen.utils.model.Constructor; import com.querydsl.codegen.utils.model.Parameter; @@ -21,62 +25,87 @@ import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.codegen.utils.model.Types; import com.querydsl.core.annotations.Generated; -import org.junit.Test; - import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Arrays; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class ProjectionSerializerTest { - @Test - public void constructors() throws IOException { - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - EntityType type = new EntityType(typeModel); - - // constructor - Parameter firstName = new Parameter("firstName", Types.STRING); - Parameter lastName = new Parameter("lastName", Types.STRING); - Parameter age = new Parameter("age", Types.INTEGER); - type.addConstructor(new Constructor(Arrays.asList(firstName, lastName, age))); + @Test + public void constructors() throws IOException { + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + EntityType type = new EntityType(typeModel); - Writer writer = new StringWriter(); - ProjectionSerializer serializer = new DefaultProjectionSerializer(new JavaTypeMappings()); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - assertTrue(writer.toString().contains("Expression firstName")); - assertTrue(writer.toString().contains("Expression lastName")); - assertTrue(writer.toString().contains("Expression age")); - } + // constructor + Parameter firstName = new Parameter("firstName", Types.STRING); + Parameter lastName = new Parameter("lastName", Types.STRING); + Parameter age = new Parameter("age", Types.INTEGER); + type.addConstructor(new Constructor(Arrays.asList(firstName, lastName, age))); - @Test - public void defaultGeneratedAnnotation() throws IOException { - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - EntityType type = new EntityType(typeModel); + Writer writer = new StringWriter(); + ProjectionSerializer serializer = new DefaultProjectionSerializer(new JavaTypeMappings()); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + assertTrue(writer.toString().contains("Expression firstName")); + assertTrue(writer.toString().contains("Expression lastName")); + assertTrue(writer.toString().contains("Expression age")); + } - Writer writer = new StringWriter(); - ProjectionSerializer serializer = new DefaultProjectionSerializer(new JavaTypeMappings()); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSource = writer.toString(); - assertThat(generatedSource, containsString(String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); - assertThat(generatedSource, containsString("@Generated(\"com.querydsl.codegen.DefaultProjectionSerializer\")\npublic class")); - } + @Test + public void defaultGeneratedAnnotation() throws IOException { + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + EntityType type = new EntityType(typeModel); - @Test - public void customGeneratedAnnotation() throws IOException { - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - EntityType type = new EntityType(typeModel); + Writer writer = new StringWriter(); + ProjectionSerializer serializer = new DefaultProjectionSerializer(new JavaTypeMappings()); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSource = writer.toString(); + assertThat( + generatedSource, + containsString( + String.format("import %s;", GeneratedAnnotationResolver.resolveDefault().getName()))); + assertThat( + generatedSource, + containsString( + "@Generated(\"com.querydsl.codegen.DefaultProjectionSerializer\")\npublic class")); + } - Writer writer = new StringWriter(); - ProjectionSerializer serializer = new DefaultProjectionSerializer(new JavaTypeMappings(), Generated.class); - serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - String generatedSource = writer.toString(); - assertThat(generatedSource, containsString("import com.querydsl.core.annotations.Generated")); - assertThat(generatedSource, containsString("@Generated(\"com.querydsl.codegen.DefaultProjectionSerializer\")\npublic class")); - } + @Test + public void customGeneratedAnnotation() throws IOException { + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + EntityType type = new EntityType(typeModel); + Writer writer = new StringWriter(); + ProjectionSerializer serializer = + new DefaultProjectionSerializer(new JavaTypeMappings(), Generated.class); + serializer.serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + String generatedSource = writer.toString(); + assertThat(generatedSource, containsString("import com.querydsl.core.annotations.Generated")); + assertThat( + generatedSource, + containsString( + "@Generated(\"com.querydsl.codegen.DefaultProjectionSerializer\")\npublic class")); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/PropertyTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/PropertyTest.java index 5ec735a80e..c0ecf7746f 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/PropertyTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/PropertyTest.java @@ -15,33 +15,44 @@ import static org.junit.Assert.assertEquals; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.codegen.utils.model.SimpleType; import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeCategory; +import java.util.Collections; +import org.junit.Test; public class PropertyTest { - @Test - public void equals_and_hashCode() { - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - EntityType type = new EntityType(typeModel); - Property p1 = new Property(type, "property", type, Collections.emptyList()); - Property p2 = new Property(type, "property", type, Collections.emptyList()); - assertEquals(p1, p1); - assertEquals(p1, p2); - assertEquals(p1.hashCode(), p2.hashCode()); - } - - @Test - public void escapedName() { - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false,false); - EntityType type = new EntityType(typeModel); - Property property = new Property(type, "boolean", type, Collections.emptyList()); - assertEquals("boolean$", property.getEscapedName()); - } - + @Test + public void equals_and_hashCode() { + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + EntityType type = new EntityType(typeModel); + Property p1 = new Property(type, "property", type, Collections.emptyList()); + Property p2 = new Property(type, "property", type, Collections.emptyList()); + assertEquals(p1, p1); + assertEquals(p1, p2); + assertEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + public void escapedName() { + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + EntityType type = new EntityType(typeModel); + Property property = new Property(type, "boolean", type, Collections.emptyList()); + assertEquals("boolean$", property.getEscapedName()); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEmbeddable2Test.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEmbeddable2Test.java index bbe35c3973..0674151f8d 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEmbeddable2Test.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEmbeddable2Test.java @@ -5,27 +5,24 @@ public class QueryEmbeddable2Test extends AbstractExporterTest { - @QueryEntity - public static class User { + @QueryEntity + public static class User { - Complex complex; + Complex complex; + } - } - - @QueryEmbeddable - public static class Complex> implements Comparable> { - - T a; + @QueryEmbeddable + public static class Complex> implements Comparable> { - @Override - public int compareTo(Complex arg0) { - return 0; - } - - public boolean equals(Object o) { - return o == this; - } + T a; + @Override + public int compareTo(Complex arg0) { + return 0; } -} \ No newline at end of file + public boolean equals(Object o) { + return o == this; + } + } +} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEntityImpl.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEntityImpl.java index 21801ad322..09dc65f2a1 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEntityImpl.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryEntityImpl.java @@ -13,16 +13,14 @@ */ package com.querydsl.codegen; -import java.lang.annotation.Annotation; - import com.querydsl.core.annotations.QueryEntity; +import java.lang.annotation.Annotation; @SuppressWarnings("all") public class QueryEntityImpl implements QueryEntity { - @Override - public Class annotationType() { - return QueryEntity.class; - } - -} \ No newline at end of file + @Override + public Class annotationType() { + return QueryEntity.class; + } +} diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryTypeFactoryTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryTypeFactoryTest.java index ae5e165426..a40df7bfba 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryTypeFactoryTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/QueryTypeFactoryTest.java @@ -15,37 +15,35 @@ import static org.junit.Assert.assertEquals; -import org.junit.Test; - import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.codegen.utils.model.Type; +import org.junit.Test; public class QueryTypeFactoryTest { - private Type type = new ClassType(Point.class); - - @Test - public void prefix_only() { - QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "", ""); - assertEquals("com.querydsl.codegen.QPoint", factory.create(type).getFullName()); - } - - @Test - public void prefix_and_suffix() { - QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "Type", ""); - assertEquals("com.querydsl.codegen.QPointType", factory.create(type).getFullName()); - } - - @Test - public void suffix_only() { - QueryTypeFactory factory = new QueryTypeFactoryImpl("", "Type", ""); - assertEquals("com.querydsl.codegen.PointType", factory.create(type).getFullName()); - } - - @Test - public void prefix_and_package_suffix() { - QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "", ".query"); - assertEquals("com.querydsl.codegen.query.QPoint", factory.create(type).getFullName()); - } - + private Type type = new ClassType(Point.class); + + @Test + public void prefix_only() { + QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "", ""); + assertEquals("com.querydsl.codegen.QPoint", factory.create(type).getFullName()); + } + + @Test + public void prefix_and_suffix() { + QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "Type", ""); + assertEquals("com.querydsl.codegen.QPointType", factory.create(type).getFullName()); + } + + @Test + public void suffix_only() { + QueryTypeFactory factory = new QueryTypeFactoryImpl("", "Type", ""); + assertEquals("com.querydsl.codegen.PointType", factory.create(type).getFullName()); + } + + @Test + public void prefix_and_package_suffix() { + QueryTypeFactory factory = new QueryTypeFactoryImpl("Q", "", ".query"); + assertEquals("com.querydsl.codegen.query.QPoint", factory.create(type).getFullName()); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/ScalaTypeDump.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/ScalaTypeDump.java index 002b4716ca..a9e6e92b6b 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/ScalaTypeDump.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/ScalaTypeDump.java @@ -13,60 +13,57 @@ */ package com.querydsl.codegen; +import com.querydsl.codegen.utils.ScalaWriter; +import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.Parameter; +import com.querydsl.codegen.utils.model.Type; +import com.querydsl.core.types.Expression; +import com.querydsl.core.types.dsl.*; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; - import org.junit.Ignore; import org.junit.Test; -import com.querydsl.codegen.utils.ScalaWriter; -import com.querydsl.codegen.utils.model.ClassType; -import com.querydsl.codegen.utils.model.Parameter; -import com.querydsl.codegen.utils.model.Type; -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.dsl.*; - public class ScalaTypeDump { - @Test - @Ignore - public void test() throws IOException { - List> classes = new ArrayList>(); - classes.add(SimpleExpression.class); - classes.add(ComparableExpression.class); - classes.add(BooleanExpression.class); - classes.add(StringExpression.class); - classes.add(TemporalExpression.class); - classes.add(TimeExpression.class); - classes.add(DateTimeExpression.class); - classes.add(DateExpression.class); - classes.add(EnumExpression.class); - classes.add(NumberExpression.class); + @Test + @Ignore + public void test() throws IOException { + List> classes = new ArrayList>(); + classes.add(SimpleExpression.class); + classes.add(ComparableExpression.class); + classes.add(BooleanExpression.class); + classes.add(StringExpression.class); + classes.add(TemporalExpression.class); + classes.add(TimeExpression.class); + classes.add(DateTimeExpression.class); + classes.add(DateExpression.class); + classes.add(EnumExpression.class); + classes.add(NumberExpression.class); - StringWriter w = new StringWriter(); - ScalaWriter writer = new ScalaWriter(w); - writer.packageDecl("com.querydsl.scala"); - writer.imports(Expression.class.getPackage()); - for (Class cl : classes) { - Type type = new ClassType(cl); - Type superClass = new ClassType(cl.getSuperclass()); - writer.beginClass(type, superClass); - for (Method m : cl.getDeclaredMethods()) { - List params = new ArrayList(); - for (Class paramType : m.getParameterTypes()) { - params.add(new Parameter("arg" + params.size(), new ClassType(paramType))); - } - Type returnType = new ClassType(m.getReturnType()); - writer.beginPublicMethod(returnType, ":" + m.getName(), params.toArray(new Parameter[0])); - writer.end(); - } - writer.end(); + StringWriter w = new StringWriter(); + ScalaWriter writer = new ScalaWriter(w); + writer.packageDecl("com.querydsl.scala"); + writer.imports(Expression.class.getPackage()); + for (Class cl : classes) { + Type type = new ClassType(cl); + Type superClass = new ClassType(cl.getSuperclass()); + writer.beginClass(type, superClass); + for (Method m : cl.getDeclaredMethods()) { + List params = new ArrayList(); + for (Class paramType : m.getParameterTypes()) { + params.add(new Parameter("arg" + params.size(), new ClassType(paramType))); } - - System.out.println(w); + Type returnType = new ClassType(m.getReturnType()); + writer.beginPublicMethod(returnType, ":" + m.getName(), params.toArray(new Parameter[0])); + writer.end(); + } + writer.end(); } + System.out.println(w); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/SerializerTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/SerializerTest.java index ff3d484904..26242ef834 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/SerializerTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/SerializerTest.java @@ -13,81 +13,114 @@ */ package com.querydsl.codegen; +import com.querydsl.codegen.utils.JavaWriter; +import com.querydsl.codegen.utils.StringUtils; +import com.querydsl.codegen.utils.model.*; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.*; - import org.junit.Before; import org.junit.Test; -import com.querydsl.codegen.utils.JavaWriter; -import com.querydsl.codegen.utils.StringUtils; -import com.querydsl.codegen.utils.model.*; - public class SerializerTest { - private EntityType type; - - private Writer writer = new StringWriter(); - - private TypeMappings typeMappings = new JavaTypeMappings(); - - @SuppressWarnings("unchecked") - @Before - public void setUp() { - // type - Type typeModel = new SimpleType(TypeCategory.ENTITY, "com.querydsl.DomainClass", "com.querydsl", "DomainClass", false, false); - type = new EntityType(typeModel); - - // property - type.addProperty(new Property(type, "entityField", type)); - type.addProperty(new Property(type, "collection", new ClassType(TypeCategory.COLLECTION, Collection.class, typeModel))); - type.addProperty(new Property(type, "listField", new ClassType(TypeCategory.LIST, List.class, typeModel))); - type.addProperty(new Property(type, "setField", new ClassType(TypeCategory.SET, Set.class, typeModel))); - type.addProperty(new Property(type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class, typeModel))); - type.addProperty(new Property(type, "mapField", new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel))); - type.addProperty(new Property(type, "superTypeField", new TypeExtends(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)))); - type.addProperty(new Property(type, "extendsTypeField", new TypeSuper(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)))); - - for (Class cl : Arrays.asList(Boolean.class, Comparable.class, Integer.class, Date.class, java.sql.Date.class, java.sql.Time.class)) { - Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); - type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); - } - - // constructor - Parameter firstName = new Parameter("firstName", new ClassType(TypeCategory.STRING, String.class)); - Parameter lastName = new Parameter("lastName", new ClassType(TypeCategory.STRING, String.class)); - type.addConstructor(new Constructor(Arrays.asList(firstName, lastName))); - } - - @Test - public void entitySerializer() throws Exception { - new DefaultEntitySerializer(typeMappings, Collections.emptyList()) - .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - } - - @Test - public void entitySerializer2() throws Exception { - new DefaultEntitySerializer(typeMappings,Collections.emptyList()) - .serialize(type, new SimpleSerializerConfig(true,true,true,true,""), new JavaWriter(writer)); + private EntityType type; + + private Writer writer = new StringWriter(); + + private TypeMappings typeMappings = new JavaTypeMappings(); + + @SuppressWarnings("unchecked") + @Before + public void setUp() { + // type + Type typeModel = + new SimpleType( + TypeCategory.ENTITY, + "com.querydsl.DomainClass", + "com.querydsl", + "DomainClass", + false, + false); + type = new EntityType(typeModel); + + // property + type.addProperty(new Property(type, "entityField", type)); + type.addProperty( + new Property( + type, + "collection", + new ClassType(TypeCategory.COLLECTION, Collection.class, typeModel))); + type.addProperty( + new Property(type, "listField", new ClassType(TypeCategory.LIST, List.class, typeModel))); + type.addProperty( + new Property(type, "setField", new ClassType(TypeCategory.SET, Set.class, typeModel))); + type.addProperty( + new Property( + type, "arrayField", new ClassType(TypeCategory.ARRAY, String[].class, typeModel))); + type.addProperty( + new Property( + type, "mapField", new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel))); + type.addProperty( + new Property( + type, + "superTypeField", + new TypeExtends(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)))); + type.addProperty( + new Property( + type, + "extendsTypeField", + new TypeSuper(new ClassType(TypeCategory.MAP, List.class, typeModel, typeModel)))); + + for (Class cl : + Arrays.asList( + Boolean.class, + Comparable.class, + Integer.class, + Date.class, + java.sql.Date.class, + java.sql.Time.class)) { + Type classType = new ClassType(TypeCategory.get(cl.getName()), cl); + type.addProperty(new Property(type, StringUtils.uncapitalize(cl.getSimpleName()), classType)); } - @Test - public void embeddableSerializer() throws Exception { - new DefaultEmbeddableSerializer(typeMappings,Collections.emptyList()) - .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - } - - @Test - public void supertypeSerializer() throws IOException { - new DefaultSupertypeSerializer(typeMappings,Collections.emptyList()) - .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - } - - @Test - public void projectionSerializer() throws IOException { - new DefaultProjectionSerializer(typeMappings) - .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); - } + // constructor + Parameter firstName = + new Parameter("firstName", new ClassType(TypeCategory.STRING, String.class)); + Parameter lastName = + new Parameter("lastName", new ClassType(TypeCategory.STRING, String.class)); + type.addConstructor(new Constructor(Arrays.asList(firstName, lastName))); + } + + @Test + public void entitySerializer() throws Exception { + new DefaultEntitySerializer(typeMappings, Collections.emptyList()) + .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + } + + @Test + public void entitySerializer2() throws Exception { + new DefaultEntitySerializer(typeMappings, Collections.emptyList()) + .serialize( + type, new SimpleSerializerConfig(true, true, true, true, ""), new JavaWriter(writer)); + } + + @Test + public void embeddableSerializer() throws Exception { + new DefaultEmbeddableSerializer(typeMappings, Collections.emptyList()) + .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + } + + @Test + public void supertypeSerializer() throws IOException { + new DefaultSupertypeSerializer(typeMappings, Collections.emptyList()) + .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + } + + @Test + public void projectionSerializer() throws IOException { + new DefaultProjectionSerializer(typeMappings) + .serialize(type, SimpleSerializerConfig.DEFAULT, new JavaWriter(writer)); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass.java index 25ec9e12ad..0d6cd4a17a 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass.java @@ -2,9 +2,9 @@ public class SomeOtherClass { - static { - SomeOtherClass2.property = "XXX"; - } + static { + SomeOtherClass2.property = "XXX"; + } - public String someProperty; + public String someProperty; } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass2.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass2.java index 853b493910..9ac9851b67 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass2.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/SomeOtherClass2.java @@ -2,8 +2,7 @@ public final class SomeOtherClass2 { - private SomeOtherClass2() { } - - public static String property; + private SomeOtherClass2() {} + public static String property; } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeFactoryTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeFactoryTest.java index f530c88b81..8ebfef827c 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeFactoryTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeFactoryTest.java @@ -15,6 +15,9 @@ import static org.junit.Assert.*; +import com.querydsl.codegen.utils.model.*; +import com.querydsl.core.DefaultQueryMetadata; +import com.querydsl.core.types.Expression; import java.io.Serializable; import java.lang.reflect.Field; import java.sql.Blob; @@ -22,222 +25,221 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; - import org.junit.Test; -import com.querydsl.codegen.utils.model.*; -import com.querydsl.core.DefaultQueryMetadata; -import com.querydsl.core.types.Expression; - public class TypeFactoryTest { - Expression field; - - Expression field2; - - Expression field3; - - List> field4; - - enum EnumExample { FIRST, SECOND } - - static class Entity { - - List field; - - } - - static class ComparableEntity> implements Serializable { - - private static final long serialVersionUID = 4781357420221474135L; - - } - - private TypeFactory factory = new TypeFactory(); - - @Test - public void innerClass_field() throws SecurityException, NoSuchFieldException { - Field field = Entity.class.getDeclaredField("field"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); - assertEquals(Types.OBJECT, type.getParameters().get(0)); - } - - @Test - public void parameters() { - EntityType type = factory.getEntityType(Examples.Complex.class); - assertEquals(1, type.getParameters().size()); - assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); - } - - @Test - public void map_field_parameters() throws SecurityException, NoSuchFieldException { - Field field = Examples.ComplexCollections.class.getDeclaredField("map2"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(2, type.getParameters().size()); - Type valueType = type.getParameters().get(1); - assertEquals(1, valueType.getParameters().size()); - assertEquals(TypeExtends.class, valueType.getParameters().get(0).getClass()); - } - - @Test - public void orderBys() throws SecurityException, NoSuchFieldException { - Field field = Examples.OrderBys.class.getDeclaredField("orderBy"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); - } - - @Test - public void subEntity() { - Type type = factory.get(Examples.SubEntity.class); - assertEquals(0, type.getParameters().size()); - } - - @Test - public void abstractEntity_code() throws SecurityException, NoSuchFieldException { - Field field = EmbeddedTest.AbstractEntity.class.getDeclaredField("code"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertTrue(type instanceof TypeExtends); - assertEquals("C", ((TypeExtends) type).getVarName()); - } - - @Test - public void simpleTypes_classList5() throws SecurityException, NoSuchFieldException { - Field field = Examples.SimpleTypes.class.getDeclaredField("classList5"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(TypeCategory.LIST, type.getCategory()); - Type parameter = type.getParameters().get(0); - assertEquals(ClassType.class, parameter.getClass()); - assertEquals(TypeExtends.class, parameter.getParameters().get(0).getClass()); - } - - @Test - public void collection_of_collection() throws SecurityException, NoSuchFieldException { - Field field = Examples.GenericRelations.class.getDeclaredField("col3"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); - Type valueType = type.getParameters().get(0); - assertEquals(TypeExtends.class, valueType.getParameters().get(0).getClass()); - } - - @Test - public void generics_wildCard() throws SecurityException, NoSuchFieldException { - Field field = getClass().getDeclaredField("field"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); - assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); -// assertNull(type.getParameters().get(0)); - } - - @Test - public void generics_object() throws SecurityException, NoSuchFieldException { - Field field = getClass().getDeclaredField("field2"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); - assertEquals(Types.OBJECT, type.getParameters().get(0)); - } - - @Test - public void generics_typeVariable() { - Type type = factory.getEntityType(Generic2Test.AbstractCollectionAttribute.class); - assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); - TypeExtends t = (TypeExtends) type.getParameters().get(0); - assertEquals("T", t.getVarName()); - } - - @Test - public void generics_wildcard() throws SecurityException, NoSuchFieldException { - Field field = DefaultQueryMetadata.class.getDeclaredField("exprInJoins"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(TypeCategory.SET, type.getCategory()); - Type parameter = type.getParameters().get(0); - assertEquals(Expression.class, parameter.getJavaClass()); - parameter = parameter.getParameters().get(0); - assertEquals(TypeExtends.class, parameter.getClass()); - assertNull(((TypeExtends) parameter).getVarName()); - } - - @Test - public void comparableEntity() { - Type type = factory.getEntityType(ComparableEntity.class); - //ComparableEntity> implements Serializable - assertEquals(1, type.getParameters().size()); - TypeExtends t = (TypeExtends) type.getParameters().get(0); - assertEquals("T", t.getVarName()); - assertEquals(1, t.getParameters().size()); - } - - @Test - public void rawField() throws SecurityException, NoSuchFieldException { - Field field = getClass().getDeclaredField("field3"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); -// assertEquals(Types.OBJECT, type.getParameters().get(0)); - } - - @Test - public void extends_() throws SecurityException, NoSuchFieldException { - Field field = getClass().getDeclaredField("field4"); - Type type = factory.get(field.getType(), field.getGenericType()); - assertEquals(1, type.getParameters().size()); -// assertEquals(Types.OBJECT, type.getParameters().get(0)); - } - - @Test - public void className() { - Type type = factory.get(EnumExample.class); - assertEquals("com.querydsl.codegen.TypeFactoryTest.EnumExample", type.getFullName()); - } - - @Test - public void blob() { - Type blob = factory.get(Blob.class); - assertEquals("Blob", blob.getSimpleName()); - assertEquals("java.sql.Blob", blob.getFullName()); - assertEquals("java.sql", blob.getPackageName()); - } - - @Test - public void boolean_() { - Type bo = factory.get(boolean.class); - assertEquals(TypeCategory.BOOLEAN, bo.getCategory()); - assertEquals("Boolean", bo.getSimpleName()); - assertEquals("java.lang.Boolean", bo.getFullName()); - assertEquals("java.lang", bo.getPackageName()); - } - - @Test - public void simpleType() { - for (Class cl : Arrays.>asList(Blob.class, Clob.class, Locale.class, Class.class, Serializable.class)) { - assertEquals("wrong type for " + cl.getName(), TypeCategory.SIMPLE, factory.get(cl).getCategory()); - } - } - - @Test - public void numberType() { - for (Class cl : Arrays.>asList(Byte.class, Integer.class)) { - assertEquals("wrong type for " + cl.getName(), TypeCategory.NUMERIC, factory.get(cl).getCategory()); - } - } - - @Test - public void enumType() { - assertEquals(TypeCategory.ENUM, factory.get(EnumExample.class).getCategory()); - } - - @Test - public void unknownAsEntity() { - assertEquals(TypeCategory.SIMPLE, factory.get(TypeFactoryTest.class).getCategory()); - - factory = new TypeFactory(); - factory.setUnknownAsEntity(true); - assertEquals(TypeCategory.CUSTOM, factory.get(TypeFactoryTest.class).getCategory()); - } - - @Test - public void arrayType() { - assertEquals(Types.BYTE.asArrayType(), factory.get(Byte[].class)); - assertEquals(Types.BYTE_P.asArrayType(), factory.get(byte[].class)); - } - + Expression field; + + Expression field2; + + Expression field3; + + List> field4; + + enum EnumExample { + FIRST, + SECOND + } + + static class Entity { + + List field; + } + + static class ComparableEntity> implements Serializable { + + private static final long serialVersionUID = 4781357420221474135L; + } + + private TypeFactory factory = new TypeFactory(); + + @Test + public void innerClass_field() throws SecurityException, NoSuchFieldException { + Field field = Entity.class.getDeclaredField("field"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + assertEquals(Types.OBJECT, type.getParameters().get(0)); + } + + @Test + public void parameters() { + EntityType type = factory.getEntityType(Examples.Complex.class); + assertEquals(1, type.getParameters().size()); + assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); + } + + @Test + public void map_field_parameters() throws SecurityException, NoSuchFieldException { + Field field = Examples.ComplexCollections.class.getDeclaredField("map2"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(2, type.getParameters().size()); + Type valueType = type.getParameters().get(1); + assertEquals(1, valueType.getParameters().size()); + assertEquals(TypeExtends.class, valueType.getParameters().get(0).getClass()); + } + + @Test + public void orderBys() throws SecurityException, NoSuchFieldException { + Field field = Examples.OrderBys.class.getDeclaredField("orderBy"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + } + + @Test + public void subEntity() { + Type type = factory.get(Examples.SubEntity.class); + assertEquals(0, type.getParameters().size()); + } + + @Test + public void abstractEntity_code() throws SecurityException, NoSuchFieldException { + Field field = EmbeddedTest.AbstractEntity.class.getDeclaredField("code"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertTrue(type instanceof TypeExtends); + assertEquals("C", ((TypeExtends) type).getVarName()); + } + + @Test + public void simpleTypes_classList5() throws SecurityException, NoSuchFieldException { + Field field = Examples.SimpleTypes.class.getDeclaredField("classList5"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(TypeCategory.LIST, type.getCategory()); + Type parameter = type.getParameters().get(0); + assertEquals(ClassType.class, parameter.getClass()); + assertEquals(TypeExtends.class, parameter.getParameters().get(0).getClass()); + } + + @Test + public void collection_of_collection() throws SecurityException, NoSuchFieldException { + Field field = Examples.GenericRelations.class.getDeclaredField("col3"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + Type valueType = type.getParameters().get(0); + assertEquals(TypeExtends.class, valueType.getParameters().get(0).getClass()); + } + + @Test + public void generics_wildCard() throws SecurityException, NoSuchFieldException { + Field field = getClass().getDeclaredField("field"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); + // assertNull(type.getParameters().get(0)); + } + + @Test + public void generics_object() throws SecurityException, NoSuchFieldException { + Field field = getClass().getDeclaredField("field2"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + assertEquals(Types.OBJECT, type.getParameters().get(0)); + } + + @Test + public void generics_typeVariable() { + Type type = factory.getEntityType(Generic2Test.AbstractCollectionAttribute.class); + assertEquals(TypeExtends.class, type.getParameters().get(0).getClass()); + TypeExtends t = (TypeExtends) type.getParameters().get(0); + assertEquals("T", t.getVarName()); + } + + @Test + public void generics_wildcard() throws SecurityException, NoSuchFieldException { + Field field = DefaultQueryMetadata.class.getDeclaredField("exprInJoins"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(TypeCategory.SET, type.getCategory()); + Type parameter = type.getParameters().get(0); + assertEquals(Expression.class, parameter.getJavaClass()); + parameter = parameter.getParameters().get(0); + assertEquals(TypeExtends.class, parameter.getClass()); + assertNull(((TypeExtends) parameter).getVarName()); + } + + @Test + public void comparableEntity() { + Type type = factory.getEntityType(ComparableEntity.class); + // ComparableEntity> implements Serializable + assertEquals(1, type.getParameters().size()); + TypeExtends t = (TypeExtends) type.getParameters().get(0); + assertEquals("T", t.getVarName()); + assertEquals(1, t.getParameters().size()); + } + + @Test + public void rawField() throws SecurityException, NoSuchFieldException { + Field field = getClass().getDeclaredField("field3"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + // assertEquals(Types.OBJECT, type.getParameters().get(0)); + } + + @Test + public void extends_() throws SecurityException, NoSuchFieldException { + Field field = getClass().getDeclaredField("field4"); + Type type = factory.get(field.getType(), field.getGenericType()); + assertEquals(1, type.getParameters().size()); + // assertEquals(Types.OBJECT, type.getParameters().get(0)); + } + + @Test + public void className() { + Type type = factory.get(EnumExample.class); + assertEquals("com.querydsl.codegen.TypeFactoryTest.EnumExample", type.getFullName()); + } + + @Test + public void blob() { + Type blob = factory.get(Blob.class); + assertEquals("Blob", blob.getSimpleName()); + assertEquals("java.sql.Blob", blob.getFullName()); + assertEquals("java.sql", blob.getPackageName()); + } + + @Test + public void boolean_() { + Type bo = factory.get(boolean.class); + assertEquals(TypeCategory.BOOLEAN, bo.getCategory()); + assertEquals("Boolean", bo.getSimpleName()); + assertEquals("java.lang.Boolean", bo.getFullName()); + assertEquals("java.lang", bo.getPackageName()); + } + + @Test + public void simpleType() { + for (Class cl : + Arrays.>asList( + Blob.class, Clob.class, Locale.class, Class.class, Serializable.class)) { + assertEquals( + "wrong type for " + cl.getName(), TypeCategory.SIMPLE, factory.get(cl).getCategory()); + } + } + + @Test + public void numberType() { + for (Class cl : Arrays.>asList(Byte.class, Integer.class)) { + assertEquals( + "wrong type for " + cl.getName(), TypeCategory.NUMERIC, factory.get(cl).getCategory()); + } + } + + @Test + public void enumType() { + assertEquals(TypeCategory.ENUM, factory.get(EnumExample.class).getCategory()); + } + + @Test + public void unknownAsEntity() { + assertEquals(TypeCategory.SIMPLE, factory.get(TypeFactoryTest.class).getCategory()); + + factory = new TypeFactory(); + factory.setUnknownAsEntity(true); + assertEquals(TypeCategory.CUSTOM, factory.get(TypeFactoryTest.class).getCategory()); + } + + @Test + public void arrayType() { + assertEquals(Types.BYTE.asArrayType(), factory.get(Byte[].class)); + assertEquals(Types.BYTE_P.asArrayType(), factory.get(byte[].class)); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeMappingsTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeMappingsTest.java index a73d6db8cc..936e0e24d9 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeMappingsTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeMappingsTest.java @@ -16,52 +16,53 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import com.querydsl.codegen.utils.model.SimpleType; -import org.junit.Test; - import com.querydsl.codegen.utils.model.ClassType; +import com.querydsl.codegen.utils.model.SimpleType; import com.querydsl.codegen.utils.model.Type; - import java.util.Collections; import java.util.List; +import org.junit.Test; public class TypeMappingsTest { - static class Entity { } - - @Test - public void getPathType_of_innerClass() { - TypeMappings typeMappings = new JavaTypeMappings(); - EntityType model = new EntityType(new ClassType(TypeMappingsTest.class)); - EntityType type = new EntityType(new ClassType(Entity.class)); - typeMappings.register(type, new QueryTypeFactoryImpl("Q","","").create(type)); + static class Entity {} - Type pathType = typeMappings.getPathType(type, model, false); - assertEquals("QTypeMappingsTest_Entity", pathType.getSimpleName()); - } + @Test + public void getPathType_of_innerClass() { + TypeMappings typeMappings = new JavaTypeMappings(); + EntityType model = new EntityType(new ClassType(TypeMappingsTest.class)); + EntityType type = new EntityType(new ClassType(Entity.class)); + typeMappings.register(type, new QueryTypeFactoryImpl("Q", "", "").create(type)); - @Test - public void isRegistered() { - TypeMappings typeMappings = new JavaTypeMappings(); - typeMappings.register(new ClassType(Double[].class), new ClassType(Point.class)); - assertTrue(typeMappings.isRegistered(new ClassType(Double[].class))); - } + Type pathType = typeMappings.getPathType(type, model, false); + assertEquals("QTypeMappingsTest_Entity", pathType.getSimpleName()); + } - @Test - public void testGenericTypeRegistration() { - SimpleType rawListType = new SimpleType(List.class.getName()); - SimpleType integerListType = new SimpleType(rawListType, Collections. singletonList(new SimpleType(Integer.class.getName()))); - SimpleType longListType = new SimpleType(rawListType, Collections. singletonList(new SimpleType(Long.class.getName()))); + @Test + public void isRegistered() { + TypeMappings typeMappings = new JavaTypeMappings(); + typeMappings.register(new ClassType(Double[].class), new ClassType(Point.class)); + assertTrue(typeMappings.isRegistered(new ClassType(Double[].class))); + } - SimpleType integerListTypeExpression = new SimpleType("integerListTypeExpression"); - SimpleType longListTypeExpression = new SimpleType("longListTypeExpression"); + @Test + public void testGenericTypeRegistration() { + SimpleType rawListType = new SimpleType(List.class.getName()); + SimpleType integerListType = + new SimpleType( + rawListType, Collections.singletonList(new SimpleType(Integer.class.getName()))); + SimpleType longListType = + new SimpleType( + rawListType, Collections.singletonList(new SimpleType(Long.class.getName()))); - TypeMappings typeMappings = new JavaTypeMappings(); - typeMappings.register(integerListType, integerListTypeExpression); - typeMappings.register(longListType, longListTypeExpression); + SimpleType integerListTypeExpression = new SimpleType("integerListTypeExpression"); + SimpleType longListTypeExpression = new SimpleType("longListTypeExpression"); - assertEquals(integerListTypeExpression, typeMappings.getExprType(integerListType, null, false)); - assertEquals(longListTypeExpression, typeMappings.getExprType(longListType, null, false)); - } + TypeMappings typeMappings = new JavaTypeMappings(); + typeMappings.register(integerListType, integerListTypeExpression); + typeMappings.register(longListType, longListTypeExpression); + assertEquals(integerListTypeExpression, typeMappings.getExprType(integerListType, null, false)); + assertEquals(longListTypeExpression, typeMappings.getExprType(longListType, null, false)); + } } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeResolverTest.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeResolverTest.java index 4f03ecc203..224788f6b1 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeResolverTest.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/TypeResolverTest.java @@ -2,6 +2,6 @@ public class TypeResolverTest { - // generic parameter + // generic parameter } diff --git a/querydsl-codegen/src/test/java/com/querydsl/codegen/sub/ExampleEntity2.java b/querydsl-codegen/src/test/java/com/querydsl/codegen/sub/ExampleEntity2.java index a9d66276f3..31b2a0f637 100644 --- a/querydsl-codegen/src/test/java/com/querydsl/codegen/sub/ExampleEntity2.java +++ b/querydsl-codegen/src/test/java/com/querydsl/codegen/sub/ExampleEntity2.java @@ -18,14 +18,13 @@ @QueryEntity public class ExampleEntity2 { - private int id; + private int id; - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } } diff --git a/querydsl-codegen/src/test/java/com/suntanning/ShouldBeLoaded.java b/querydsl-codegen/src/test/java/com/suntanning/ShouldBeLoaded.java index 91114f6b82..1b30d2e32c 100644 --- a/querydsl-codegen/src/test/java/com/suntanning/ShouldBeLoaded.java +++ b/querydsl-codegen/src/test/java/com/suntanning/ShouldBeLoaded.java @@ -1,4 +1,3 @@ package com.suntanning; -public class ShouldBeLoaded { -} +public class ShouldBeLoaded {} diff --git a/querydsl-collections/pom.xml b/querydsl-collections/pom.xml index 9f39625d8f..d4177f4971 100644 --- a/querydsl-collections/pom.xml +++ b/querydsl-collections/pom.xml @@ -1,5 +1,5 @@ - + 4.0.0 @@ -11,10 +11,10 @@ com.querydsl querydsl-collections + jar Querydsl - Collections support Collections support for Querydsl ${project.homepage} - jar ${project.checkout} @@ -39,22 +39,22 @@ ${project.version} - + org.hamcrest hamcrest compile true - - + + com.querydsl querydsl-core ${project.version} - test test-jar + test @@ -90,13 +90,13 @@ ${jmh.version} test - + joda-time joda-time ${jodatime.version} test - + @@ -116,7 +116,7 @@ org.apache.felix maven-bundle-plugin - + com.mysema.maven apt-maven-plugin @@ -124,13 +124,13 @@ test-process - add-test-sources - + add-test-sources + target/generated-test-sources/java com.querydsl.apt.QuerydslAnnotationProcessor true - + diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/AbstractCollQuery.java b/querydsl-collections/src/main/java/com/querydsl/collections/AbstractCollQuery.java index 80eb51f911..e75d418308 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/AbstractCollQuery.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/AbstractCollQuery.java @@ -13,202 +13,199 @@ */ package com.querydsl.collections; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - import com.mysema.commons.lang.CloseableIterator; import com.mysema.commons.lang.IteratorAdapter; import com.querydsl.core.*; import com.querydsl.core.support.FetchableQueryBase; import com.querydsl.core.types.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; /** * {@code AbstractCollQuery} provides a base class for {@code Collection} query implementations. * * @param result type * @param concrete subtype - * * @see CollQuery * @author tiwe */ -public abstract class AbstractCollQuery> extends FetchableQueryBase - implements FetchableQuery { - - private final Map, Iterable> iterables = new HashMap, Iterable>(); - - private final QueryEngine queryEngine; - - public AbstractCollQuery(QueryMetadata metadata, QueryEngine queryEngine) { - super(new CollQueryMixin(metadata)); - @SuppressWarnings("unchecked") // Q is this + subtype - Q self = (Q) this; - this.queryMixin.setSelf(self); - this.queryEngine = queryEngine; - } - - @Override - public long fetchCount() { - return queryEngine.count(queryMixin.getMetadata(), iterables); - } - - protected QueryMetadata getMetadata() { - return queryMixin.getMetadata(); - } - - private Expression createAlias(Path> target, Path alias) { - return ExpressionUtils.operation(alias.getType(), Ops.ALIAS, target, alias); - } - - private Expression createAlias(MapExpression target, Path alias) { - return ExpressionUtils.operation(alias.getType(), Ops.ALIAS, target, alias); - } - - /** - * Add a query source - * - * @param type of expression - * @param entity Path for the source - * @param col content of the source - * @return current object - */ - public Q from(Path entity, Iterable col) { - iterables.put(entity, col); - getMetadata().addJoin(JoinType.DEFAULT, entity); - return queryMixin.getSelf(); - } - - /** - * Bind the given collection to an already existing query source - * - * @param type of expression - * @param entity Path for the source - * @param col content of the source - * @return current object - */ - public Q bind(Path entity, Iterable col) { - iterables.put(entity, col); - return queryMixin.getSelf(); - } - - @Override - public Q groupBy(Expression e) { - throw new UnsupportedOperationException(); - } - - @Override - public Q groupBy(Expression... o) { - throw new UnsupportedOperationException(); - } - - @Override - public Q having(Predicate e) { - throw new UnsupportedOperationException(); - } - - @Override - public Q having(Predicate... e) { - throw new UnsupportedOperationException(); - } - - protected QueryEngine getQueryEngine() { - return queryEngine; - } - - /** - * Define an inner join from the Collection typed path to the alias - * - * @param

type of expression - * @param target target of the join - * @param alias alias for the join target - * @return current object - */ - public

Q innerJoin(Path> target, Path

alias) { - getMetadata().addJoin(JoinType.INNERJOIN, createAlias(target, alias)); - return queryMixin.getSelf(); - } - - /** - * Define an inner join from the Map typed path to the alias - * - * @param

type of expression - * @param target target of the join - * @param alias alias for the join target - * @return current object - */ - public

Q innerJoin(MapExpression target, Path

alias) { - getMetadata().addJoin(JoinType.INNERJOIN, createAlias(target, alias)); - return queryMixin.getSelf(); - } - - /** - * Define a left join from the Collection typed path to the alias - * - * @param

type of expression - * @param target target of the join - * @param alias alias for the join target - * @return current object - */ - public

Q leftJoin(Path> target, Path

alias) { - getMetadata().addJoin(JoinType.LEFTJOIN, createAlias(target, alias)); - return queryMixin.getSelf(); - } - - /** - * Define a left join from the Map typed path to the alias - * - * @param

type of expression - * @param target target of the join - * @param alias alias for the joint target - * @return current object - */ - public

Q leftJoin(MapExpression target, Path

alias) { - getMetadata().addJoin(JoinType.LEFTJOIN, createAlias(target, alias)); - return queryMixin.getSelf(); - } - - @Override - public CloseableIterator iterate() { - @SuppressWarnings("unchecked") // This is the built type - Expression projection = (Expression) queryMixin.getMetadata().getProjection(); - return new IteratorAdapter(fetch().iterator()); - } - - @Override - public Stream stream() { - return fetch().stream(); - } - - @Override - public List fetch() { - @SuppressWarnings("unchecked") // This is the built type - Expression projection = (Expression) queryMixin.getMetadata().getProjection(); - return queryEngine.list(getMetadata(), iterables, projection); - } - - @Override - public QueryResults fetchResults() { - @SuppressWarnings("unchecked") // This is the built type - Expression projection = (Expression) queryMixin.getMetadata().getProjection(); - long count = queryEngine.count(getMetadata(), iterables); - if (count > 0L) { - List list = queryEngine.list(getMetadata(), iterables, projection); - return new QueryResults(list, getMetadata().getModifiers(), count); - } else { - return QueryResults.emptyResults(); - } - } - - @Override - public T fetchOne() throws NonUniqueResultException { - queryMixin.setUnique(true); - if (queryMixin.getMetadata().getModifiers().getLimit() == null) { - limit(2L); - } - return uniqueResult(iterate()); - } - - +public abstract class AbstractCollQuery> + extends FetchableQueryBase implements FetchableQuery { + + private final Map, Iterable> iterables = + new HashMap, Iterable>(); + + private final QueryEngine queryEngine; + + public AbstractCollQuery(QueryMetadata metadata, QueryEngine queryEngine) { + super(new CollQueryMixin(metadata)); + @SuppressWarnings("unchecked") // Q is this + subtype + Q self = (Q) this; + this.queryMixin.setSelf(self); + this.queryEngine = queryEngine; + } + + @Override + public long fetchCount() { + return queryEngine.count(queryMixin.getMetadata(), iterables); + } + + protected QueryMetadata getMetadata() { + return queryMixin.getMetadata(); + } + + private Expression createAlias(Path> target, Path alias) { + return ExpressionUtils.operation(alias.getType(), Ops.ALIAS, target, alias); + } + + private Expression createAlias(MapExpression target, Path alias) { + return ExpressionUtils.operation(alias.getType(), Ops.ALIAS, target, alias); + } + + /** + * Add a query source + * + * @param type of expression + * @param entity Path for the source + * @param col content of the source + * @return current object + */ + public Q from(Path entity, Iterable col) { + iterables.put(entity, col); + getMetadata().addJoin(JoinType.DEFAULT, entity); + return queryMixin.getSelf(); + } + + /** + * Bind the given collection to an already existing query source + * + * @param type of expression + * @param entity Path for the source + * @param col content of the source + * @return current object + */ + public Q bind(Path entity, Iterable col) { + iterables.put(entity, col); + return queryMixin.getSelf(); + } + + @Override + public Q groupBy(Expression e) { + throw new UnsupportedOperationException(); + } + + @Override + public Q groupBy(Expression... o) { + throw new UnsupportedOperationException(); + } + + @Override + public Q having(Predicate e) { + throw new UnsupportedOperationException(); + } + + @Override + public Q having(Predicate... e) { + throw new UnsupportedOperationException(); + } + + protected QueryEngine getQueryEngine() { + return queryEngine; + } + + /** + * Define an inner join from the Collection typed path to the alias + * + * @param

type of expression + * @param target target of the join + * @param alias alias for the join target + * @return current object + */ + public

Q innerJoin(Path> target, Path

alias) { + getMetadata().addJoin(JoinType.INNERJOIN, createAlias(target, alias)); + return queryMixin.getSelf(); + } + + /** + * Define an inner join from the Map typed path to the alias + * + * @param

type of expression + * @param target target of the join + * @param alias alias for the join target + * @return current object + */ + public

Q innerJoin(MapExpression target, Path

alias) { + getMetadata().addJoin(JoinType.INNERJOIN, createAlias(target, alias)); + return queryMixin.getSelf(); + } + + /** + * Define a left join from the Collection typed path to the alias + * + * @param

type of expression + * @param target target of the join + * @param alias alias for the join target + * @return current object + */ + public

Q leftJoin(Path> target, Path

alias) { + getMetadata().addJoin(JoinType.LEFTJOIN, createAlias(target, alias)); + return queryMixin.getSelf(); + } + + /** + * Define a left join from the Map typed path to the alias + * + * @param

type of expression + * @param target target of the join + * @param alias alias for the joint target + * @return current object + */ + public

Q leftJoin(MapExpression target, Path

alias) { + getMetadata().addJoin(JoinType.LEFTJOIN, createAlias(target, alias)); + return queryMixin.getSelf(); + } + + @Override + public CloseableIterator iterate() { + @SuppressWarnings("unchecked") // This is the built type + Expression projection = (Expression) queryMixin.getMetadata().getProjection(); + return new IteratorAdapter(fetch().iterator()); + } + + @Override + public Stream stream() { + return fetch().stream(); + } + + @Override + public List fetch() { + @SuppressWarnings("unchecked") // This is the built type + Expression projection = (Expression) queryMixin.getMetadata().getProjection(); + return queryEngine.list(getMetadata(), iterables, projection); + } + + @Override + public QueryResults fetchResults() { + @SuppressWarnings("unchecked") // This is the built type + Expression projection = (Expression) queryMixin.getMetadata().getProjection(); + long count = queryEngine.count(getMetadata(), iterables); + if (count > 0L) { + List list = queryEngine.list(getMetadata(), iterables, projection); + return new QueryResults(list, getMetadata().getModifiers(), count); + } else { + return QueryResults.emptyResults(); + } + } + + @Override + public T fetchOne() throws NonUniqueResultException { + queryMixin.setUnique(true); + if (queryMixin.getMetadata().getModifiers().getLimit() == null) { + limit(2L); + } + return uniqueResult(iterate()); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollDeleteClause.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollDeleteClause.java index a7f1bad3f1..de7cd8d64b 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollDeleteClause.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollDeleteClause.java @@ -13,53 +13,51 @@ */ package com.querydsl.collections; -import java.util.Collection; - import com.querydsl.core.dml.DeleteClause; import com.querydsl.core.types.Path; import com.querydsl.core.types.Predicate; +import java.util.Collection; /** - * {@code CollDeleteClause} is an implementation of the {@link DeleteClause} interface for the Querydsl - * Collections module + * {@code CollDeleteClause} is an implementation of the {@link DeleteClause} interface for the + * Querydsl Collections module * * @author tiwe - * * @param */ public class CollDeleteClause implements DeleteClause> { - private final Collection col; - - private final CollQuery query; + private final Collection col; - public CollDeleteClause(QueryEngine qe, Path expr, Collection col) { - this.query = new CollQuery(qe).from(expr, col).select(expr); - this.col = col; - } + private final CollQuery query; - public CollDeleteClause(Path expr, Collection col) { - this(DefaultQueryEngine.getDefault(), expr, col); - } + public CollDeleteClause(QueryEngine qe, Path expr, Collection col) { + this.query = new CollQuery(qe).from(expr, col).select(expr); + this.col = col; + } - @Override - public long execute() { - int rv = 0; - for (T match : query.fetch()) { - col.remove(match); - rv++; - } - return rv; - } - - @Override - public CollDeleteClause where(Predicate... o) { - query.where(o); - return this; - } + public CollDeleteClause(Path expr, Collection col) { + this(DefaultQueryEngine.getDefault(), expr, col); + } - @Override - public String toString() { - return "delete " + query.toString(); + @Override + public long execute() { + int rv = 0; + for (T match : query.fetch()) { + col.remove(match); + rv++; } + return rv; + } + + @Override + public CollDeleteClause where(Predicate... o) { + query.where(o); + return this; + } + + @Override + public String toString() { + return "delete " + query.toString(); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQuery.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQuery.java index 016fdaeeca..322d37e592 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQuery.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQuery.java @@ -20,80 +20,75 @@ import com.querydsl.core.types.Expression; /** - * {@code CollQuery} is the default implementation of the {@link FetchableQuery} interface for collections + * {@code CollQuery} is the default implementation of the {@link FetchableQuery} interface for + * collections * * @param result type - * * @author tiwe */ public class CollQuery extends AbstractCollQuery> implements Cloneable { - /** - * Create a new CollQuery instance - */ - public CollQuery() { - super(new DefaultQueryMetadata(), DefaultQueryEngine.getDefault()); - } - - /** - * Creates a new CollQuery instance - * - * @param templates serialization templates - */ - public CollQuery(CollQueryTemplates templates) { - this(new DefaultQueryEngine(new DefaultEvaluatorFactory(templates))); - } + /** Create a new CollQuery instance */ + public CollQuery() { + super(new DefaultQueryMetadata(), DefaultQueryEngine.getDefault()); + } - /** - * Create a new CollQuery instance - * - * @param queryEngine query engine for query execution - */ - public CollQuery(QueryEngine queryEngine) { - super(new DefaultQueryMetadata(), queryEngine); - } + /** + * Creates a new CollQuery instance + * + * @param templates serialization templates + */ + public CollQuery(CollQueryTemplates templates) { + this(new DefaultQueryEngine(new DefaultEvaluatorFactory(templates))); + } + /** + * Create a new CollQuery instance + * + * @param queryEngine query engine for query execution + */ + public CollQuery(QueryEngine queryEngine) { + super(new DefaultQueryMetadata(), queryEngine); + } - /** - * Create a new CollQuery instance - * - * @param metadata query metadata - */ - public CollQuery(QueryMetadata metadata) { - super(metadata, DefaultQueryEngine.getDefault()); - } + /** + * Create a new CollQuery instance + * + * @param metadata query metadata + */ + public CollQuery(QueryMetadata metadata) { + super(metadata, DefaultQueryEngine.getDefault()); + } - /** - * Create a new CollQuery instance - * - * @param metadata query metadata - * @param queryEngine query engine for query execution - */ - public CollQuery(QueryMetadata metadata, QueryEngine queryEngine) { - super(metadata, queryEngine); - } + /** + * Create a new CollQuery instance + * + * @param metadata query metadata + * @param queryEngine query engine for query execution + */ + public CollQuery(QueryMetadata metadata, QueryEngine queryEngine) { + super(metadata, queryEngine); + } - /** - * Clone the state of this query to a new CollQuery instance - */ - @Override - public CollQuery clone() { - return new CollQuery(queryMixin.getMetadata().clone(), getQueryEngine()); - } + /** Clone the state of this query to a new CollQuery instance */ + @Override + public CollQuery clone() { + return new CollQuery(queryMixin.getMetadata().clone(), getQueryEngine()); + } - @Override - public CollQuery select(Expression expr) { - queryMixin.setProjection(expr); - @SuppressWarnings("unchecked") // This is the new projection's type - CollQuery newType = (CollQuery) queryMixin.getSelf(); - return newType; - } + @Override + public CollQuery select(Expression expr) { + queryMixin.setProjection(expr); + @SuppressWarnings("unchecked") // This is the new projection's type + CollQuery newType = (CollQuery) queryMixin.getSelf(); + return newType; + } - @Override - public CollQuery select(Expression... exprs) { - queryMixin.setProjection(exprs); - @SuppressWarnings("unchecked") // This is the new projection's type - CollQuery newType = (CollQuery) queryMixin.getSelf(); - return newType; - } + @Override + public CollQuery select(Expression... exprs) { + queryMixin.setProjection(exprs); + @SuppressWarnings("unchecked") // This is the new projection's type + CollQuery newType = (CollQuery) queryMixin.getSelf(); + return newType; + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFactory.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFactory.java index b43aa21463..cc9a929c28 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFactory.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFactory.java @@ -13,13 +13,12 @@ */ package com.querydsl.collections; +import com.querydsl.core.alias.Alias; +import com.querydsl.core.types.Path; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import com.querydsl.core.alias.Alias; -import com.querydsl.core.types.Path; - /** * {@code CollQueryFactory} provides static convenience methods for query construction * @@ -27,62 +26,63 @@ */ public final class CollQueryFactory { - /** - * Create a new delete clause - * - * @param path source expression - * @param col source collection - * @return delete clause - */ - public static CollDeleteClause delete(Path path, Collection col) { - return new CollDeleteClause(path, col); - } - - /** - * Create a new query - * - * @param alias source alias - * @param col source collection - * @return query - */ - public static CollQuery from(A alias, Iterable col) { - Path expr = Alias.$(alias); - return new CollQuery().from(expr, col).select(expr); - } + /** + * Create a new delete clause + * + * @param path source expression + * @param col source collection + * @return delete clause + */ + public static CollDeleteClause delete(Path path, Collection col) { + return new CollDeleteClause(path, col); + } - /** - * Create a new query - * - * @param path source expression - * @param arr source array - * @return query - */ - public static CollQuery from(Path path, A... arr) { - return new CollQuery().from(path, Collections.unmodifiableList(Arrays.asList(arr))).select(path); - } + /** + * Create a new query + * + * @param alias source alias + * @param col source collection + * @return query + */ + public static CollQuery from(A alias, Iterable col) { + Path expr = Alias.$(alias); + return new CollQuery().from(expr, col).select(expr); + } - /** - * Create a new query - * - * @param path source expression - * @param col source collection - * @return query - */ - public static CollQuery from(Path path, Iterable col) { - return new CollQuery().from(path, col).select(path); - } + /** + * Create a new query + * + * @param path source expression + * @param arr source array + * @return query + */ + public static CollQuery from(Path path, A... arr) { + return new CollQuery() + .from(path, Collections.unmodifiableList(Arrays.asList(arr))) + .select(path); + } - /** - * Create a new update clause - * - * @param path source expression - * @param col source collection - * @return query - */ - public static CollUpdateClause update(Path path, Iterable col) { - return new CollUpdateClause(path, col); - } + /** + * Create a new query + * + * @param path source expression + * @param col source collection + * @return query + */ + public static CollQuery from(Path path, Iterable col) { + return new CollQuery().from(path, col).select(path); + } - private CollQueryFactory() { } + /** + * Create a new update clause + * + * @param path source expression + * @param col source collection + * @return query + */ + public static CollUpdateClause update(Path path, Iterable col) { + return new CollUpdateClause(path, col); + } + private CollQueryFactory() {} } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFunctions.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFunctions.java index 4477a38293..b5e096e848 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFunctions.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryFunctions.java @@ -13,299 +13,299 @@ */ package com.querydsl.collections; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.util.*; -import java.util.regex.Pattern; - -import org.jetbrains.annotations.Nullable; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.Operator; import com.querydsl.core.types.Ops; import com.querydsl.core.util.MathUtils; import com.querydsl.core.util.ReflectionUtils; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.*; +import java.util.regex.Pattern; +import org.jetbrains.annotations.Nullable; /** * {@code CollQueryFunctions} defines function implementation for use in ColQueryTemplates * * @author tiwe - * */ public final class CollQueryFunctions { - private interface BinaryFunction { + private interface BinaryFunction { - Number apply(Number num1, Number num2); - } + Number apply(Number num1, Number num2); + } - private static final BinaryFunction SUM = new BinaryFunction() { + private static final BinaryFunction SUM = + new BinaryFunction() { @Override public Number apply(Number num1, Number num2) { - return MathUtils.sum(num1, num2); + return MathUtils.sum(num1, num2); } - }; + }; - private static final BinaryFunction MAX = new BinaryFunction() { + private static final BinaryFunction MAX = + new BinaryFunction() { @Override public Number apply(Number num1, Number num2) { - if (num1.getClass().equals(num2.getClass()) && num1 instanceof Comparable) { - @SuppressWarnings("unchecked") // The types are interchangeable, guarded by previous check - Comparable left = (Comparable) num1; - return left.compareTo(num2) < 0 ? num2 : num1; - } else { - BigDecimal n1 = new BigDecimal(num1.toString()); - BigDecimal n2 = new BigDecimal(num2.toString()); - return n1.compareTo(n2) < 0 ? num2 : num1; - } + if (num1.getClass().equals(num2.getClass()) && num1 instanceof Comparable) { + @SuppressWarnings( + "unchecked") // The types are interchangeable, guarded by previous check + Comparable left = (Comparable) num1; + return left.compareTo(num2) < 0 ? num2 : num1; + } else { + BigDecimal n1 = new BigDecimal(num1.toString()); + BigDecimal n2 = new BigDecimal(num2.toString()); + return n1.compareTo(n2) < 0 ? num2 : num1; + } } - }; + }; - private static final BinaryFunction MIN = new BinaryFunction() { + private static final BinaryFunction MIN = + new BinaryFunction() { @Override public Number apply(Number num1, Number num2) { - if (num1.getClass().equals(num2.getClass()) && num1 instanceof Comparable) { - @SuppressWarnings("unchecked") // The types are interchangeable, guarded by previous check - Comparable left = (Comparable) num1; - return left.compareTo(num2) < 0 ? num1 : num2; - } else { - BigDecimal n1 = new BigDecimal(num1.toString()); - BigDecimal n2 = new BigDecimal(num2.toString()); - return n1.compareTo(n2) < 0 ? num1 : num2; - } - } - }; - - private static final List nullList = Collections.singletonList((Object) null); - - @SuppressWarnings("unused") - public static boolean equals(Object o1, Object o2) { - return Objects.equals(o1, o2); - } - - public static > int compareTo(T c1, T c2) { - if (c1 == null) { - return c2 == null ? 0 : -1; - } else if (c2 == null) { - return 1; - } else { - return c1.compareTo(c2); - } - } - - public static > boolean between(A a, A b, A c) { - return compareTo(a, b) >= 0 && compareTo(a, c) <= 0; - } - - public static double cot(double x) { - return Math.cos(x) / Math.sin(x); - } - - public static double coth(double x) { - return Math.cosh(x) / Math.sinh(x); - } - - public static double degrees(double x) { - return x * 180.0 / Math.PI; - } - - public static double radians(double x) { - return x * Math.PI / 180.0; - } - - public static double log(double x, int y) { - return Math.log(x) / Math.log(y); - } - - @Nullable - public static T coalesce(T... args) { - for (T arg : args) { - if (arg != null) { - return arg; - } + if (num1.getClass().equals(num2.getClass()) && num1 instanceof Comparable) { + @SuppressWarnings( + "unchecked") // The types are interchangeable, guarded by previous check + Comparable left = (Comparable) num1; + return left.compareTo(num2) < 0 ? num1 : num2; + } else { + BigDecimal n1 = new BigDecimal(num1.toString()); + BigDecimal n2 = new BigDecimal(num2.toString()); + return n1.compareTo(n2) < 0 ? num1 : num2; + } } - return null; - } - - public static T nullif(T first, T second) { - if (first.equals(second)) { - return null; - } else { - return first; - } - } - - public static int getYearMonth(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(Calendar.YEAR) * 100 + cal.get(Calendar.MONTH) + 1; - } - - public static int getDayOfMonth(Date date) { - return getField(date, Calendar.DAY_OF_MONTH); - } - - public static int getDayOfWeek(Date date) { - return getField(date, Calendar.DAY_OF_WEEK); - } - - public static int getDayOfYear(Date date) { - return getField(date, Calendar.DAY_OF_YEAR); - } - - private static int getField(Date date, int field) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(field); - } - - public static int getHour(Date date) { - return getField(date, Calendar.HOUR_OF_DAY); - } - - public static int getMilliSecond(Date date) { - return getField(date, Calendar.MILLISECOND); - } - - public static int getMinute(Date date) { - return getField(date, Calendar.MINUTE); - } - - public static int getMonth(Date date) { - return getField(date, Calendar.MONTH) + 1; - } - - public static int getSecond(Date date) { - return getField(date, Calendar.SECOND); - } - - public static int getWeek(Date date) { - return getField(date, Calendar.WEEK_OF_YEAR); - } - - public static int getYear(Date date) { - return getField(date, Calendar.YEAR); - } - - public static int getYearWeek(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal.get(Calendar.YEAR) * 100 + cal.get(Calendar.WEEK_OF_YEAR); - } - - public static Collection leftJoin(Collection coll) { - if (coll == null || coll.isEmpty()) { - @SuppressWarnings("unchecked") // List only contains null - Collection rv = (Collection) nullList; - return rv; - } else { - return coll; - } - } - - private static Number reduce(Iterable source, BinaryFunction f) { - Iterator it = source.iterator(); - Number result = it.next(); - while (it.hasNext()) { - result = f.apply(result, it.next()); - } - return result; - } - - public static Number aggregate(Collection source, Expression expr, Operator aggregator) { - @SuppressWarnings("unchecked") // This is a number expression - Class numberType = (Class) expr.getType(); - if (aggregator == Ops.AggOps.AVG_AGG) { - Number sum = reduce(source, SUM); - return sum.doubleValue() / source.size(); - } else if (aggregator == Ops.AggOps.COUNT_AGG) { - return (long) source.size(); - } else if (aggregator == Ops.AggOps.COUNT_DISTINCT_AGG) { - if (!Set.class.isInstance(source)) { - source = new HashSet<>(source); - } - return (long) source.size(); - } else if (aggregator == Ops.AggOps.MAX_AGG) { - return MathUtils.cast(reduce(source, MAX), numberType); - } else if (aggregator == Ops.AggOps.MIN_AGG) { - return MathUtils.cast(reduce(source, MIN), numberType); - } else if (aggregator == Ops.AggOps.SUM_AGG) { - return MathUtils.cast(reduce(source, SUM), numberType); - } else { - throw new IllegalArgumentException("Unknown operator " + aggregator); - } - } - - public static boolean like(final String str, String like) { - final StringBuilder pattern = new StringBuilder(like.length() + 4); - for (int i = 0; i < like.length(); i++) { - final char ch = like.charAt(i); - if (ch == '%') { - pattern.append(".*"); - continue; - } else if (ch == '_') { - pattern.append('.'); - continue; - } else if (ch == '.' || ch == '$' || ch == '^') { - pattern.append('\\'); - } - pattern.append(ch); - } - if (pattern.toString().equals(like)) { - return str.equals(like); - } else { - return str.matches(pattern.toString()); - } - } - - public static boolean like(String str, String like, char escape) { - return like(str, like); - } - - public static boolean likeIgnoreCase(String str, String like) { - final StringBuilder pattern = new StringBuilder(like.length() + 4); - for (int i = 0; i < like.length(); i++) { - final char ch = like.charAt(i); - if (ch == '%') { - pattern.append(".*"); - continue; - } else if (ch == '_') { - pattern.append('.'); - continue; - } else if (ch == '.' || ch == '$' || ch == '^') { - pattern.append('\\'); - } - pattern.append(ch); - } - if (pattern.toString().equals(like)) { - return str.equalsIgnoreCase(like); - } else { - return Pattern.compile(pattern.toString(), Pattern.CASE_INSENSITIVE) - .matcher(str).matches(); - } - } - - public static boolean likeIgnoreCase(String str, String like, char escape) { - return likeIgnoreCase(str, like); - } - - public static T get(Object parent, String f) { - try { - Field field = ReflectionUtils.getFieldOrNull(parent.getClass(), f); - if (field != null) { - field.setAccessible(true); - @SuppressWarnings("unchecked") - T rv = (T) field.get(parent); - return rv; - } else { - throw new IllegalArgumentException("No field " + f + " for " + parent.getClass()); - } - } catch (IllegalAccessException e) { - throw new IllegalStateException(e); - } - } - - private CollQueryFunctions() { } - - + }; + + private static final List nullList = Collections.singletonList((Object) null); + + @SuppressWarnings("unused") + public static boolean equals(Object o1, Object o2) { + return Objects.equals(o1, o2); + } + + public static > int compareTo(T c1, T c2) { + if (c1 == null) { + return c2 == null ? 0 : -1; + } else if (c2 == null) { + return 1; + } else { + return c1.compareTo(c2); + } + } + + public static > boolean between(A a, A b, A c) { + return compareTo(a, b) >= 0 && compareTo(a, c) <= 0; + } + + public static double cot(double x) { + return Math.cos(x) / Math.sin(x); + } + + public static double coth(double x) { + return Math.cosh(x) / Math.sinh(x); + } + + public static double degrees(double x) { + return x * 180.0 / Math.PI; + } + + public static double radians(double x) { + return x * Math.PI / 180.0; + } + + public static double log(double x, int y) { + return Math.log(x) / Math.log(y); + } + + @Nullable + public static T coalesce(T... args) { + for (T arg : args) { + if (arg != null) { + return arg; + } + } + return null; + } + + public static T nullif(T first, T second) { + if (first.equals(second)) { + return null; + } else { + return first; + } + } + + public static int getYearMonth(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.YEAR) * 100 + cal.get(Calendar.MONTH) + 1; + } + + public static int getDayOfMonth(Date date) { + return getField(date, Calendar.DAY_OF_MONTH); + } + + public static int getDayOfWeek(Date date) { + return getField(date, Calendar.DAY_OF_WEEK); + } + + public static int getDayOfYear(Date date) { + return getField(date, Calendar.DAY_OF_YEAR); + } + + private static int getField(Date date, int field) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(field); + } + + public static int getHour(Date date) { + return getField(date, Calendar.HOUR_OF_DAY); + } + + public static int getMilliSecond(Date date) { + return getField(date, Calendar.MILLISECOND); + } + + public static int getMinute(Date date) { + return getField(date, Calendar.MINUTE); + } + + public static int getMonth(Date date) { + return getField(date, Calendar.MONTH) + 1; + } + + public static int getSecond(Date date) { + return getField(date, Calendar.SECOND); + } + + public static int getWeek(Date date) { + return getField(date, Calendar.WEEK_OF_YEAR); + } + + public static int getYear(Date date) { + return getField(date, Calendar.YEAR); + } + + public static int getYearWeek(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.YEAR) * 100 + cal.get(Calendar.WEEK_OF_YEAR); + } + + public static Collection leftJoin(Collection coll) { + if (coll == null || coll.isEmpty()) { + @SuppressWarnings("unchecked") // List only contains null + Collection rv = (Collection) nullList; + return rv; + } else { + return coll; + } + } + + private static Number reduce(Iterable source, BinaryFunction f) { + Iterator it = source.iterator(); + Number result = it.next(); + while (it.hasNext()) { + result = f.apply(result, it.next()); + } + return result; + } + + public static Number aggregate( + Collection source, Expression expr, Operator aggregator) { + @SuppressWarnings("unchecked") // This is a number expression + Class numberType = (Class) expr.getType(); + if (aggregator == Ops.AggOps.AVG_AGG) { + Number sum = reduce(source, SUM); + return sum.doubleValue() / source.size(); + } else if (aggregator == Ops.AggOps.COUNT_AGG) { + return (long) source.size(); + } else if (aggregator == Ops.AggOps.COUNT_DISTINCT_AGG) { + if (!Set.class.isInstance(source)) { + source = new HashSet<>(source); + } + return (long) source.size(); + } else if (aggregator == Ops.AggOps.MAX_AGG) { + return MathUtils.cast(reduce(source, MAX), numberType); + } else if (aggregator == Ops.AggOps.MIN_AGG) { + return MathUtils.cast(reduce(source, MIN), numberType); + } else if (aggregator == Ops.AggOps.SUM_AGG) { + return MathUtils.cast(reduce(source, SUM), numberType); + } else { + throw new IllegalArgumentException("Unknown operator " + aggregator); + } + } + + public static boolean like(final String str, String like) { + final StringBuilder pattern = new StringBuilder(like.length() + 4); + for (int i = 0; i < like.length(); i++) { + final char ch = like.charAt(i); + if (ch == '%') { + pattern.append(".*"); + continue; + } else if (ch == '_') { + pattern.append('.'); + continue; + } else if (ch == '.' || ch == '$' || ch == '^') { + pattern.append('\\'); + } + pattern.append(ch); + } + if (pattern.toString().equals(like)) { + return str.equals(like); + } else { + return str.matches(pattern.toString()); + } + } + + public static boolean like(String str, String like, char escape) { + return like(str, like); + } + + public static boolean likeIgnoreCase(String str, String like) { + final StringBuilder pattern = new StringBuilder(like.length() + 4); + for (int i = 0; i < like.length(); i++) { + final char ch = like.charAt(i); + if (ch == '%') { + pattern.append(".*"); + continue; + } else if (ch == '_') { + pattern.append('.'); + continue; + } else if (ch == '.' || ch == '$' || ch == '^') { + pattern.append('\\'); + } + pattern.append(ch); + } + if (pattern.toString().equals(like)) { + return str.equalsIgnoreCase(like); + } else { + return Pattern.compile(pattern.toString(), Pattern.CASE_INSENSITIVE).matcher(str).matches(); + } + } + + public static boolean likeIgnoreCase(String str, String like, char escape) { + return likeIgnoreCase(str, like); + } + + public static T get(Object parent, String f) { + try { + Field field = ReflectionUtils.getFieldOrNull(parent.getClass(), f); + if (field != null) { + field.setAccessible(true); + @SuppressWarnings("unchecked") + T rv = (T) field.get(parent); + return rv; + } else { + throw new IllegalArgumentException("No field " + f + " for " + parent.getClass()); + } + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + private CollQueryFunctions() {} } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryMixin.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryMixin.java index 2b98f2fbb0..faa9302fcf 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryMixin.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryMixin.java @@ -22,41 +22,41 @@ import com.querydsl.core.types.dsl.Expressions; /** - * {@code CollQueryMixin} extends {@link QueryMixin} to provide normalization logic specific to this module + * {@code CollQueryMixin} extends {@link QueryMixin} to provide normalization logic specific to this + * module * * @author tiwe - * * @param */ public class CollQueryMixin extends QueryMixin { - private static final Predicate ANY = Expressions.booleanTemplate("any"); + private static final Predicate ANY = Expressions.booleanTemplate("any"); - public CollQueryMixin() { } + public CollQueryMixin() {} - public CollQueryMixin(QueryMetadata metadata) { - super(metadata); - } + public CollQueryMixin(QueryMetadata metadata) { + super(metadata); + } - public CollQueryMixin(T self, QueryMetadata metadata) { - super(self, metadata); - } + public CollQueryMixin(T self, QueryMetadata metadata) { + super(self, metadata); + } - @Override - protected Predicate convert(Predicate predicate, Role role) { - predicate = (Predicate) ExpressionUtils.extract(predicate); - if (predicate != null) { - Context context = new Context(); - Predicate transformed = (Predicate) predicate.accept(collectionAnyVisitor, context); - for (int i = 0; i < context.paths.size(); i++) { - leftJoin( - (Path) context.paths.get(i).getMetadata().getParent(), - (Path) context.replacements.get(i)); - on(ANY); - } - return transformed; - } else { - return predicate; - } + @Override + protected Predicate convert(Predicate predicate, Role role) { + predicate = (Predicate) ExpressionUtils.extract(predicate); + if (predicate != null) { + Context context = new Context(); + Predicate transformed = (Predicate) predicate.accept(collectionAnyVisitor, context); + for (int i = 0; i < context.paths.size(); i++) { + leftJoin( + (Path) context.paths.get(i).getMetadata().getParent(), + (Path) context.replacements.get(i)); + on(ANY); + } + return transformed; + } else { + return predicate; } + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQuerySerializer.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQuerySerializer.java index 3a30b0d088..90f2c89b5c 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQuerySerializer.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQuerySerializer.java @@ -13,6 +13,11 @@ */ package com.querydsl.collections; +import com.querydsl.codegen.Serializer; +import com.querydsl.core.QueryException; +import com.querydsl.core.support.SerializerBase; +import com.querydsl.core.types.*; +import com.querydsl.core.util.PrimitiveUtils; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; @@ -26,12 +31,6 @@ import java.util.List; import java.util.Map; -import com.querydsl.codegen.Serializer; -import com.querydsl.core.QueryException; -import com.querydsl.core.support.SerializerBase; -import com.querydsl.core.types.*; -import com.querydsl.core.util.PrimitiveUtils; - /** * {@code CollQuerySerializer} is a {@link Serializer} implementation for the Java language * @@ -39,181 +38,183 @@ */ public final class CollQuerySerializer extends SerializerBase { - private static final Map OPERATOR_SYMBOLS = new IdentityHashMap<>(); - - private static final Map, String> CAST_SUFFIXES = new HashMap<>(); - - static { - OPERATOR_SYMBOLS.put(Ops.EQ, " == "); - OPERATOR_SYMBOLS.put(Ops.NE, " != "); - OPERATOR_SYMBOLS.put(Ops.GT, " > "); - OPERATOR_SYMBOLS.put(Ops.LT, " < "); - OPERATOR_SYMBOLS.put(Ops.GOE, " >= "); - OPERATOR_SYMBOLS.put(Ops.LOE, " <= "); - - OPERATOR_SYMBOLS.put(Ops.ADD, " + "); - OPERATOR_SYMBOLS.put(Ops.SUB, " - "); - OPERATOR_SYMBOLS.put(Ops.MULT, " * "); - OPERATOR_SYMBOLS.put(Ops.DIV, " / "); - - CAST_SUFFIXES.put(Boolean.class, ".booleanValue()"); - CAST_SUFFIXES.put(Byte.class, ".byteValue()"); - CAST_SUFFIXES.put(Character.class, ".charValue()"); - CAST_SUFFIXES.put(Double.class, ".doubleValue()"); - CAST_SUFFIXES.put(Float.class, ".floatValue()"); - CAST_SUFFIXES.put(Integer.class, ".intValue()"); - CAST_SUFFIXES.put(Long.class, ".longValue()"); - CAST_SUFFIXES.put(Short.class, ".shortValue()"); - CAST_SUFFIXES.put(String.class, ".toString()"); - } - - public CollQuerySerializer(CollQueryTemplates templates) { - super(templates); - } - - @Override - public Void visit(Path path, Void context) { - final PathType pathType = path.getMetadata().getPathType(); - if (pathType == PathType.PROPERTY) { - final Path parent = path.getMetadata().getParent(); - final String property = path.getMetadata().getName(); - final Class parentType = parent.getType(); - try { - // getter - Method m = getAccessor(parentType, property); - if (m != null && Modifier.isPublic(m.getModifiers())) { - handle(parent); - append(".").append(m.getName()).append("()"); - } else { - // field - Field f = getField(parentType, property); - if (f != null && Modifier.isPublic(f.getModifiers())) { - handle(parent); - append(".").append(property); - } else { - // field access by reflection - append(CollQueryFunctions.class.getName() + ".<"); - append((path.getType()).getName()).append(">get("); - handle(parent); - append(", \"" + property + "\")"); - } - } - } catch (Exception e) { - throw new QueryException(e); - } - - } else if (pathType == PathType.DELEGATE) { - append("("); - append("(").append(path.getType().getName()).append(")"); - path.getMetadata().getParent().accept(this, context); - append(")"); - + private static final Map OPERATOR_SYMBOLS = new IdentityHashMap<>(); + + private static final Map, String> CAST_SUFFIXES = new HashMap<>(); + + static { + OPERATOR_SYMBOLS.put(Ops.EQ, " == "); + OPERATOR_SYMBOLS.put(Ops.NE, " != "); + OPERATOR_SYMBOLS.put(Ops.GT, " > "); + OPERATOR_SYMBOLS.put(Ops.LT, " < "); + OPERATOR_SYMBOLS.put(Ops.GOE, " >= "); + OPERATOR_SYMBOLS.put(Ops.LOE, " <= "); + + OPERATOR_SYMBOLS.put(Ops.ADD, " + "); + OPERATOR_SYMBOLS.put(Ops.SUB, " - "); + OPERATOR_SYMBOLS.put(Ops.MULT, " * "); + OPERATOR_SYMBOLS.put(Ops.DIV, " / "); + + CAST_SUFFIXES.put(Boolean.class, ".booleanValue()"); + CAST_SUFFIXES.put(Byte.class, ".byteValue()"); + CAST_SUFFIXES.put(Character.class, ".charValue()"); + CAST_SUFFIXES.put(Double.class, ".doubleValue()"); + CAST_SUFFIXES.put(Float.class, ".floatValue()"); + CAST_SUFFIXES.put(Integer.class, ".intValue()"); + CAST_SUFFIXES.put(Long.class, ".longValue()"); + CAST_SUFFIXES.put(Short.class, ".shortValue()"); + CAST_SUFFIXES.put(String.class, ".toString()"); + } + + public CollQuerySerializer(CollQueryTemplates templates) { + super(templates); + } + + @Override + public Void visit(Path path, Void context) { + final PathType pathType = path.getMetadata().getPathType(); + if (pathType == PathType.PROPERTY) { + final Path parent = path.getMetadata().getParent(); + final String property = path.getMetadata().getName(); + final Class parentType = parent.getType(); + try { + // getter + Method m = getAccessor(parentType, property); + if (m != null && Modifier.isPublic(m.getModifiers())) { + handle(parent); + append(".").append(m.getName()).append("()"); } else { - List args = new ArrayList(2); - if (path.getMetadata().getParent() != null) { - args.add(path.getMetadata().getParent()); - } - args.add(path.getMetadata().getElement()); - final Template template = getTemplate(pathType); - for (Template.Element element : template.getElements()) { - Object rv = element.convert(args); - if (rv instanceof Expression) { - ((Expression) rv).accept(this, context); - } else if (element.isString()) { - append(rv.toString()); - } else { - visitConstant(rv); - } - } + // field + Field f = getField(parentType, property); + if (f != null && Modifier.isPublic(f.getModifiers())) { + handle(parent); + append(".").append(property); + } else { + // field access by reflection + append(CollQueryFunctions.class.getName() + ".<"); + append((path.getType()).getName()).append(">get("); + handle(parent); + append(", \"" + property + "\")"); + } } - return null; - - } - - private Method getAccessor(Class owner, String property) { - try { - BeanInfo beanInfo = Introspector.getBeanInfo(owner); - PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor pd : descriptors) { - if (pd.getName().equals(property)) { - return pd.getReadMethod(); - } - } - return null; - } catch (IntrospectionException e) { - return null; + } catch (Exception e) { + throw new QueryException(e); + } + + } else if (pathType == PathType.DELEGATE) { + append("("); + append("(").append(path.getType().getName()).append(")"); + path.getMetadata().getParent().accept(this, context); + append(")"); + + } else { + List args = new ArrayList(2); + if (path.getMetadata().getParent() != null) { + args.add(path.getMetadata().getParent()); + } + args.add(path.getMetadata().getElement()); + final Template template = getTemplate(pathType); + for (Template.Element element : template.getElements()) { + Object rv = element.convert(args); + if (rv instanceof Expression) { + ((Expression) rv).accept(this, context); + } else if (element.isString()) { + append(rv.toString()); + } else { + visitConstant(rv); } + } } - - private Field getField(Class owner, String field) { - try { - return owner.getField(field); - } catch (NoSuchFieldException e) { - return null; + return null; + } + + private Method getAccessor(Class owner, String property) { + try { + BeanInfo beanInfo = Introspector.getBeanInfo(owner); + PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor pd : descriptors) { + if (pd.getName().equals(property)) { + return pd.getReadMethod(); } + } + return null; + } catch (IntrospectionException e) { + return null; } + } - @Override - public Void visit(SubQueryExpression expr, Void context) { - throw new IllegalArgumentException("Not supported"); + private Field getField(Class owner, String field) { + try { + return owner.getField(field); + } catch (NoSuchFieldException e) { + return null; } - - private void visitCast(Operator operator, Expression source, Class targetType) { - if (Number.class.isAssignableFrom(source.getType()) && !Constant.class.isInstance(source)) { - append("new ").append(source.getType().getSimpleName()).append("("); - handle(source); - append(")"); - } else { - handle(source); - } - - if (CAST_SUFFIXES.containsKey(targetType)) { - append(CAST_SUFFIXES.get(targetType)); - } else { - throw new IllegalArgumentException("Unsupported cast type " + targetType.getName()); - } + } + + @Override + public Void visit(SubQueryExpression expr, Void context) { + throw new IllegalArgumentException("Not supported"); + } + + private void visitCast(Operator operator, Expression source, Class targetType) { + if (Number.class.isAssignableFrom(source.getType()) && !Constant.class.isInstance(source)) { + append("new ").append(source.getType().getSimpleName()).append("("); + handle(source); + append(")"); + } else { + handle(source); } - @Override - protected void visitOperation(Class type, Operator operator, List> args) { - if (Ops.aggOps.contains(operator)) { - throw new UnsupportedOperationException("Aggregation operators are only supported as single expressions"); - } - if (args.size() == 2 && OPERATOR_SYMBOLS.containsKey(operator) - && isPrimitiveOrWrapperType(args.get(0).getType()) && isPrimitiveOrWrapperType(args.get(1).getType())) { - handle(args.get(0)); - append(OPERATOR_SYMBOLS.get(operator)); - handle(args.get(1)); - if (args.get(1) instanceof Constant) { - append(CAST_SUFFIXES.get(args.get(1).getType())); - } - return; - } - - if (operator == Ops.STRING_CAST) { - visitCast(operator, args.get(0), String.class); - } else if (operator == Ops.NUMCAST) { - @SuppressWarnings("unchecked") //this is the second argument's type - Constant> rightArg = (Constant>) args.get(1); - - visitCast(operator, args.get(0), rightArg.getConstant()); - } else { - super.visitOperation(type, operator, args); - } + if (CAST_SUFFIXES.containsKey(targetType)) { + append(CAST_SUFFIXES.get(targetType)); + } else { + throw new IllegalArgumentException("Unsupported cast type " + targetType.getName()); } - - private static boolean isPrimitiveOrWrapperType(Class type) { - return type.isPrimitive() || PrimitiveUtils.isWrapperType(type); + } + + @Override + protected void visitOperation( + Class type, Operator operator, List> args) { + if (Ops.aggOps.contains(operator)) { + throw new UnsupportedOperationException( + "Aggregation operators are only supported as single expressions"); } - - @Override - public Void visit(FactoryExpression expr, Void context) { - visitConstant(expr); - append(".newInstance("); - append("new Object[] {"); - handle(", ", expr.getArgs()); - append("})"); - return null; + if (args.size() == 2 + && OPERATOR_SYMBOLS.containsKey(operator) + && isPrimitiveOrWrapperType(args.get(0).getType()) + && isPrimitiveOrWrapperType(args.get(1).getType())) { + handle(args.get(0)); + append(OPERATOR_SYMBOLS.get(operator)); + handle(args.get(1)); + if (args.get(1) instanceof Constant) { + append(CAST_SUFFIXES.get(args.get(1).getType())); + } + return; } + if (operator == Ops.STRING_CAST) { + visitCast(operator, args.get(0), String.class); + } else if (operator == Ops.NUMCAST) { + @SuppressWarnings("unchecked") // this is the second argument's type + Constant> rightArg = (Constant>) args.get(1); + + visitCast(operator, args.get(0), rightArg.getConstant()); + } else { + super.visitOperation(type, operator, args); + } + } + + private static boolean isPrimitiveOrWrapperType(Class type) { + return type.isPrimitive() || PrimitiveUtils.isWrapperType(type); + } + + @Override + public Void visit(FactoryExpression expr, Void context) { + visitConstant(expr); + append(".newInstance("); + append("new Object[] {"); + handle(", ", expr.getArgs()); + append("})"); + return null; + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryTemplates.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryTemplates.java index 8fa66af6de..e2e074a094 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryTemplates.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollQueryTemplates.java @@ -25,74 +25,71 @@ */ public class CollQueryTemplates extends JavaTemplates { - @SuppressWarnings("FieldNameHidesFieldInSuperclass") //intentional - public static final CollQueryTemplates DEFAULT = new CollQueryTemplates(); + @SuppressWarnings("FieldNameHidesFieldInSuperclass") // intentional + public static final CollQueryTemplates DEFAULT = new CollQueryTemplates(); - protected CollQueryTemplates() { - String functions = CollQueryFunctions.class.getName(); - add(Ops.EQ, functions + ".equals({0}, {1})"); - add(Ops.NE, "!" + functions + ".equals({0}, {1})"); - add(Ops.INSTANCE_OF, "{1}.isInstance({0})"); + protected CollQueryTemplates() { + String functions = CollQueryFunctions.class.getName(); + add(Ops.EQ, functions + ".equals({0}, {1})"); + add(Ops.NE, "!" + functions + ".equals({0}, {1})"); + add(Ops.INSTANCE_OF, "{1}.isInstance({0})"); - // Comparable - add(Ops.GT, functions + ".compareTo({0}, {1}) > 0"); - add(Ops.LT, functions + ".compareTo({0}, {1}) < 0"); - add(Ops.GOE, functions + ".compareTo({0}, {1}) >= 0"); - add(Ops.LOE, functions + ".compareTo({0}, {1}) <= 0"); - add(Ops.BETWEEN, functions + ".between({0}, {1}, {2})"); - add(Ops.STRING_CAST, "String.valueOf({0})"); + // Comparable + add(Ops.GT, functions + ".compareTo({0}, {1}) > 0"); + add(Ops.LT, functions + ".compareTo({0}, {1}) < 0"); + add(Ops.GOE, functions + ".compareTo({0}, {1}) >= 0"); + add(Ops.LOE, functions + ".compareTo({0}, {1}) <= 0"); + add(Ops.BETWEEN, functions + ".between({0}, {1}, {2})"); + add(Ops.STRING_CAST, "String.valueOf({0})"); - // Number - add(Ops.MathOps.COT, functions + ".cot({0})"); - add(Ops.MathOps.COTH, functions + ".coth({0})"); - add(Ops.MathOps.DEG, functions + ".degrees({0})"); - add(Ops.MathOps.LN, "Math.log({0})"); - add(Ops.MathOps.LOG, functions + ".log({0},{1})"); - add(Ops.MathOps.RAD, functions + ".radians({0})"); - add(Ops.MathOps.SIGN, "{0} > 0 ? 1 : -1"); + // Number + add(Ops.MathOps.COT, functions + ".cot({0})"); + add(Ops.MathOps.COTH, functions + ".coth({0})"); + add(Ops.MathOps.DEG, functions + ".degrees({0})"); + add(Ops.MathOps.LN, "Math.log({0})"); + add(Ops.MathOps.LOG, functions + ".log({0},{1})"); + add(Ops.MathOps.RAD, functions + ".radians({0})"); + add(Ops.MathOps.SIGN, "{0} > 0 ? 1 : -1"); - add(Ops.ADD, "{0}.add({1})"); - add(Ops.SUB, "{0}.subtract({1})"); - add(Ops.MULT, "{0}.multiply({1})"); - add(Ops.DIV, "{0}.divide({1})"); + add(Ops.ADD, "{0}.add({1})"); + add(Ops.SUB, "{0}.subtract({1})"); + add(Ops.MULT, "{0}.multiply({1})"); + add(Ops.DIV, "{0}.divide({1})"); - // Date and Time - add(Ops.DateTimeOps.YEAR, functions + ".getYear({0})"); - add(Ops.DateTimeOps.MONTH, functions + ".getMonth({0})"); - add(Ops.DateTimeOps.WEEK, functions + ".getWeek({0})"); - add(Ops.DateTimeOps.DAY_OF_WEEK, functions + ".getDayOfWeek({0})"); - add(Ops.DateTimeOps.DAY_OF_MONTH, functions + ".getDayOfMonth({0})"); - add(Ops.DateTimeOps.DAY_OF_YEAR, functions + ".getDayOfYear({0})"); - add(Ops.DateTimeOps.HOUR, functions + ".getHour({0})"); - add(Ops.DateTimeOps.MINUTE, functions + ".getMinute({0})"); - add(Ops.DateTimeOps.SECOND, functions + ".getSecond({0})"); - add(Ops.DateTimeOps.MILLISECOND, functions + ".getMilliSecond({0})"); + // Date and Time + add(Ops.DateTimeOps.YEAR, functions + ".getYear({0})"); + add(Ops.DateTimeOps.MONTH, functions + ".getMonth({0})"); + add(Ops.DateTimeOps.WEEK, functions + ".getWeek({0})"); + add(Ops.DateTimeOps.DAY_OF_WEEK, functions + ".getDayOfWeek({0})"); + add(Ops.DateTimeOps.DAY_OF_MONTH, functions + ".getDayOfMonth({0})"); + add(Ops.DateTimeOps.DAY_OF_YEAR, functions + ".getDayOfYear({0})"); + add(Ops.DateTimeOps.HOUR, functions + ".getHour({0})"); + add(Ops.DateTimeOps.MINUTE, functions + ".getMinute({0})"); + add(Ops.DateTimeOps.SECOND, functions + ".getSecond({0})"); + add(Ops.DateTimeOps.MILLISECOND, functions + ".getMilliSecond({0})"); - add(Ops.DateTimeOps.YEAR_MONTH, functions + ".getYearMonth({0})"); - add(Ops.DateTimeOps.YEAR_WEEK, functions + ".getYearWeek({0})"); + add(Ops.DateTimeOps.YEAR_MONTH, functions + ".getYearMonth({0})"); + add(Ops.DateTimeOps.YEAR_WEEK, functions + ".getYearWeek({0})"); - // String - add(Ops.LIKE, functions + ".like({0},{1})"); - add(Ops.LIKE_IC, functions + ".likeIgnoreCase({0},{1})"); - add(Ops.LIKE_ESCAPE, functions + ".like({0},{1},{2})"); - add(Ops.LIKE_ESCAPE_IC, functions + ".likeIgnoreCase({0},{1},{2})"); + // String + add(Ops.LIKE, functions + ".like({0},{1})"); + add(Ops.LIKE_IC, functions + ".likeIgnoreCase({0},{1})"); + add(Ops.LIKE_ESCAPE, functions + ".like({0},{1},{2})"); + add(Ops.LIKE_ESCAPE_IC, functions + ".likeIgnoreCase({0},{1},{2})"); - // Path types - for (PathType type : new PathType[] { - PathType.LISTVALUE, - PathType.MAPVALUE, - PathType.MAPVALUE_CONSTANT }) { - add(type, "{0}.get({1})"); - } - add(PathType.LISTVALUE_CONSTANT, "{0}.get({1})"); - add(PathType.ARRAYVALUE, "{0}[{1}]"); - add(PathType.ARRAYVALUE_CONSTANT, "{0}[{1}]"); - add(PathType.COLLECTION_ANY, "{0}_any"); - - // coalesce - add(Ops.COALESCE, functions + ".coalesce({0})"); - - add(Ops.NULLIF, functions + ".nullif({0}, {1})"); + // Path types + for (PathType type : + new PathType[] {PathType.LISTVALUE, PathType.MAPVALUE, PathType.MAPVALUE_CONSTANT}) { + add(type, "{0}.get({1})"); } + add(PathType.LISTVALUE_CONSTANT, "{0}.get({1})"); + add(PathType.ARRAYVALUE, "{0}[{1}]"); + add(PathType.ARRAYVALUE_CONSTANT, "{0}[{1}]"); + add(PathType.COLLECTION_ANY, "{0}_any"); + + // coalesce + add(Ops.COALESCE, functions + ".coalesce({0})"); + add(Ops.NULLIF, functions + ".nullif({0}, {1})"); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/CollUpdateClause.java b/querydsl-collections/src/main/java/com/querydsl/collections/CollUpdateClause.java index 55ebb9e36c..9dd37a1779 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/CollUpdateClause.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/CollUpdateClause.java @@ -13,94 +13,90 @@ */ package com.querydsl.collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.querydsl.core.dml.UpdateClause; import com.querydsl.core.types.Expression; import com.querydsl.core.types.Path; import com.querydsl.core.types.Predicate; import com.querydsl.core.util.BeanMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** - * {@code CollUpdateClause} is an implementation of the {@link UpdateClause} interface for Querydsl Collections + * {@code CollUpdateClause} is an implementation of the {@link UpdateClause} interface for Querydsl + * Collections * * @author tiwe - * * @param */ public class CollUpdateClause implements UpdateClause> { - private final Map, Object> paths = new HashMap, Object>(); - - private final CollQuery query; - - public CollUpdateClause(QueryEngine qe, Path expr, Iterable col) { - this.query = new CollQuery(qe).from(expr, col).select(expr); - } - - public CollUpdateClause(Path expr, Iterable col) { - this(DefaultQueryEngine.getDefault(), expr, col); - } - - @Override - public long execute() { - int rv = 0; - for (T match : query.fetch()) { - BeanMap beanMap = new BeanMap(match); - for (Map.Entry,Object> entry : paths.entrySet()) { - // TODO : support deep updates as well - String propertyName = entry.getKey().getMetadata().getName(); - beanMap.put(propertyName, entry.getValue()); - } - rv++; - } - return rv; - } - - @Override - public CollUpdateClause set(Path path, U value) { - paths.put(path, value); - return this; - } - - - @Override - public CollUpdateClause set(Path path, Expression expression) { - // TODO : implement - throw new UnsupportedOperationException(); + private final Map, Object> paths = new HashMap, Object>(); + + private final CollQuery query; + + public CollUpdateClause(QueryEngine qe, Path expr, Iterable col) { + this.query = new CollQuery(qe).from(expr, col).select(expr); + } + + public CollUpdateClause(Path expr, Iterable col) { + this(DefaultQueryEngine.getDefault(), expr, col); + } + + @Override + public long execute() { + int rv = 0; + for (T match : query.fetch()) { + BeanMap beanMap = new BeanMap(match); + for (Map.Entry, Object> entry : paths.entrySet()) { + // TODO : support deep updates as well + String propertyName = entry.getKey().getMetadata().getName(); + beanMap.put(propertyName, entry.getValue()); + } + rv++; } - - @Override - public CollUpdateClause setNull(Path path) { - paths.put(path, null); - return this; - } - - @Override - public CollUpdateClause set(List> p, List v) { - for (int i = 0; i < p.size(); i++) { - paths.put(p.get(i), v.get(i)); - } - return this; + return rv; + } + + @Override + public CollUpdateClause set(Path path, U value) { + paths.put(path, value); + return this; + } + + @Override + public CollUpdateClause set(Path path, Expression expression) { + // TODO : implement + throw new UnsupportedOperationException(); + } + + @Override + public CollUpdateClause setNull(Path path) { + paths.put(path, null); + return this; + } + + @Override + public CollUpdateClause set(List> p, List v) { + for (int i = 0; i < p.size(); i++) { + paths.put(p.get(i), v.get(i)); } - - @Override - public CollUpdateClause where(Predicate... o) { - query.where(o); - return this; - } - - @Override - public String toString() { - return "update " + query; - } - - @Override - public boolean isEmpty() { - return paths.isEmpty(); - } - - + return this; + } + + @Override + public CollUpdateClause where(Predicate... o) { + query.where(o); + return this; + } + + @Override + public String toString() { + return "update " + query; + } + + @Override + public boolean isEmpty() { + return paths.isEmpty(); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/DefaultEvaluatorFactory.java b/querydsl-collections/src/main/java/com/querydsl/collections/DefaultEvaluatorFactory.java index 5e460c3ed1..2ac4310b8d 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/DefaultEvaluatorFactory.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/DefaultEvaluatorFactory.java @@ -35,264 +35,267 @@ import com.querydsl.core.types.ParamNotSetException; import com.querydsl.core.types.Predicate; import com.querydsl.core.util.PrimitiveUtils; -import org.jetbrains.annotations.Nullable; - -import javax.tools.JavaCompiler; -import javax.tools.ToolProvider; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; +import org.jetbrains.annotations.Nullable; /** - * {@code DefaultEvaluatorFactory} provides Java source templates for evaluation of {@link CollQuery} queries + * {@code DefaultEvaluatorFactory} provides Java source templates for evaluation of {@link + * CollQuery} queries * * @author tiwe - * */ public class DefaultEvaluatorFactory { - private final EvaluatorFactory factory; + private final EvaluatorFactory factory; - private final CollQueryTemplates templates; + private final CollQueryTemplates templates; - private final CollectionAnyVisitor collectionAnyVisitor = new CollectionAnyVisitor(); + private final CollectionAnyVisitor collectionAnyVisitor = new CollectionAnyVisitor(); - public DefaultEvaluatorFactory(CollQueryTemplates templates) { - this(templates, - Thread.currentThread().getContextClassLoader() != null ? Thread.currentThread().getContextClassLoader() : DefaultEvaluatorFactory.class.getClassLoader()); - } + public DefaultEvaluatorFactory(CollQueryTemplates templates) { + this( + templates, + Thread.currentThread().getContextClassLoader() != null + ? Thread.currentThread().getContextClassLoader() + : DefaultEvaluatorFactory.class.getClassLoader()); + } - public DefaultEvaluatorFactory(CollQueryTemplates templates, EvaluatorFactory factory) { - this.templates = templates; - this.factory = factory; - } + public DefaultEvaluatorFactory(CollQueryTemplates templates, EvaluatorFactory factory) { + this.templates = templates; + this.factory = factory; + } - protected DefaultEvaluatorFactory(CollQueryTemplates templates, - URLClassLoader classLoader, JavaCompiler compiler) { - this.templates = templates; - this.factory = new JDKEvaluatorFactory(classLoader, compiler); - } + protected DefaultEvaluatorFactory( + CollQueryTemplates templates, URLClassLoader classLoader, JavaCompiler compiler) { + this.templates = templates; + this.factory = new JDKEvaluatorFactory(classLoader, compiler); + } - protected DefaultEvaluatorFactory(CollQueryTemplates templates, ClassLoader classLoader) { - this.templates = templates; - final JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); - if (classLoader instanceof URLClassLoader && systemJavaCompiler != null) { - this.factory = new JDKEvaluatorFactory((URLClassLoader) classLoader, systemJavaCompiler); - } else { - // for OSGi and JRE compatibility - this.factory = new ECJEvaluatorFactory(classLoader); - } + protected DefaultEvaluatorFactory(CollQueryTemplates templates, ClassLoader classLoader) { + this.templates = templates; + final JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); + if (classLoader instanceof URLClassLoader && systemJavaCompiler != null) { + this.factory = new JDKEvaluatorFactory((URLClassLoader) classLoader, systemJavaCompiler); + } else { + // for OSGi and JRE compatibility + this.factory = new ECJEvaluatorFactory(classLoader); } + } - /** - * Create an Evaluator for the given query sources and projection - * - * @param - * @param metadata query metadata - * @param sources sources of the query - * @param projection projection of the query - * @return evaluator - */ - public Evaluator create(QueryMetadata metadata, List> sources, - Expression projection) { - final CollQuerySerializer serializer = new CollQuerySerializer(templates); - serializer.append("return "); - if (projection instanceof FactoryExpression) { - serializer.append("("); - serializer.append(ClassUtils.getName(projection.getType())); - serializer.append(")("); - serializer.handle(projection); - serializer.append(")"); - } else { - serializer.handle(projection); - } - serializer.append(";"); - - Map constantToLabel = serializer.getConstantToLabel(); - Map constants = getConstants(metadata, constantToLabel); - Class[] types = new Class[sources.size()]; - String[] names = new String[sources.size()]; - for (int i = 0; i < sources.size(); i++) { - types[i] = sources.get(i).getType(); - names[i] = sources.get(i).toString(); - } - - // normalize types - for (int i = 0; i < types.length; i++) { - if (PrimitiveUtils.isWrapperType(types[i])) { - types[i] = PrimitiveUtils.unwrap(types[i]); - } - } + /** + * Create an Evaluator for the given query sources and projection + * + * @param + * @param metadata query metadata + * @param sources sources of the query + * @param projection projection of the query + * @return evaluator + */ + public Evaluator create( + QueryMetadata metadata, List> sources, Expression projection) { + final CollQuerySerializer serializer = new CollQuerySerializer(templates); + serializer.append("return "); + if (projection instanceof FactoryExpression) { + serializer.append("("); + serializer.append(ClassUtils.getName(projection.getType())); + serializer.append(")("); + serializer.handle(projection); + serializer.append(")"); + } else { + serializer.handle(projection); + } + serializer.append(";"); - return factory.createEvaluator(serializer.toString(), projection.getType(), names, - types, constants); + Map constantToLabel = serializer.getConstantToLabel(); + Map constants = getConstants(metadata, constantToLabel); + Class[] types = new Class[sources.size()]; + String[] names = new String[sources.size()]; + for (int i = 0; i < sources.size(); i++) { + types[i] = sources.get(i).getType(); + names[i] = sources.get(i).toString(); } - /** - * Create an Evaluator for the given source and filter - * - * @param - * @param source source of the query - * @param filter filter of the query - * @return evaluator - */ - public Evaluator> createEvaluator(QueryMetadata metadata, - Expression source, Predicate filter) { - String typeName = ClassUtils.getName(source.getType()); - CollQuerySerializer ser = new CollQuerySerializer(templates); - ser.append("java.util.List<" + typeName + "> rv = new java.util.ArrayList<" + typeName + ">();\n"); - ser.append("for (" + typeName + " " + source + " : " + source + "_) {\n"); - ser.append(" try {\n"); - ser.append(" if (").handle(filter).append(") {\n"); - ser.append(" rv.add(" + source + ");\n"); - ser.append(" }\n"); - ser.append(" } catch (NullPointerException npe) { }\n"); - ser.append("}\n"); - ser.append("return rv;"); + // normalize types + for (int i = 0; i < types.length; i++) { + if (PrimitiveUtils.isWrapperType(types[i])) { + types[i] = PrimitiveUtils.unwrap(types[i]); + } + } - Map constantToLabel = ser.getConstantToLabel(); - Map constants = getConstants(metadata, constantToLabel); + return factory.createEvaluator( + serializer.toString(), projection.getType(), names, types, constants); + } - Type sourceType = new ClassType(TypeCategory.SIMPLE, source.getType()); - ClassType sourceListType = new ClassType(TypeCategory.SIMPLE, Iterable.class, sourceType); + /** + * Create an Evaluator for the given source and filter + * + * @param + * @param source source of the query + * @param filter filter of the query + * @return evaluator + */ + public Evaluator> createEvaluator( + QueryMetadata metadata, Expression source, Predicate filter) { + String typeName = ClassUtils.getName(source.getType()); + CollQuerySerializer ser = new CollQuerySerializer(templates); + ser.append( + "java.util.List<" + typeName + "> rv = new java.util.ArrayList<" + typeName + ">();\n"); + ser.append("for (" + typeName + " " + source + " : " + source + "_) {\n"); + ser.append(" try {\n"); + ser.append(" if (").handle(filter).append(") {\n"); + ser.append(" rv.add(" + source + ");\n"); + ser.append(" }\n"); + ser.append(" } catch (NullPointerException npe) { }\n"); + ser.append("}\n"); + ser.append("return rv;"); - return factory.createEvaluator( - ser.toString(), - sourceListType, - new String[]{source + "_"}, - new Type[]{sourceListType}, - new Class[]{Iterable.class}, - constants); - } + Map constantToLabel = ser.getConstantToLabel(); + Map constants = getConstants(metadata, constantToLabel); - /** - * Create an Evaluator for the given sources and the given optional filter - * - * @param metadata query metadata - * @param joins joins - * @param filter where condition - * @return evaluator - */ - public Evaluator> createEvaluator(QueryMetadata metadata, - List joins, @Nullable Predicate filter) { - List sourceNames = new ArrayList(); - List sourceTypes = new ArrayList(); - List> sourceClasses = new ArrayList>(); - StringBuilder vars = new StringBuilder(); - CollQuerySerializer ser = new CollQuerySerializer(templates); - ser.append("java.util.List rv = new java.util.ArrayList();\n"); + Type sourceType = new ClassType(TypeCategory.SIMPLE, source.getType()); + ClassType sourceListType = new ClassType(TypeCategory.SIMPLE, Iterable.class, sourceType); - List anyJoinMatchers = new ArrayList(); + return factory.createEvaluator( + ser.toString(), + sourceListType, + new String[] {source + "_"}, + new Type[] {sourceListType}, + new Class[] {Iterable.class}, + constants); + } - // creating context - for (JoinExpression join : joins) { - Expression target = join.getTarget(); - String typeName = com.querydsl.codegen.utils.support.ClassUtils.getName(target.getType()); - if (vars.length() > 0) { - vars.append(","); - } - switch (join.getType()) { - case DEFAULT: - ser.append("for (" + typeName + " " + target + " : " + target + "_) {\n"); - vars.append(target); - sourceNames.add(target + "_"); - sourceTypes.add(new SimpleType(Types.ITERABLE, new ClassType(TypeCategory.SIMPLE,target.getType()))); - sourceClasses.add(Iterable.class); - break; + /** + * Create an Evaluator for the given sources and the given optional filter + * + * @param metadata query metadata + * @param joins joins + * @param filter where condition + * @return evaluator + */ + public Evaluator> createEvaluator( + QueryMetadata metadata, List joins, @Nullable Predicate filter) { + List sourceNames = new ArrayList(); + List sourceTypes = new ArrayList(); + List> sourceClasses = new ArrayList>(); + StringBuilder vars = new StringBuilder(); + CollQuerySerializer ser = new CollQuerySerializer(templates); + ser.append("java.util.List rv = new java.util.ArrayList();\n"); - case INNERJOIN: - case LEFTJOIN: - Operation alias = (Operation) join.getTarget(); - boolean colAnyJoin = join.getCondition() != null && join.getCondition().toString().equals("any"); - boolean leftJoin = join.getType() == JoinType.LEFTJOIN; - String matcher = null; - if (colAnyJoin) { - matcher = alias.getArg(1).toString() + "_matched"; - ser.append("boolean " + matcher + " = false;\n"); - anyJoinMatchers.add(matcher); - } - ser.append("for (" + typeName + " " + alias.getArg(1) + " : "); - if (leftJoin) { - ser.append(CollQueryFunctions.class.getName() + ".leftJoin("); - } - if (colAnyJoin) { - Context context = new Context(); - Expression replacement = alias.getArg(0) - .accept(collectionAnyVisitor, context); - ser.handle(replacement); - } else { - ser.handle(alias.getArg(0)); - } - if (alias.getArg(0).getType().equals(Map.class)) { - ser.append(".values()"); - } - if (leftJoin) { - ser.append(")"); - } - ser.append(") {\n"); - if (matcher != null) { - ser.append("if (!" + matcher + ") {\n"); - } - vars.append(alias.getArg(1)); - break; + List anyJoinMatchers = new ArrayList(); - default: - throw new IllegalArgumentException("Illegal join expression " + join); - } - } + // creating context + for (JoinExpression join : joins) { + Expression target = join.getTarget(); + String typeName = com.querydsl.codegen.utils.support.ClassUtils.getName(target.getType()); + if (vars.length() > 0) { + vars.append(","); + } + switch (join.getType()) { + case DEFAULT: + ser.append("for (" + typeName + " " + target + " : " + target + "_) {\n"); + vars.append(target); + sourceNames.add(target + "_"); + sourceTypes.add( + new SimpleType(Types.ITERABLE, new ClassType(TypeCategory.SIMPLE, target.getType()))); + sourceClasses.add(Iterable.class); + break; - // filter - if (filter != null) { - ser.append("try {\n"); - ser.append("if ("); - ser.handle(filter).append(") {\n"); - for (String matcher : anyJoinMatchers) { - ser.append(" " + matcher + " = true;\n"); - } - ser.append(" rv.add(new Object[]{" + vars + "});\n"); - ser.append("}\n"); - ser.append("} catch (NullPointerException npe) { }\n"); - } else { - ser.append("rv.add(new Object[]{" + vars + "});\n"); - } + case INNERJOIN: + case LEFTJOIN: + Operation alias = (Operation) join.getTarget(); + boolean colAnyJoin = + join.getCondition() != null && join.getCondition().toString().equals("any"); + boolean leftJoin = join.getType() == JoinType.LEFTJOIN; + String matcher = null; + if (colAnyJoin) { + matcher = alias.getArg(1).toString() + "_matched"; + ser.append("boolean " + matcher + " = false;\n"); + anyJoinMatchers.add(matcher); + } + ser.append("for (" + typeName + " " + alias.getArg(1) + " : "); + if (leftJoin) { + ser.append(CollQueryFunctions.class.getName() + ".leftJoin("); + } + if (colAnyJoin) { + Context context = new Context(); + Expression replacement = alias.getArg(0).accept(collectionAnyVisitor, context); + ser.handle(replacement); + } else { + ser.handle(alias.getArg(0)); + } + if (alias.getArg(0).getType().equals(Map.class)) { + ser.append(".values()"); + } + if (leftJoin) { + ser.append(")"); + } + ser.append(") {\n"); + if (matcher != null) { + ser.append("if (!" + matcher + ") {\n"); + } + vars.append(alias.getArg(1)); + break; - // closing context - int amount = joins.size() + anyJoinMatchers.size(); - for (int i = 0; i < amount; i++) { - ser.append("}\n"); - } - ser.append("return rv;"); + default: + throw new IllegalArgumentException("Illegal join expression " + join); + } + } - Map constantToLabel = ser.getConstantToLabel(); - Map constants = getConstants(metadata, constantToLabel); + // filter + if (filter != null) { + ser.append("try {\n"); + ser.append("if ("); + ser.handle(filter).append(") {\n"); + for (String matcher : anyJoinMatchers) { + ser.append(" " + matcher + " = true;\n"); + } + ser.append(" rv.add(new Object[]{" + vars + "});\n"); + ser.append("}\n"); + ser.append("} catch (NullPointerException npe) { }\n"); + } else { + ser.append("rv.add(new Object[]{" + vars + "});\n"); + } - ClassType projectionType = new ClassType(TypeCategory.LIST, List.class, Types.OBJECTS); - return factory.createEvaluator( - ser.toString(), - projectionType, - sourceNames.toArray(new String[0]), - sourceTypes.toArray(new Type[0]), - sourceClasses.toArray(new Class[0]), - constants); + // closing context + int amount = joins.size() + anyJoinMatchers.size(); + for (int i = 0; i < amount; i++) { + ser.append("}\n"); } + ser.append("return rv;"); - private Map getConstants(QueryMetadata metadata, - Map constantToLabel) { - Map constants = new HashMap(); - for (Map.Entry entry : constantToLabel.entrySet()) { - if (entry.getKey() instanceof ParamExpression) { - Object value = metadata.getParams().get(entry.getKey()); - if (value == null) { - throw new ParamNotSetException((ParamExpression) entry.getKey()); - } - constants.put(entry.getValue(), value); - } else { - constants.put(entry.getValue(), entry.getKey()); - } + Map constantToLabel = ser.getConstantToLabel(); + Map constants = getConstants(metadata, constantToLabel); + + ClassType projectionType = new ClassType(TypeCategory.LIST, List.class, Types.OBJECTS); + return factory.createEvaluator( + ser.toString(), + projectionType, + sourceNames.toArray(new String[0]), + sourceTypes.toArray(new Type[0]), + sourceClasses.toArray(new Class[0]), + constants); + } + + private Map getConstants( + QueryMetadata metadata, Map constantToLabel) { + Map constants = new HashMap(); + for (Map.Entry entry : constantToLabel.entrySet()) { + if (entry.getKey() instanceof ParamExpression) { + Object value = metadata.getParams().get(entry.getKey()); + if (value == null) { + throw new ParamNotSetException((ParamExpression) entry.getKey()); } - return constants; + constants.put(entry.getValue(), value); + } else { + constants.put(entry.getValue(), entry.getKey()); + } } - + return constants; + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/DefaultQueryEngine.java b/querydsl-collections/src/main/java/com/querydsl/collections/DefaultQueryEngine.java index e09247cdf1..9ea5895b72 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/DefaultQueryEngine.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/DefaultQueryEngine.java @@ -13,8 +13,8 @@ */ package com.querydsl.collections; -import com.querydsl.codegen.utils.Evaluator; import com.mysema.commons.lang.IteratorAdapter; +import com.querydsl.codegen.utils.Evaluator; import com.querydsl.core.JoinExpression; import com.querydsl.core.JoinType; import com.querydsl.core.QueryMetadata; @@ -26,7 +26,6 @@ import com.querydsl.core.types.Ops; import com.querydsl.core.types.Order; import com.querydsl.core.types.OrderSpecifier; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -40,209 +39,208 @@ * Default implementation of the {@link QueryEngine} interface * * @author tiwe - * */ @SuppressWarnings("unchecked") public class DefaultQueryEngine implements QueryEngine { - private static transient volatile QueryEngine defaultQueryEngine; + private static transient volatile QueryEngine defaultQueryEngine; - public static QueryEngine getDefault() { - if (defaultQueryEngine == null) { - defaultQueryEngine = new DefaultQueryEngine(new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT)); - } - return defaultQueryEngine; + public static QueryEngine getDefault() { + if (defaultQueryEngine == null) { + defaultQueryEngine = + new DefaultQueryEngine(new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT)); } + return defaultQueryEngine; + } - private final DefaultEvaluatorFactory evaluatorFactory; + private final DefaultEvaluatorFactory evaluatorFactory; - public DefaultQueryEngine(DefaultEvaluatorFactory evaluatorFactory) { - this.evaluatorFactory = evaluatorFactory; - } - - @Override - public long count(QueryMetadata metadata, Map, Iterable> iterables) { - if (metadata.getJoins().size() == 1) { - return evaluateSingleSource(metadata, iterables, true).size(); - } else { - return evaluateMultipleSources(metadata, iterables, true).size(); - } - } + public DefaultQueryEngine(DefaultEvaluatorFactory evaluatorFactory) { + this.evaluatorFactory = evaluatorFactory; + } - @Override - public boolean exists(QueryMetadata metadata, Map, Iterable> iterables) { - QueryModifiers modifiers = metadata.getModifiers(); - metadata.setLimit(1L); - try { - if (metadata.getJoins().size() == 1) { - return !evaluateSingleSource(metadata, iterables, true).isEmpty(); - } else { - return !evaluateMultipleSources(metadata, iterables, true).isEmpty(); - } - } finally { - metadata.setModifiers(modifiers); - } + @Override + public long count(QueryMetadata metadata, Map, Iterable> iterables) { + if (metadata.getJoins().size() == 1) { + return evaluateSingleSource(metadata, iterables, true).size(); + } else { + return evaluateMultipleSources(metadata, iterables, true).size(); } - - @Override - public List list(QueryMetadata metadata, Map, Iterable> iterables, - Expression projection) { - if (metadata.getJoins().size() == 1) { - return evaluateSingleSource(metadata, iterables, false); - } else { - return evaluateMultipleSources(metadata, iterables, false); - } + } + + @Override + public boolean exists(QueryMetadata metadata, Map, Iterable> iterables) { + QueryModifiers modifiers = metadata.getModifiers(); + metadata.setLimit(1L); + try { + if (metadata.getJoins().size() == 1) { + return !evaluateSingleSource(metadata, iterables, true).isEmpty(); + } else { + return !evaluateMultipleSources(metadata, iterables, true).isEmpty(); + } + } finally { + metadata.setModifiers(modifiers); } - - private List distinct(List list) { - List rv = new ArrayList(list.size()); - if (!list.isEmpty() && list.get(0) != null && list.get(0).getClass().isArray()) { - Set set = new HashSet(list.size()); - for (T o : list) { - if (set.add(Collections.unmodifiableList(Arrays.asList((Object[]) o)))) { - rv.add(o); - } - } - return rv; - } else { - for (T o : list) { - if (!rv.contains(o)) { - rv.add(o); - } - } - } - return rv; + } + + @Override + public List list( + QueryMetadata metadata, Map, Iterable> iterables, Expression projection) { + if (metadata.getJoins().size() == 1) { + return evaluateSingleSource(metadata, iterables, false); + } else { + return evaluateMultipleSources(metadata, iterables, false); } - - private List evaluateMultipleSources(QueryMetadata metadata, Map, - Iterable> iterables, boolean count) { - // from where - Evaluator> ev = evaluatorFactory.createEvaluator(metadata, metadata.getJoins(), metadata.getWhere()); - List> iterableList = new ArrayList>(metadata.getJoins().size()); - for (JoinExpression join : metadata.getJoins()) { - if (join.getType() == JoinType.DEFAULT) { - iterableList.add(iterables.get(join.getTarget())); - } + } + + private List distinct(List list) { + List rv = new ArrayList(list.size()); + if (!list.isEmpty() && list.get(0) != null && list.get(0).getClass().isArray()) { + Set set = new HashSet(list.size()); + for (T o : list) { + if (set.add(Collections.unmodifiableList(Arrays.asList((Object[]) o)))) { + rv.add(o); } - List list = ev.evaluate(iterableList.toArray()); - - if (!count && !list.isEmpty()) { - List> sources = new ArrayList>(metadata.getJoins().size()); - for (JoinExpression join : metadata.getJoins()) { - if (join.getType() == JoinType.DEFAULT) { - sources.add(join.getTarget()); - } else { - Operation target = (Operation) join.getTarget(); - sources.add(target.getArg(1)); - } - } - // ordered - if (!metadata.getOrderBy().isEmpty()) { - order(metadata, sources, list); - } - // projection - list = project(metadata, sources, list); - // limit + offset - if (metadata.getModifiers().isRestricting()) { - list = metadata.getModifiers().subList(list); - } - if (list.isEmpty()) { - return list; - } + } + return rv; + } else { + for (T o : list) { + if (!rv.contains(o)) { + rv.add(o); } + } + } + return rv; + } + + private List evaluateMultipleSources( + QueryMetadata metadata, Map, Iterable> iterables, boolean count) { + // from where + Evaluator> ev = + evaluatorFactory.createEvaluator(metadata, metadata.getJoins(), metadata.getWhere()); + List> iterableList = new ArrayList>(metadata.getJoins().size()); + for (JoinExpression join : metadata.getJoins()) { + if (join.getType() == JoinType.DEFAULT) { + iterableList.add(iterables.get(join.getTarget())); + } + } + List list = ev.evaluate(iterableList.toArray()); - // distinct - if (metadata.isDistinct()) { - list = distinct(list); + if (!count && !list.isEmpty()) { + List> sources = new ArrayList>(metadata.getJoins().size()); + for (JoinExpression join : metadata.getJoins()) { + if (join.getType() == JoinType.DEFAULT) { + sources.add(join.getTarget()); + } else { + Operation target = (Operation) join.getTarget(); + sources.add(target.getArg(1)); } - + } + // ordered + if (!metadata.getOrderBy().isEmpty()) { + order(metadata, sources, list); + } + // projection + list = project(metadata, sources, list); + // limit + offset + if (metadata.getModifiers().isRestricting()) { + list = metadata.getModifiers().subList(list); + } + if (list.isEmpty()) { return list; + } } - private List evaluateSingleSource(QueryMetadata metadata, Map, - Iterable> iterables, boolean count) { - final Expression source = metadata.getJoins().get(0).getTarget(); - final List> sources = Collections.>singletonList(source); - final Iterable iterable = iterables.values().iterator().next(); - List list; - if (iterable instanceof List) { - list = (List) iterable; - } else { - list = IteratorAdapter.asList(iterable.iterator()); - } + // distinct + if (metadata.isDistinct()) { + list = distinct(list); + } - // from & where - if (metadata.getWhere() != null) { - Evaluator> evaluator = (Evaluator) evaluatorFactory - .createEvaluator(metadata, source, metadata.getWhere()); - list = evaluator.evaluate(list); - } + return list; + } + + private List evaluateSingleSource( + QueryMetadata metadata, Map, Iterable> iterables, boolean count) { + final Expression source = metadata.getJoins().get(0).getTarget(); + final List> sources = Collections.>singletonList(source); + final Iterable iterable = iterables.values().iterator().next(); + List list; + if (iterable instanceof List) { + list = (List) iterable; + } else { + list = IteratorAdapter.asList(iterable.iterator()); + } - if (!count && !list.isEmpty()) { - // ordered - if (!metadata.getOrderBy().isEmpty()) { - // clone list - if (list == iterable) { - list = new ArrayList(list); - } - order(metadata, sources, list); - } - // projection - if (metadata.getProjection() != null && !metadata.getProjection().equals(source)) { - list = project(metadata, sources, list); - } - // limit + offset - if (metadata.getModifiers().isRestricting()) { - list = metadata.getModifiers().subList(list); - } - if (list.isEmpty()) { - return list; - } - } + // from & where + if (metadata.getWhere() != null) { + Evaluator> evaluator = + (Evaluator) evaluatorFactory.createEvaluator(metadata, source, metadata.getWhere()); + list = evaluator.evaluate(list); + } - // distinct - if (metadata.isDistinct()) { - list = distinct(list); + if (!count && !list.isEmpty()) { + // ordered + if (!metadata.getOrderBy().isEmpty()) { + // clone list + if (list == iterable) { + list = new ArrayList(list); } - + order(metadata, sources, list); + } + // projection + if (metadata.getProjection() != null && !metadata.getProjection().equals(source)) { + list = project(metadata, sources, list); + } + // limit + offset + if (metadata.getModifiers().isRestricting()) { + list = metadata.getModifiers().subList(list); + } + if (list.isEmpty()) { return list; - + } } - private void order(QueryMetadata metadata, List> sources, List list) { - // create a projection for the order - List> orderBy = metadata.getOrderBy(); - Expression[] orderByExpr = new Expression[orderBy.size()]; - boolean[] directions = new boolean[orderBy.size()]; - boolean[] nullsLast = new boolean[orderBy.size()]; - for (int i = 0; i < orderBy.size(); i++) { - orderByExpr[i] = (Expression) orderBy.get(i).getTarget(); - directions[i] = orderBy.get(i).getOrder() == Order.ASC; - nullsLast[i] = orderBy.get(i).getNullHandling() == OrderSpecifier.NullHandling.NullsLast; - } - Expression expr = new ArrayConstructorExpression(Object[].class, orderByExpr); - Evaluator orderEvaluator = evaluatorFactory.create(metadata, sources, expr); - list.sort(new MultiComparator(orderEvaluator, directions, nullsLast)); + // distinct + if (metadata.isDistinct()) { + list = distinct(list); } - private List project(QueryMetadata metadata, List> sources, List list) { - Expression projection = metadata.getProjection(); - Operator aggregator = null; - if (projection instanceof Operation && Ops.aggOps.contains(((Operation) projection).getOperator())) { - Operation aggregation = (Operation) projection; - aggregator = aggregation.getOperator(); - projection = aggregation.getArg(0); - } - Evaluator projectionEvaluator = evaluatorFactory.create(metadata, sources, projection); - EvaluatorFunction transformer = new EvaluatorFunction(projectionEvaluator); - List target = list.stream().map(transformer).collect(Collectors.toList()); - if (aggregator != null) { - return Collections.singletonList(CollQueryFunctions.aggregate(target, projection, aggregator)); - } else { - return target; - } + return list; + } + + private void order(QueryMetadata metadata, List> sources, List list) { + // create a projection for the order + List> orderBy = metadata.getOrderBy(); + Expression[] orderByExpr = new Expression[orderBy.size()]; + boolean[] directions = new boolean[orderBy.size()]; + boolean[] nullsLast = new boolean[orderBy.size()]; + for (int i = 0; i < orderBy.size(); i++) { + orderByExpr[i] = (Expression) orderBy.get(i).getTarget(); + directions[i] = orderBy.get(i).getOrder() == Order.ASC; + nullsLast[i] = orderBy.get(i).getNullHandling() == OrderSpecifier.NullHandling.NullsLast; } - - - + Expression expr = new ArrayConstructorExpression(Object[].class, orderByExpr); + Evaluator orderEvaluator = evaluatorFactory.create(metadata, sources, expr); + list.sort(new MultiComparator(orderEvaluator, directions, nullsLast)); + } + + private List project(QueryMetadata metadata, List> sources, List list) { + Expression projection = metadata.getProjection(); + Operator aggregator = null; + if (projection instanceof Operation + && Ops.aggOps.contains(((Operation) projection).getOperator())) { + Operation aggregation = (Operation) projection; + aggregator = aggregation.getOperator(); + projection = aggregation.getArg(0); + } + Evaluator projectionEvaluator = evaluatorFactory.create(metadata, sources, projection); + EvaluatorFunction transformer = new EvaluatorFunction(projectionEvaluator); + List target = list.stream().map(transformer).collect(Collectors.toList()); + if (aggregator != null) { + return Collections.singletonList( + CollQueryFunctions.aggregate(target, projection, aggregator)); + } else { + return target; + } + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/EvaluatorFunction.java b/querydsl-collections/src/main/java/com/querydsl/collections/EvaluatorFunction.java index eab6b0cb03..72d36a7aeb 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/EvaluatorFunction.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/EvaluatorFunction.java @@ -14,7 +14,6 @@ package com.querydsl.collections; import com.querydsl.codegen.utils.Evaluator; - import java.util.function.Function; /** @@ -22,23 +21,22 @@ * * @param source type * @param target type - * * @author tiwe */ public class EvaluatorFunction implements Function { - private final Evaluator ev; + private final Evaluator ev; - public EvaluatorFunction(Evaluator ev) { - this.ev = ev; - } + public EvaluatorFunction(Evaluator ev) { + this.ev = ev; + } - @Override - public T apply(S input) { - if (input.getClass().isArray()) { - return ev.evaluate((Object[]) input); - } else { - return ev.evaluate(input); - } + @Override + public T apply(S input) { + if (input.getClass().isArray()) { + return ev.evaluate((Object[]) input); + } else { + return ev.evaluate(input); } + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/FunctionalHelpers.java b/querydsl-collections/src/main/java/com/querydsl/collections/FunctionalHelpers.java index 3176f7e5f7..1871a6ae7a 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/FunctionalHelpers.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/FunctionalHelpers.java @@ -19,59 +19,56 @@ import com.querydsl.core.types.Path; import com.querydsl.core.types.PathExtractor; import com.querydsl.core.types.Predicate; - import java.util.Collections; import java.util.function.Function; /** - * {@code GuavaHelpers} provides functionality to wrap Querydsl {@link Predicate} instances to Guava predicates - * and Querydsl {@link Expression} instances to Guava functions + * {@code GuavaHelpers} provides functionality to wrap Querydsl {@link Predicate} instances to Guava + * predicates and Querydsl {@link Expression} instances to Guava functions * * @author tiwe - * */ public final class FunctionalHelpers { - private static final DefaultEvaluatorFactory evaluatorFactory = - new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); - - /** - * Wrap a Querydsl predicate into a Guava predicate - * - * @param predicate predicate to wrapped - * @return Guava predicate - */ - public static java.util.function.Predicate wrap(Predicate predicate) { - Path path = predicate.accept(PathExtractor.DEFAULT, null); - if (path != null) { - final Evaluator ev = createEvaluator(path.getRoot(), predicate); - return ev::evaluate; - } else { - throw new IllegalArgumentException("No path in " + predicate); - } - } + private static final DefaultEvaluatorFactory evaluatorFactory = + new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); - /** - * Wrap a Querydsl expression into a Guava function - * - * @param projection projection to wrap - * @return Guava function - */ - public static Function wrap(Expression projection) { - Path path = projection.accept(PathExtractor.DEFAULT, null); - if (path != null) { - final Evaluator ev = createEvaluator(path.getRoot(), projection); - return ev::evaluate; - } else { - throw new IllegalArgumentException("No path in " + projection); - } + /** + * Wrap a Querydsl predicate into a Guava predicate + * + * @param predicate predicate to wrapped + * @return Guava predicate + */ + public static java.util.function.Predicate wrap(Predicate predicate) { + Path path = predicate.accept(PathExtractor.DEFAULT, null); + if (path != null) { + final Evaluator ev = createEvaluator(path.getRoot(), predicate); + return ev::evaluate; + } else { + throw new IllegalArgumentException("No path in " + predicate); } + } - private static Evaluator createEvaluator(Path path, Expression projection) { - return evaluatorFactory.create(EmptyMetadata.DEFAULT, - Collections.singletonList(path), projection); + /** + * Wrap a Querydsl expression into a Guava function + * + * @param projection projection to wrap + * @return Guava function + */ + public static Function wrap(Expression projection) { + Path path = projection.accept(PathExtractor.DEFAULT, null); + if (path != null) { + final Evaluator ev = createEvaluator(path.getRoot(), projection); + return ev::evaluate; + } else { + throw new IllegalArgumentException("No path in " + projection); } + } - private FunctionalHelpers() { } + private static Evaluator createEvaluator(Path path, Expression projection) { + return evaluatorFactory.create( + EmptyMetadata.DEFAULT, Collections.singletonList(path), projection); + } + private FunctionalHelpers() {} } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/JodaTimeTemplates.java b/querydsl-collections/src/main/java/com/querydsl/collections/JodaTimeTemplates.java index ea53433384..afb6225b1b 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/JodaTimeTemplates.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/JodaTimeTemplates.java @@ -15,32 +15,29 @@ import com.querydsl.core.types.Ops; - /** * Custom templates which support the Joda Time API instead of the JDK Date API * * @author tiwe - * */ public class JodaTimeTemplates extends CollQueryTemplates { - @SuppressWarnings("FieldNameHidesFieldInSuperclass") //Intentional - public static final JodaTimeTemplates DEFAULT = new JodaTimeTemplates(); - - protected JodaTimeTemplates() { - add(Ops.DateTimeOps.YEAR, "{0}.getYear()"); - add(Ops.DateTimeOps.MONTH, "{0}.getMonthOfYear()"); - add(Ops.DateTimeOps.WEEK, "{0}.getWeekOfWeekyear()"); - add(Ops.DateTimeOps.DAY_OF_WEEK, "{0}.getDayOfWeek()"); - add(Ops.DateTimeOps.DAY_OF_MONTH, "{0}.getDayOfMonth()"); - add(Ops.DateTimeOps.DAY_OF_YEAR, "{0}.getDayOfYear()"); - add(Ops.DateTimeOps.HOUR, "{0}.getHourOfDay()"); - add(Ops.DateTimeOps.MINUTE, "{0}.getMinuteOfHour()"); - add(Ops.DateTimeOps.SECOND, "{0}.getSecondOfMinute()"); - add(Ops.DateTimeOps.MILLISECOND, "{0}.getMillisOfSecond()"); + @SuppressWarnings("FieldNameHidesFieldInSuperclass") // Intentional + public static final JodaTimeTemplates DEFAULT = new JodaTimeTemplates(); - add(Ops.DateTimeOps.YEAR_MONTH, "({0}.getYear() * 100 + {0}.getMonthOfYear())"); - add(Ops.DateTimeOps.YEAR_WEEK, "({0}.getWeekyear() * 100 + {0}.getWeekOfWeekyear())"); - } + protected JodaTimeTemplates() { + add(Ops.DateTimeOps.YEAR, "{0}.getYear()"); + add(Ops.DateTimeOps.MONTH, "{0}.getMonthOfYear()"); + add(Ops.DateTimeOps.WEEK, "{0}.getWeekOfWeekyear()"); + add(Ops.DateTimeOps.DAY_OF_WEEK, "{0}.getDayOfWeek()"); + add(Ops.DateTimeOps.DAY_OF_MONTH, "{0}.getDayOfMonth()"); + add(Ops.DateTimeOps.DAY_OF_YEAR, "{0}.getDayOfYear()"); + add(Ops.DateTimeOps.HOUR, "{0}.getHourOfDay()"); + add(Ops.DateTimeOps.MINUTE, "{0}.getMinuteOfHour()"); + add(Ops.DateTimeOps.SECOND, "{0}.getSecondOfMinute()"); + add(Ops.DateTimeOps.MILLISECOND, "{0}.getMillisOfSecond()"); + add(Ops.DateTimeOps.YEAR_MONTH, "({0}.getYear() * 100 + {0}.getMonthOfYear())"); + add(Ops.DateTimeOps.YEAR_WEEK, "({0}.getWeekyear() * 100 + {0}.getWeekOfWeekyear())"); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/MultiComparator.java b/querydsl-collections/src/main/java/com/querydsl/collections/MultiComparator.java index a68e3740bf..c18e3f83e7 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/MultiComparator.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/MultiComparator.java @@ -13,11 +13,10 @@ */ package com.querydsl.collections; -import java.io.Serializable; -import java.util.Comparator; - import com.querydsl.codegen.utils.Evaluator; import com.querydsl.core.util.NullSafeComparableComparator; +import java.io.Serializable; +import java.util.Comparator; /** * {@code MultiComparator} compares arrays @@ -27,47 +26,46 @@ */ public class MultiComparator implements Comparator, Serializable { - @SuppressWarnings("unchecked") - private static final Comparator naturalOrder = new NullSafeComparableComparator(); + @SuppressWarnings("unchecked") + private static final Comparator naturalOrder = new NullSafeComparableComparator(); - private static final long serialVersionUID = 1121416260773566299L; + private static final long serialVersionUID = 1121416260773566299L; - private final boolean[] asc; + private final boolean[] asc; - private final boolean[] nullsLast; + private final boolean[] nullsLast; - private final transient Evaluator ev; + private final transient Evaluator ev; - public MultiComparator(Evaluator ev, boolean[] directions, boolean[] nullsLast) { - this.ev = ev; - this.asc = directions.clone(); - this.nullsLast = nullsLast.clone(); - } + public MultiComparator(Evaluator ev, boolean[] directions, boolean[] nullsLast) { + this.ev = ev; + this.asc = directions.clone(); + this.nullsLast = nullsLast.clone(); + } - @Override - public int compare(T o1, T o2) { - if (o1 instanceof Object[]) { - return innerCompare(ev.evaluate((Object[]) o1), ev.evaluate((Object[]) o2)); - } else { - return innerCompare(ev.evaluate(o1), ev.evaluate(o2)); - } + @Override + public int compare(T o1, T o2) { + if (o1 instanceof Object[]) { + return innerCompare(ev.evaluate((Object[]) o1), ev.evaluate((Object[]) o2)); + } else { + return innerCompare(ev.evaluate(o1), ev.evaluate(o2)); } + } - private int innerCompare(Object[] o1, Object[] o2) { - for (int i = 0; i < o1.length; i++) { - if (o1[i] == null) { - return o2[i] == null ? 0 : nullsLast[i] ? 1 : -1; - } else if (o2[i] == null) { - return nullsLast[i] ? -1 : 1; - } else { - int res; - res = naturalOrder.compare(o1[i], o2[i]); - if (res != 0) { - return asc[i] ? res : -res; - } - } + private int innerCompare(Object[] o1, Object[] o2) { + for (int i = 0; i < o1.length; i++) { + if (o1[i] == null) { + return o2[i] == null ? 0 : nullsLast[i] ? 1 : -1; + } else if (o2[i] == null) { + return nullsLast[i] ? -1 : 1; + } else { + int res; + res = naturalOrder.compare(o1[i], o2[i]); + if (res != 0) { + return asc[i] ? res : -res; } - return 0; + } } - + return 0; + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/PathComparator.java b/querydsl-collections/src/main/java/com/querydsl/collections/PathComparator.java index 4e1139ecd5..c7a0b590eb 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/PathComparator.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/PathComparator.java @@ -14,7 +14,6 @@ package com.querydsl.collections; import com.querydsl.core.types.Path; - import java.util.Comparator; import java.util.function.Function; @@ -23,50 +22,49 @@ * * @author Jeroen van Schagen * @author tiwe - * * @param type of the path root * @param type of value being matched */ public class PathComparator> implements Comparator { - private final Function accessor; + private final Function accessor; - public PathComparator(Path comparingPath) { - this(comparingPath, FunctionalHelpers.wrap(comparingPath)); - } + public PathComparator(Path comparingPath) { + this(comparingPath, FunctionalHelpers.wrap(comparingPath)); + } - public PathComparator(Path comparingPath, Function accessor) { - this.accessor = accessor; - } + public PathComparator(Path comparingPath, Function accessor) { + this.accessor = accessor; + } - public static > PathComparator pathComparator(Path comparingPath) { - return new PathComparator(comparingPath); - } + public static > PathComparator pathComparator( + Path comparingPath) { + return new PathComparator(comparingPath); + } - @Override - public int compare(T leftBean, T rightBean) { - if (leftBean == rightBean) { - return 0; // Reference to the same object should always result in '0' - } else if (leftBean == null) { - return -1; // Whenever the reference varies and left is null, right is not null - } else if (rightBean == null) { - return 1; // Whenever the reference varies and right is null, left is not null - } else if (leftBean.equals(rightBean)) { - return 0; // Equal beans should always result in '0' - } - return comparePathValues(leftBean, rightBean); + @Override + public int compare(T leftBean, T rightBean) { + if (leftBean == rightBean) { + return 0; // Reference to the same object should always result in '0' + } else if (leftBean == null) { + return -1; // Whenever the reference varies and left is null, right is not null + } else if (rightBean == null) { + return 1; // Whenever the reference varies and right is null, left is not null + } else if (leftBean.equals(rightBean)) { + return 0; // Equal beans should always result in '0' } + return comparePathValues(leftBean, rightBean); + } - private int comparePathValues(T leftBean, T rightBean) { - V left = accessor.apply(leftBean); - V right = accessor.apply(rightBean); - if (left == null) { - return -1; - } else if (right == null) { - return 1; - } else { - return left.compareTo(right); - } + private int comparePathValues(T leftBean, T rightBean) { + V left = accessor.apply(leftBean); + V right = accessor.apply(rightBean); + if (left == null) { + return -1; + } else if (right == null) { + return 1; + } else { + return left.compareTo(right); } - + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/PathMatcher.java b/querydsl-collections/src/main/java/com/querydsl/collections/PathMatcher.java index 03432cbb20..9de09be70a 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/PathMatcher.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/PathMatcher.java @@ -13,68 +13,65 @@ */ package com.querydsl.collections; +import static org.hamcrest.core.IsNull.notNullValue; + import com.querydsl.core.types.Path; +import java.util.function.Function; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; -import java.util.function.Function; - -import static org.hamcrest.core.IsNull.notNullValue; - /** * Matches based on the current value of a path. * * @author Jeroen van Schagen * @author tiwe - * * @param type of the path root * @param type of value being matched */ public class PathMatcher extends TypeSafeDiagnosingMatcher { - private final Function accessor; + private final Function accessor; - private final Matcher matcher; + private final Matcher matcher; - private final Path path; + private final Path path; - public PathMatcher(Path path, Matcher matcher) { - this(path, matcher, FunctionalHelpers.wrap(path)); - } + public PathMatcher(Path path, Matcher matcher) { + this(path, matcher, FunctionalHelpers.wrap(path)); + } - public PathMatcher(Path path, Matcher matcher, Function accessor) { - this.path = path; - this.matcher = matcher; - this.accessor = accessor; - } + public PathMatcher(Path path, Matcher matcher, Function accessor) { + this.path = path; + this.matcher = matcher; + this.accessor = accessor; + } - public static Matcher hasValue(Path

path) { - return new PathMatcher(path, notNullValue()); - } + public static Matcher hasValue(Path

path) { + return new PathMatcher(path, notNullValue()); + } - public static Matcher hasValue(Path

path, Matcher matcher) { - return new PathMatcher(path, matcher); - } - - @Override - protected boolean matchesSafely(T bean, Description mismatchDescription) { - V value = accessor.apply(bean); - boolean valueMatches = matcher.matches(value); - if (!valueMatches) { - mismatchDescription.appendText("value \"" + path.toString() + "\" "); - matcher.describeMismatch(value, mismatchDescription); - } - return valueMatches; - } + public static Matcher hasValue(Path

path, Matcher matcher) { + return new PathMatcher(path, matcher); + } - @Override - public void describeTo(Description description) { - description.appendText("valueOf("); - description.appendValue(path.toString()); - description.appendText(", "); - description.appendDescriptionOf(matcher); - description.appendText(")"); + @Override + protected boolean matchesSafely(T bean, Description mismatchDescription) { + V value = accessor.apply(bean); + boolean valueMatches = matcher.matches(value); + if (!valueMatches) { + mismatchDescription.appendText("value \"" + path.toString() + "\" "); + matcher.describeMismatch(value, mismatchDescription); } + return valueMatches; + } + @Override + public void describeTo(Description description) { + description.appendText("valueOf("); + description.appendValue(path.toString()); + description.appendText(", "); + description.appendDescriptionOf(matcher); + description.appendText(")"); + } } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/QueryEngine.java b/querydsl-collections/src/main/java/com/querydsl/collections/QueryEngine.java index bb61210872..63f7071d09 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/QueryEngine.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/QueryEngine.java @@ -13,46 +13,43 @@ */ package com.querydsl.collections; -import java.util.List; -import java.util.Map; - import com.querydsl.core.QueryMetadata; import com.querydsl.core.types.Expression; +import java.util.List; +import java.util.Map; /** * {@code QueryEngine} defines an interface for the evaluation of ColQuery queries * * @author tiwe - * */ public interface QueryEngine { - /** - * Evaluate the given query and return the count of matched rows - * - * @param metadata query metadata - * @param iterables source contents - * @return matching row count - */ - long count(QueryMetadata metadata, Map, Iterable> iterables); - - /** - * Evaluate the given query and return the projection as a list - * - * @param metadata query metadata - * @param iterables source contents - * @return matching rows - */ - List list(QueryMetadata metadata, Map, Iterable> iterables, - Expression projection); + /** + * Evaluate the given query and return the count of matched rows + * + * @param metadata query metadata + * @param iterables source contents + * @return matching row count + */ + long count(QueryMetadata metadata, Map, Iterable> iterables); - /** - * Evaluate the given query return whether rows where matched - * - * @param metadata query metadata - * @param iterables source contents - * @return true, if at least one row was matched - */ - boolean exists(QueryMetadata metadata, Map, Iterable> iterables); + /** + * Evaluate the given query and return the projection as a list + * + * @param metadata query metadata + * @param iterables source contents + * @return matching rows + */ + List list( + QueryMetadata metadata, Map, Iterable> iterables, Expression projection); + /** + * Evaluate the given query return whether rows where matched + * + * @param metadata query metadata + * @param iterables source contents + * @return true, if at least one row was matched + */ + boolean exists(QueryMetadata metadata, Map, Iterable> iterables); } diff --git a/querydsl-collections/src/main/java/com/querydsl/collections/package-info.java b/querydsl-collections/src/main/java/com/querydsl/collections/package-info.java index 9bde598cf1..ae741c1068 100644 --- a/querydsl-collections/src/main/java/com/querydsl/collections/package-info.java +++ b/querydsl-collections/src/main/java/com/querydsl/collections/package-info.java @@ -12,7 +12,5 @@ * limitations under the License. */ -/** - * Java Bean collections support - */ +/** Java Bean collections support */ package com.querydsl.collections; diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/AbstractQueryTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/AbstractQueryTest.java index ec39f83d4e..bae31dd9de 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/AbstractQueryTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/AbstractQueryTest.java @@ -13,95 +13,92 @@ */ package com.querydsl.collections; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; - import com.querydsl.core.DefaultQueryMetadata; import com.querydsl.core.Tuple; import com.querydsl.core.alias.Alias; import com.querydsl.core.types.Expression; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Before; public abstract class AbstractQueryTest { - protected final Cat c1 = new Cat("Kitty"); + protected final Cat c1 = new Cat("Kitty"); + + protected final Cat c2 = new Cat("Bob"); + + protected final Cat c3 = new Cat("Alex"); - protected final Cat c2 = new Cat("Bob"); + protected final Cat c4 = new Cat("Francis"); - protected final Cat c3 = new Cat("Alex"); + protected final QCat cat = new QCat("cat"); - protected final Cat c4 = new Cat("Francis"); + protected final QCat kitten = new QCat("kitten"); - protected final QCat cat = new QCat("cat"); + protected final QCat offspr = new QCat("offspr"); - protected final QCat kitten = new QCat("kitten"); + protected final QCat otherCat = new QCat("otherCat"); - protected final QCat offspr = new QCat("offspr"); + protected final QCat mate = new QCat("mate"); - protected final QCat otherCat = new QCat("otherCat"); + protected List cats = Arrays.asList(c1, c2, c3, c4); - protected final QCat mate = new QCat("mate"); + protected List ints = new ArrayList(); - protected List cats = Arrays.asList(c1, c2, c3, c4); + protected List myInts = new ArrayList(); - protected List ints = new ArrayList(); + protected TestQuery last; + + @Before + public void setUp() { + myInts.addAll(Arrays.asList(1, 2, 3, 4)); + Alias.resetAlias(); + } + + protected List cats(int size) { + List cats = new ArrayList(size); + for (int i = 0; i < size / 2; i++) { + cats.add(new Cat("Kate" + (i + 1))); + cats.add(new Cat("Bob" + (i + 1))); + } + return cats; + } - protected List myInts = new ArrayList(); + protected TestQuery query() { + last = new TestQuery(); + return last; + } - protected TestQuery last; + static class TestQuery extends AbstractCollQuery> { + List res = new ArrayList(); - @Before - public void setUp() { - myInts.addAll(Arrays.asList(1, 2, 3, 4)); - Alias.resetAlias(); + TestQuery() { + super(new DefaultQueryMetadata(), DefaultQueryEngine.getDefault()); } - protected List cats(int size) { - List cats = new ArrayList(size); - for (int i = 0; i < size / 2; i++) { - cats.add(new Cat("Kate" + (i + 1))); - cats.add(new Cat("Bob" + (i + 1))); - } - return cats; + @Override + public List fetch() { + List rv = super.fetch(); + res.addAll(rv); + return rv; } - protected TestQuery query() { - last = new TestQuery(); - return last; + @Override + public TestQuery select(Expression expr) { + queryMixin.setProjection(expr); + @SuppressWarnings("unchecked") // This is the new projection's type + TestQuery newType = (TestQuery) queryMixin.getSelf(); + return newType; } - static class TestQuery extends AbstractCollQuery> { - - List res = new ArrayList(); - - TestQuery() { - super(new DefaultQueryMetadata(), DefaultQueryEngine.getDefault()); - } - - @Override - public List fetch() { - List rv = super.fetch(); - res.addAll(rv); - return rv; - } - - @Override - public TestQuery select(Expression expr) { - queryMixin.setProjection(expr); - @SuppressWarnings("unchecked") // This is the new projection's type - TestQuery newType = (TestQuery) queryMixin.getSelf(); - return newType; - } - - @Override - public TestQuery select(Expression... exprs) { - queryMixin.setProjection(exprs); - @SuppressWarnings("unchecked") // This is the new projection's type - TestQuery newType = (TestQuery) queryMixin.getSelf(); - return newType; - } + @Override + public TestQuery select(Expression... exprs) { + queryMixin.setProjection(exprs); + @SuppressWarnings("unchecked") // This is the new projection's type + TestQuery newType = (TestQuery) queryMixin.getSelf(); + return newType; } + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/AggregationTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/AggregationTest.java index 51033e1221..89fd81029d 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/AggregationTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/AggregationTest.java @@ -3,64 +3,62 @@ import static org.junit.Assert.assertEquals; import java.util.Arrays; - import org.junit.Before; import org.junit.Test; public class AggregationTest extends AbstractQueryTest { - private static final QCat cat = QCat.cat; - - private CollQuery query; + private static final QCat cat = QCat.cat; - @Override - @Before - public void setUp() { - Cat cat1 = new Cat(); - cat1.setWeight(2); - Cat cat2 = new Cat(); - cat2.setWeight(3); - Cat cat3 = new Cat(); - cat3.setWeight(4); - Cat cat4 = new Cat(); - cat4.setWeight(5); - query = CollQueryFactory. from(cat, Arrays.asList(cat1, cat2, cat3, cat4)); - } + private CollQuery query; - @Test - public void avg() { - assertEquals(3.5, query.select(cat.weight.avg()).fetchOne(), 0.0); - } + @Override + @Before + public void setUp() { + Cat cat1 = new Cat(); + cat1.setWeight(2); + Cat cat2 = new Cat(); + cat2.setWeight(3); + Cat cat3 = new Cat(); + cat3.setWeight(4); + Cat cat4 = new Cat(); + cat4.setWeight(5); + query = CollQueryFactory.from(cat, Arrays.asList(cat1, cat2, cat3, cat4)); + } - @Test - public void count() { - assertEquals(Long.valueOf(4L), query.select(cat.count()).fetchOne()); - } + @Test + public void avg() { + assertEquals(3.5, query.select(cat.weight.avg()).fetchOne(), 0.0); + } - @Test - public void countDistinct() { - assertEquals(Long.valueOf(4L), query.select(cat.countDistinct()).fetchOne()); - } + @Test + public void count() { + assertEquals(Long.valueOf(4L), query.select(cat.count()).fetchOne()); + } - @Test - public void max() { - assertEquals(Integer.valueOf(5), query.select(cat.weight.max()).fetchOne()); - } + @Test + public void countDistinct() { + assertEquals(Long.valueOf(4L), query.select(cat.countDistinct()).fetchOne()); + } - @Test - public void min() { - assertEquals(Integer.valueOf(2), query.select(cat.weight.min()).fetchOne()); - } + @Test + public void max() { + assertEquals(Integer.valueOf(5), query.select(cat.weight.max()).fetchOne()); + } - @SuppressWarnings("unchecked") - @Test(expected = UnsupportedOperationException.class) - public void min_and_max() { - query.select(cat.weight.min(), cat.weight.max()).fetchOne(); - } + @Test + public void min() { + assertEquals(Integer.valueOf(2), query.select(cat.weight.min()).fetchOne()); + } - @Test - public void sum() { - assertEquals(Integer.valueOf(14), query.select(cat.weight.sum()).fetchOne()); - } + @SuppressWarnings("unchecked") + @Test(expected = UnsupportedOperationException.class) + public void min_and_max() { + query.select(cat.weight.min(), cat.weight.max()).fetchOne(); + } + @Test + public void sum() { + assertEquals(Integer.valueOf(14), query.select(cat.weight.sum()).fetchOne()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/AliasTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/AliasTest.java index ac88bc7d85..b29514ae93 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/AliasTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/AliasTest.java @@ -17,135 +17,138 @@ import static com.querydsl.core.alias.Alias.*; import static org.junit.Assert.*; +import com.querydsl.core.alias.Alias; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.StringPath; import java.util.Arrays; import java.util.Collections; import java.util.Date; - import org.junit.Before; import org.junit.Test; -import com.querydsl.core.alias.Alias; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.NumberPath; -import com.querydsl.core.types.dsl.StringPath; - public class AliasTest extends AbstractQueryTest { - @Before - public void setUp() { - myInts.add(1); - myInts.add(2); - myInts.add(3); - myInts.add(4); - - Alias.resetAlias(); - } - - @Test - public void aliasVariations1() { - // 1st - QCat cat = new QCat("cat"); - assertEquals(Arrays.asList("Kitty", "Bob", "Alex", "Francis"), - from(cat, cats).where(cat.kittens.size().gt(0)).select(cat.name).fetch()); - - // 2nd - Cat c = alias(Cat.class, "cat"); - assertEquals(Arrays.asList("Kitty", "Bob", "Alex", "Francis"), - from(c, cats).where($(c.getKittens()).size().gt(0)).select($(c.getName())).fetch()); - } - - @Test - public void aliasVariations2() { - // 1st - QCat cat = new QCat("cat"); - assertEquals(Collections.emptyList(), - from(cat, cats).where(cat.name.matches("fri.*")).select(cat.name).fetch()); - - // 2nd - Cat c = alias(Cat.class, "cat"); - assertEquals(Collections.emptyList(), - from(c, cats).where($(c.getName()).matches("fri.*")).select($(c.getName())).fetch()); - } - - @Test - public void alias3() { - QCat cat = new QCat("cat"); - Cat other = new Cat(); - Cat c = alias(Cat.class, "cat"); - - // 1 - from(c, cats).where($(c.getBirthdate()).gt(new Date())).select($(c)).iterate(); - - // 2 - try { - from(c, cats).where($(c.getMate().getName().toUpperCase()).eq("MOE")); - fail("expected NPE"); - } catch (NullPointerException ne) { - // expected - } - - // 3 - assertEquals(cat.name, $(c.getName())); - - // 4 - from(c,cats) - .where($(c.getKittens().get(0).getBodyWeight()).gt(12)) - .select($(c.getName())).iterate(); - - // 5 - from(c, cats).where($(c).eq(other)).select($(c)).iterate(); - - // 6 - from(c, cats).where($(c.getKittens()).contains(other)).select($(c)) - .iterate(); - - // 7 - from(c, cats).where($(c.getKittens().isEmpty())).select($(c)).iterate(); - - // 8 - from(c, cats).where($(c.getName()).startsWith("B")).select($(c)).iterate(); - - // 9 - from(c, cats).where($(c.getName()).upper().eq("MOE")).select($(c)).iterate(); - - // 10 - assertNotNull($(c.getKittensByName())); - assertNotNull($(c.getKittensByName().get("Kitty"))); - from(c, cats).where($(c.getKittensByName().get("Kitty")).isNotNull()).select(cat).iterate(); - - // 11 -// try { -// from(cat, cats).where(cat.mate.alive).fetch(cat); -// fail("expected RuntimeException"); -// } catch (RuntimeException e) { -// System.out.println(e.getMessage()); -// assertEquals("null in cat.mate.alive", e.getMessage()); -// } - - // 12 - // TestQuery query = query().from(cat, c1, c2).from(cat, c1, c2); - // assertEquals(1, query.getMetadata().getJoins().size()); - - } - - @Test - public void various1() { - StringPath str = Expressions.stringPath("str"); - assertEquals(Arrays.asList("a", "ab"), - from(str, "a", "ab", "cd", "de").where(str.startsWith("a")).select(str).fetch()); - } - - @Test - public void various2() { - assertEquals(Arrays.asList(1, 2, 5, 3), - from(var(), 1, 2, "abc", 5, 3).where(var().ne("abc")).select(var()).fetch()); - } - - @Test - public void various3() { - NumberPath num = Expressions.numberPath(Integer.class, "num"); - assertEquals(Arrays.asList(1, 2, 3), - from(num, 1, 2, 3, 4).where(num.lt(4)).select(num).fetch()); + @Before + public void setUp() { + myInts.add(1); + myInts.add(2); + myInts.add(3); + myInts.add(4); + + Alias.resetAlias(); + } + + @Test + public void aliasVariations1() { + // 1st + QCat cat = new QCat("cat"); + assertEquals( + Arrays.asList("Kitty", "Bob", "Alex", "Francis"), + from(cat, cats).where(cat.kittens.size().gt(0)).select(cat.name).fetch()); + + // 2nd + Cat c = alias(Cat.class, "cat"); + assertEquals( + Arrays.asList("Kitty", "Bob", "Alex", "Francis"), + from(c, cats).where($(c.getKittens()).size().gt(0)).select($(c.getName())).fetch()); + } + + @Test + public void aliasVariations2() { + // 1st + QCat cat = new QCat("cat"); + assertEquals( + Collections.emptyList(), + from(cat, cats).where(cat.name.matches("fri.*")).select(cat.name).fetch()); + + // 2nd + Cat c = alias(Cat.class, "cat"); + assertEquals( + Collections.emptyList(), + from(c, cats).where($(c.getName()).matches("fri.*")).select($(c.getName())).fetch()); + } + + @Test + public void alias3() { + QCat cat = new QCat("cat"); + Cat other = new Cat(); + Cat c = alias(Cat.class, "cat"); + + // 1 + from(c, cats).where($(c.getBirthdate()).gt(new Date())).select($(c)).iterate(); + + // 2 + try { + from(c, cats).where($(c.getMate().getName().toUpperCase()).eq("MOE")); + fail("expected NPE"); + } catch (NullPointerException ne) { + // expected } + // 3 + assertEquals(cat.name, $(c.getName())); + + // 4 + from(c, cats) + .where($(c.getKittens().get(0).getBodyWeight()).gt(12)) + .select($(c.getName())) + .iterate(); + + // 5 + from(c, cats).where($(c).eq(other)).select($(c)).iterate(); + + // 6 + from(c, cats).where($(c.getKittens()).contains(other)).select($(c)).iterate(); + + // 7 + from(c, cats).where($(c.getKittens().isEmpty())).select($(c)).iterate(); + + // 8 + from(c, cats).where($(c.getName()).startsWith("B")).select($(c)).iterate(); + + // 9 + from(c, cats).where($(c.getName()).upper().eq("MOE")).select($(c)).iterate(); + + // 10 + assertNotNull($(c.getKittensByName())); + assertNotNull($(c.getKittensByName().get("Kitty"))); + from(c, cats).where($(c.getKittensByName().get("Kitty")).isNotNull()).select(cat).iterate(); + + // 11 + // try { + // from(cat, cats).where(cat.mate.alive).fetch(cat); + // fail("expected RuntimeException"); + // } catch (RuntimeException e) { + // System.out.println(e.getMessage()); + // assertEquals("null in cat.mate.alive", e.getMessage()); + // } + + // 12 + // TestQuery query = query().from(cat, c1, c2).from(cat, c1, c2); + // assertEquals(1, query.getMetadata().getJoins().size()); + + } + + @Test + public void various1() { + StringPath str = Expressions.stringPath("str"); + assertEquals( + Arrays.asList("a", "ab"), + from(str, "a", "ab", "cd", "de").where(str.startsWith("a")).select(str).fetch()); + } + + @Test + public void various2() { + assertEquals( + Arrays.asList(1, 2, 5, 3), + from(var(), 1, 2, "abc", 5, 3).where(var().ne("abc")).select(var()).fetch()); + } + + @Test + public void various3() { + NumberPath num = Expressions.numberPath(Integer.class, "num"); + assertEquals( + Arrays.asList(1, 2, 3), from(num, 1, 2, 3, 4).where(num.lt(4)).select(num).fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Animal.java b/querydsl-collections/src/test/java/com/querydsl/collections/Animal.java index 646f97ff7e..7b83dd142a 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Animal.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Animal.java @@ -13,100 +13,98 @@ */ package com.querydsl.collections; -import java.util.Date; - import com.querydsl.core.annotations.PropertyType; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QueryType; +import java.util.Date; @QueryEntity public class Animal { - protected boolean alive; - - protected java.util.Date birthdate = new java.util.Date(); + protected boolean alive; - @QueryType(PropertyType.SIMPLE) - private Date dateAsSimple; + protected java.util.Date birthdate = new java.util.Date(); - protected int bodyWeight, weight, toes; + @QueryType(PropertyType.SIMPLE) + private Date dateAsSimple; - protected Color color; + protected int bodyWeight, weight, toes; - protected int id; + protected Color color; - protected String name; + protected int id; - public java.util.Date getBirthdate() { - return birthdate; - } + protected String name; - public int getBodyWeight() { - return bodyWeight; - } + public java.util.Date getBirthdate() { + return birthdate; + } - public Color getColor() { - return color; - } + public int getBodyWeight() { + return bodyWeight; + } - public int getId() { - return id; - } + public Color getColor() { + return color; + } - public String getName() { - return name; - } + public int getId() { + return id; + } - public int getToes() { - return toes; - } + public String getName() { + return name; + } - public int getWeight() { - return weight; - } + public int getToes() { + return toes; + } - public boolean isAlive() { - return alive; - } + public int getWeight() { + return weight; + } - public void setAlive(boolean alive) { - this.alive = alive; - } + public boolean isAlive() { + return alive; + } - public void setBirthdate(java.util.Date birthdate) { - this.birthdate = new Date(birthdate.getTime()); - } + public void setAlive(boolean alive) { + this.alive = alive; + } - public void setBodyWeight(int bodyWeight) { - this.bodyWeight = bodyWeight; - } + public void setBirthdate(java.util.Date birthdate) { + this.birthdate = new Date(birthdate.getTime()); + } - public void setWeight(int weight) { - this.weight = weight; - } + public void setBodyWeight(int bodyWeight) { + this.bodyWeight = bodyWeight; + } - public void setToes(int toes) { - this.toes = toes; - } + public void setWeight(int weight) { + this.weight = weight; + } - public void setColor(Color color) { - this.color = color; - } + public void setToes(int toes) { + this.toes = toes; + } - public void setId(int id) { - this.id = id; - } + public void setColor(Color color) { + this.color = color; + } - public void setName(String name) { - this.name = name; - } + public void setId(int id) { + this.id = id; + } - public Date getDateAsSimple() { - return dateAsSimple; - } + public void setName(String name) { + this.name = name; + } - public void setDateAsSimple(Date dateAsSimple) { - this.dateAsSimple = new Date(dateAsSimple.getTime()); - } + public Date getDateAsSimple() { + return dateAsSimple; + } + public void setDateAsSimple(Date dateAsSimple) { + this.dateAsSimple = new Date(dateAsSimple.getTime()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/AnimalTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/AnimalTest.java index c0af354e98..ec3303eca8 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/AnimalTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/AnimalTest.java @@ -16,22 +16,20 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - import com.querydsl.core.types.dsl.SimplePath; +import org.junit.Test; public class AnimalTest { - @Test - public void cast() { - QCat cat = QAnimal.animal.as(QCat.class); - assertEquals(QAnimal.animal, cat.getMetadata().getElement()); - assertEquals("animal", cat.toString()); - } - - @Test - public void date_as_simple() { - assertTrue(QAnimal.animal.dateAsSimple.getClass().equals(SimplePath.class)); - } + @Test + public void cast() { + QCat cat = QAnimal.animal.as(QCat.class); + assertEquals(QAnimal.animal, cat.getMetadata().getElement()); + assertEquals("animal", cat.toString()); + } + @Test + public void date_as_simple() { + assertTrue(QAnimal.animal.dateAsSimple.getClass().equals(SimplePath.class)); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/BigDecimalTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/BigDecimalTest.java index 1d492bb29f..55a35be919 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/BigDecimalTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/BigDecimalTest.java @@ -2,28 +2,31 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.NumberPath; import java.math.BigDecimal; import java.util.Arrays; - import org.junit.Test; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.NumberPath; - public class BigDecimalTest { - @Test - public void arithmetic() { - NumberPath num = Expressions.numberPath(BigDecimal.class, "num"); - CollQuery query = CollQueryFactory. from(num, Arrays. asList(BigDecimal.ONE, BigDecimal.valueOf(2))); - assertEquals(Arrays.asList(BigDecimal.valueOf(11), BigDecimal.valueOf(12)), - query. select(num.add(BigDecimal.TEN)).fetch()); - assertEquals(Arrays.asList(BigDecimal.valueOf(-9), BigDecimal.valueOf(-8)), - query. select(num.subtract(BigDecimal.TEN)).fetch()); - assertEquals(Arrays.asList(BigDecimal.valueOf(10), BigDecimal.valueOf(20)), - query. select(num.multiply(BigDecimal.TEN)).fetch()); - assertEquals(Arrays.asList(new BigDecimal("0.1"), new BigDecimal("0.2")), - query. select(num.divide(BigDecimal.TEN)).fetch()); - } - + @Test + public void arithmetic() { + NumberPath num = Expressions.numberPath(BigDecimal.class, "num"); + CollQuery query = + CollQueryFactory.from( + num, Arrays.asList(BigDecimal.ONE, BigDecimal.valueOf(2))); + assertEquals( + Arrays.asList(BigDecimal.valueOf(11), BigDecimal.valueOf(12)), + query.select(num.add(BigDecimal.TEN)).fetch()); + assertEquals( + Arrays.asList(BigDecimal.valueOf(-9), BigDecimal.valueOf(-8)), + query.select(num.subtract(BigDecimal.TEN)).fetch()); + assertEquals( + Arrays.asList(BigDecimal.valueOf(10), BigDecimal.valueOf(20)), + query.select(num.multiply(BigDecimal.TEN)).fetch()); + assertEquals( + Arrays.asList(new BigDecimal("0.1"), new BigDecimal("0.2")), + query.select(num.divide(BigDecimal.TEN)).fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/BooleanTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/BooleanTest.java index 495e01ad16..bb0bd7018b 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/BooleanTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/BooleanTest.java @@ -3,45 +3,44 @@ import static com.querydsl.core.alias.Alias.$; import static org.junit.Assert.assertEquals; +import com.querydsl.core.alias.Alias; import java.util.Collections; - import org.junit.Test; -import com.querydsl.core.alias.Alias; - public class BooleanTest { - public static class Entity { - - private boolean boolean1 = true; + public static class Entity { - private Boolean boolean2 = Boolean.TRUE; + private boolean boolean1 = true; - public boolean isBoolean1() { - return boolean1; - } - - public Boolean getBoolean2() { - return boolean2; - } + private Boolean boolean2 = Boolean.TRUE; + public boolean isBoolean1() { + return boolean1; } - @Test - public void primitive_boolean() { - Entity entity = Alias.alias(Entity.class); - assertEquals(1, CollQueryFactory.from(entity, Collections.singleton(new Entity())) - .where($(entity.isBoolean1()).eq(Boolean.TRUE)) - .fetchCount()); + public Boolean getBoolean2() { + return boolean2; } - - @Test - public void object_boolean() { - Entity entity = Alias.alias(Entity.class); - assertEquals(1, CollQueryFactory.from(entity, Collections.singleton(new Entity())) - .where($(entity.getBoolean2()).eq(Boolean.TRUE)) - .fetchCount()); - - } - + } + + @Test + public void primitive_boolean() { + Entity entity = Alias.alias(Entity.class); + assertEquals( + 1, + CollQueryFactory.from(entity, Collections.singleton(new Entity())) + .where($(entity.isBoolean1()).eq(Boolean.TRUE)) + .fetchCount()); + } + + @Test + public void object_boolean() { + Entity entity = Alias.alias(Entity.class); + assertEquals( + 1, + CollQueryFactory.from(entity, Collections.singleton(new Entity())) + .where($(entity.getBoolean2()).eq(Boolean.TRUE)) + .fetchCount()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Car.java b/querydsl-collections/src/test/java/com/querydsl/collections/Car.java index 7e38354427..f91fab7f30 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Car.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Car.java @@ -1,36 +1,34 @@ package com.querydsl.collections; - public class Car { - private String model; - - private Integer horsePower; + private String model; - private Person owner; + private Integer horsePower; - public String getModel() { - return model; - } + private Person owner; - public void setModel(String model) { - this.model = model; - } + public String getModel() { + return model; + } - public Integer getHorsePower() { - return horsePower; - } + public void setModel(String model) { + this.model = model; + } - public void setHorsePower(Integer horsePower) { - this.horsePower = horsePower; - } + public Integer getHorsePower() { + return horsePower; + } - public Person getOwner() { - return owner; - } + public void setHorsePower(Integer horsePower) { + this.horsePower = horsePower; + } - public void setOwner(Person owner) { - this.owner = owner; - } + public Person getOwner() { + return owner; + } + public void setOwner(Person owner) { + this.owner = owner; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CastTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CastTest.java index bd91972221..4b22693a99 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CastTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CastTest.java @@ -3,33 +3,36 @@ import static org.junit.Assert.assertEquals; import java.util.Arrays; - import org.junit.Test; public class CastTest extends AbstractQueryTest { - @Test - public void parents() { - QCat cat = QAnimal.animal.as(QCat.class); - assertEquals(QAnimal.animal, cat.getMetadata().getParent()); - } - - @Test - public void cast() { - assertEquals(Arrays.asList(c1, c2, c3, c4), - query().from(QAnimal.animal, cats) - .where(QAnimal.animal.as(QCat.class).breed.eq(0)) - .select(QAnimal.animal).fetch()); - } - - @Test - public void property_dereference() { - Cat cat = new Cat(); - cat.setEyecolor(Color.TABBY); - assertEquals(Color.TABBY, - CollQueryFactory.from(QAnimal.animal, cat) - .where(QAnimal.animal.instanceOf(Cat.class)) - .select(QAnimal.animal.as(QCat.class).eyecolor).fetchFirst()); - } - + @Test + public void parents() { + QCat cat = QAnimal.animal.as(QCat.class); + assertEquals(QAnimal.animal, cat.getMetadata().getParent()); + } + + @Test + public void cast() { + assertEquals( + Arrays.asList(c1, c2, c3, c4), + query() + .from(QAnimal.animal, cats) + .where(QAnimal.animal.as(QCat.class).breed.eq(0)) + .select(QAnimal.animal) + .fetch()); + } + + @Test + public void property_dereference() { + Cat cat = new Cat(); + cat.setEyecolor(Color.TABBY); + assertEquals( + Color.TABBY, + CollQueryFactory.from(QAnimal.animal, cat) + .where(QAnimal.animal.instanceOf(Cat.class)) + .select(QAnimal.animal.as(QCat.class).eyecolor) + .fetchFirst()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Cat.java b/querydsl-collections/src/test/java/com/querydsl/collections/Cat.java index 067f8fa219..471e1e30a7 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Cat.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Cat.java @@ -13,151 +13,149 @@ */ package com.querydsl.collections; -import java.util.*; - import com.querydsl.core.annotations.PropertyType; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QueryProjection; import com.querydsl.core.annotations.QueryType; +import java.util.*; @QueryEntity public class Cat extends Animal { - private int breed; - - private java.sql.Date dateField; - - private Color eyecolor; + private int breed; - private List kittens = new ArrayList<>(); + private java.sql.Date dateField; - private Cat[] kittenArray; + private Color eyecolor; - private Map kittensByName = new HashMap<>(); + private List kittens = new ArrayList<>(); - private Cat mate; + private Cat[] kittenArray; - @QueryType(PropertyType.NONE) - private String skippedField; + private Map kittensByName = new HashMap<>(); - @QueryType(PropertyType.SIMPLE) - private String stringAsSimple; + private Cat mate; - private java.sql.Time timeField; + @QueryType(PropertyType.NONE) + private String skippedField; - public Cat() { - this.kittensByName = Collections.emptyMap(); - } + @QueryType(PropertyType.SIMPLE) + private String stringAsSimple; - public Cat(String name) { - Cat kitten = new Cat(); - this.kittens = Collections.singletonList(kitten); - this.kittenArray = new Cat[]{kitten}; - this.kittensByName = Collections.singletonMap("Kitty", kitten); - this.name = name; - } + private java.sql.Time timeField; - public Cat(String name, String kittenName) { - this(name); - kittens.get(0).setName(kittenName); - } + public Cat() { + this.kittensByName = Collections.emptyMap(); + } - @QueryProjection - public Cat(String name, int id) { - this(name); - this.id = id; - } + public Cat(String name) { + Cat kitten = new Cat(); + this.kittens = Collections.singletonList(kitten); + this.kittenArray = new Cat[] {kitten}; + this.kittensByName = Collections.singletonMap("Kitty", kitten); + this.name = name; + } - public Cat(String name, int id, Date birthdate) { - this(name, id); - this.birthdate = new Date(birthdate.getTime()); - this.dateField = new java.sql.Date(birthdate.getTime()); - this.timeField = new java.sql.Time(birthdate.getTime()); - } + public Cat(String name, String kittenName) { + this(name); + kittens.get(0).setName(kittenName); + } - public int getBreed() { - return breed; - } + @QueryProjection + public Cat(String name, int id) { + this(name); + this.id = id; + } - public java.sql.Date getDateField() { - return dateField; - } + public Cat(String name, int id, Date birthdate) { + this(name, id); + this.birthdate = new Date(birthdate.getTime()); + this.dateField = new java.sql.Date(birthdate.getTime()); + this.timeField = new java.sql.Time(birthdate.getTime()); + } - public Color getEyecolor() { - return eyecolor; - } + public int getBreed() { + return breed; + } - public List getKittens() { - return kittens; - } + public java.sql.Date getDateField() { + return dateField; + } - public Map getKittensByName() { - return kittensByName; - } + public Color getEyecolor() { + return eyecolor; + } - public Cat getMate() { - return mate; - } + public List getKittens() { + return kittens; + } - public String getSkippedField() { - return skippedField; - } + public Map getKittensByName() { + return kittensByName; + } - public String getStringAsSimple() { - return stringAsSimple; - } + public Cat getMate() { + return mate; + } - public java.sql.Time getTimeField() { - return timeField; - } + public String getSkippedField() { + return skippedField; + } - public void setBreed(int breed) { - this.breed = breed; - } + public String getStringAsSimple() { + return stringAsSimple; + } - public void setDateField(java.sql.Date dateField) { - this.dateField = new java.sql.Date(dateField.getTime()); - } + public java.sql.Time getTimeField() { + return timeField; + } - public void setEyecolor(Color eyecolor) { - this.eyecolor = eyecolor; - } + public void setBreed(int breed) { + this.breed = breed; + } - public void setKittens(List kittens) { - this.kittens = kittens; - } + public void setDateField(java.sql.Date dateField) { + this.dateField = new java.sql.Date(dateField.getTime()); + } - public void setKittensByName(Map kittensByName) { - this.kittensByName = kittensByName; - } + public void setEyecolor(Color eyecolor) { + this.eyecolor = eyecolor; + } - public void setMate(Cat mate) { - this.mate = mate; - } + public void setKittens(List kittens) { + this.kittens = kittens; + } - public void setSkippedField(String skippedField) { - this.skippedField = skippedField; - } - - public void setStringAsSimple(String stringAsSimple) { - this.stringAsSimple = stringAsSimple; - } - - public void setTimeField(java.sql.Time timeField) { - this.timeField = timeField; - } - - public Cat[] getKittenArray() { - return kittenArray; - } - - public void setKittenArray(Cat[] kittenArray) { - this.kittenArray = kittenArray.clone(); - } - - @Override - public String toString() { - return name; - } + public void setKittensByName(Map kittensByName) { + this.kittensByName = kittensByName; + } + public void setMate(Cat mate) { + this.mate = mate; + } + + public void setSkippedField(String skippedField) { + this.skippedField = skippedField; + } + + public void setStringAsSimple(String stringAsSimple) { + this.stringAsSimple = stringAsSimple; + } + + public void setTimeField(java.sql.Time timeField) { + this.timeField = timeField; + } + + public Cat[] getKittenArray() { + return kittenArray; + } + + public void setKittenArray(Cat[] kittenArray) { + this.kittenArray = kittenArray.clone(); + } + + @Override + public String toString() { + return name; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CatTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CatTest.java index d3dcaa3a7c..1684535d69 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CatTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CatTest.java @@ -15,24 +15,23 @@ import static org.junit.Assert.assertTrue; -import org.junit.Test; - import com.querydsl.core.types.dsl.SimplePath; +import org.junit.Test; public class CatTest { - @Test(expected = NoSuchFieldException.class) - public void skippedField() throws SecurityException, NoSuchFieldException { - QCat.class.getField("skippedField"); - } + @Test(expected = NoSuchFieldException.class) + public void skippedField() throws SecurityException, NoSuchFieldException { + QCat.class.getField("skippedField"); + } - @Test - public void stringAsSimple() throws SecurityException, NoSuchFieldException { - assertTrue(QCat.cat.stringAsSimple.getClass().equals(SimplePath.class)); - } + @Test + public void stringAsSimple() throws SecurityException, NoSuchFieldException { + assertTrue(QCat.cat.stringAsSimple.getClass().equals(SimplePath.class)); + } - @Test - public void dateAsSimple() { - assertTrue(QCat.cat.dateAsSimple.getClass().equals(SimplePath.class)); - } + @Test + public void dateAsSimple() { + assertTrue(QCat.cat.dateAsSimple.getClass().equals(SimplePath.class)); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollDeleteClauseTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollDeleteClauseTest.java index 2741ccd83f..161da58079 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollDeleteClauseTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollDeleteClauseTest.java @@ -18,24 +18,24 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.Test; public class CollDeleteClauseTest { - @Test - public void execute() { - QCat cat = QCat.cat; - List cats = new ArrayList(Arrays.asList(new Cat("Ann"), new Cat("Bob"), new Cat("John"), new Cat("Carl"))); - - CollDeleteClause deleteClause = new CollDeleteClause(cat, cats); - deleteClause.where(cat.name.eq("Bob")); - assertEquals(1, deleteClause.execute()); - - assertEquals(3, cats.size()); - assertEquals("Ann", cats.get(0).getName()); - assertEquals("John", cats.get(1).getName()); - assertEquals("Carl", cats.get(2).getName()); - } - + @Test + public void execute() { + QCat cat = QCat.cat; + List cats = + new ArrayList( + Arrays.asList(new Cat("Ann"), new Cat("Bob"), new Cat("John"), new Cat("Carl"))); + + CollDeleteClause deleteClause = new CollDeleteClause(cat, cats); + deleteClause.where(cat.name.eq("Bob")); + assertEquals(1, deleteClause.execute()); + + assertEquals(3, cats.size()); + assertEquals("Ann", cats.get(0).getName()); + assertEquals("John", cats.get(1).getName()); + assertEquals("Carl", cats.get(2).getName()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryFunctionsTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryFunctionsTest.java index 5c43f8549d..2e426a85b4 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryFunctionsTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryFunctionsTest.java @@ -20,38 +20,38 @@ public class CollQueryFunctionsTest { - @Test - public void coalesce() { - assertEquals("1", CollQueryFunctions.coalesce("1",null)); - assertEquals("1", CollQueryFunctions.coalesce(null,"1","2")); - assertNull(CollQueryFunctions.coalesce(null,null)); - } + @Test + public void coalesce() { + assertEquals("1", CollQueryFunctions.coalesce("1", null)); + assertEquals("1", CollQueryFunctions.coalesce(null, "1", "2")); + assertNull(CollQueryFunctions.coalesce(null, null)); + } - @Test - @Ignore - public void likeSpeed() { - // 3015 - final int iterations = 1000000; - long start = System.currentTimeMillis(); - for (int i = 0; i < iterations; i++) { - CollQueryFunctions.like("abcDOG", "%DOG"); - CollQueryFunctions.like("DOGabc", "DOG%"); - CollQueryFunctions.like("abcDOGabc", "%DOG%"); - } - long duration = System.currentTimeMillis() - start; - System.err.println(duration); + @Test + @Ignore + public void likeSpeed() { + // 3015 + final int iterations = 1000000; + long start = System.currentTimeMillis(); + for (int i = 0; i < iterations; i++) { + CollQueryFunctions.like("abcDOG", "%DOG"); + CollQueryFunctions.like("DOGabc", "DOG%"); + CollQueryFunctions.like("abcDOGabc", "%DOG%"); } + long duration = System.currentTimeMillis() - start; + System.err.println(duration); + } - @Test - public void like() { - assertTrue(CollQueryFunctions.like("abcDOG", "%DOG")); - assertTrue(CollQueryFunctions.like("DOGabc", "DOG%")); - assertTrue(CollQueryFunctions.like("abcDOGabc", "%DOG%")); - } + @Test + public void like() { + assertTrue(CollQueryFunctions.like("abcDOG", "%DOG")); + assertTrue(CollQueryFunctions.like("DOGabc", "DOG%")); + assertTrue(CollQueryFunctions.like("abcDOGabc", "%DOG%")); + } - @Test - public void like_with_special_chars() { - assertTrue(CollQueryFunctions.like("$DOG", "$DOG")); - assertTrue(CollQueryFunctions.like("$DOGabc", "$DOG%")); - } + @Test + public void like_with_special_chars() { + assertTrue(CollQueryFunctions.like("$DOG", "$DOG")); + assertTrue(CollQueryFunctions.like("$DOGabc", "$DOG%")); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryStandardTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryStandardTest.java index 8a35a7cf9e..93371d1ba5 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryStandardTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryStandardTest.java @@ -18,13 +18,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - import com.querydsl.core.Fetchable; -import com.querydsl.core.QuerydslModule; import com.querydsl.core.QueryExecution; +import com.querydsl.core.QuerydslModule; import com.querydsl.core.Target; import com.querydsl.core.Tuple; import com.querydsl.core.types.ArrayConstructorExpression; @@ -35,147 +31,173 @@ import com.querydsl.core.types.Projections; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.Param; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.junit.Test; public class CollQueryStandardTest { - private final Date birthDate = new Date(); + private final Date birthDate = new Date(); - private final java.sql.Date date = new java.sql.Date(birthDate.getTime()); + private final java.sql.Date date = new java.sql.Date(birthDate.getTime()); - private final java.sql.Time time = new java.sql.Time(birthDate.getTime()); + private final java.sql.Time time = new java.sql.Time(birthDate.getTime()); - private final QCat cat = new QCat("cat"); + private final QCat cat = new QCat("cat"); - private final QCat otherCat = new QCat("otherCat"); + private final QCat otherCat = new QCat("otherCat"); - private final List data = Arrays.asList( - new Cat("Bob", 1, birthDate), - new Cat("Ruth", 2, birthDate), - new Cat("Felix", 3, birthDate), - new Cat("Allen", 4, birthDate), - new Cat("Mary", 5, birthDate) - ); + private final List data = + Arrays.asList( + new Cat("Bob", 1, birthDate), + new Cat("Ruth", 2, birthDate), + new Cat("Felix", 3, birthDate), + new Cat("Allen", 4, birthDate), + new Cat("Mary", 5, birthDate)); - private static final Expression[] NO_EXPRESSIONS = new Expression[0]; + private static final Expression[] NO_EXPRESSIONS = new Expression[0]; - private QueryExecution standardTest = new QueryExecution(QuerydslModule.COLLECTIONS, Target.MEM) { + private QueryExecution standardTest = + new QueryExecution(QuerydslModule.COLLECTIONS, Target.MEM) { @Override protected Fetchable createQuery() { - return CollQueryFactory.from(cat, data).from(otherCat, data); + return CollQueryFactory.from(cat, data).from(otherCat, data); } + @Override protected Fetchable createQuery(Predicate filter) { - return CollQueryFactory.from(cat, data).from(otherCat, data) - .where(filter).select(cat.name); - } - }; - - @Test - public void test() { - Cat kitten = data.get(0).getKittens().get(0); - standardTest.runArrayTests(cat.kittenArray, otherCat.kittenArray, kitten, new Cat()); - standardTest.runBooleanTests(cat.name.isNull(), otherCat.kittens.isEmpty()); - standardTest.runCollectionTests(cat.kittens, otherCat.kittens, kitten, new Cat()); - standardTest.runDateTests(cat.dateField, otherCat.dateField, date); - standardTest.runDateTimeTests(cat.birthdate, otherCat.birthdate, birthDate); - standardTest.runListTests(cat.kittens, otherCat.kittens, kitten, new Cat()); - standardTest.runMapTests(cat.kittensByName, otherCat.kittensByName, "Kitty", kitten, "NoName", new Cat()); - - // int - standardTest.runNumericCasts(cat.id, otherCat.id, 1); - standardTest.runNumericTests(cat.id, otherCat.id, 1); - - standardTest.runStringTests(cat.name, otherCat.name, "Bob"); - standardTest.runTimeTests(cat.timeField, otherCat.timeField, time); - standardTest.report(); - } - - @Test - public void tupleMultipleFieldsProjection() { - List tuples = CollQueryFactory.from(cat, data) - .select(cat.name, cat.birthdate).fetch(); - for (Tuple tuple : tuples) { - assertNotNull(tuple.get(cat.name)); - assertNotNull(tuple.get(cat.birthdate)); - } - } - - @Test - public void tupleOneFieldProjection() { - List tuples = CollQueryFactory.from(cat, data) - .select(new Expression[] {cat.name}).fetch(); - for (Tuple tuple : tuples) { - assertEquals(1, tuple.size()); - assertNotNull(tuple.get(cat.name)); + return CollQueryFactory.from(cat, data) + .from(otherCat, data) + .where(filter) + .select(cat.name); } + }; + + @Test + public void test() { + Cat kitten = data.get(0).getKittens().get(0); + standardTest.runArrayTests(cat.kittenArray, otherCat.kittenArray, kitten, new Cat()); + standardTest.runBooleanTests(cat.name.isNull(), otherCat.kittens.isEmpty()); + standardTest.runCollectionTests(cat.kittens, otherCat.kittens, kitten, new Cat()); + standardTest.runDateTests(cat.dateField, otherCat.dateField, date); + standardTest.runDateTimeTests(cat.birthdate, otherCat.birthdate, birthDate); + standardTest.runListTests(cat.kittens, otherCat.kittens, kitten, new Cat()); + standardTest.runMapTests( + cat.kittensByName, otherCat.kittensByName, "Kitty", kitten, "NoName", new Cat()); + + // int + standardTest.runNumericCasts(cat.id, otherCat.id, 1); + standardTest.runNumericTests(cat.id, otherCat.id, 1); + + standardTest.runStringTests(cat.name, otherCat.name, "Bob"); + standardTest.runTimeTests(cat.timeField, otherCat.timeField, time); + standardTest.report(); + } + + @Test + public void tupleMultipleFieldsProjection() { + List tuples = CollQueryFactory.from(cat, data).select(cat.name, cat.birthdate).fetch(); + for (Tuple tuple : tuples) { + assertNotNull(tuple.get(cat.name)); + assertNotNull(tuple.get(cat.birthdate)); } - - @Test - public void tupleOneNullFieldProjection() { - List tuples = CollQueryFactory.from(cat, data) - .select(new Expression[] {Expressions.nullExpression()}).fetch(); - for (Tuple tuple : tuples) { - assertNotNull(tuple); - assertEquals(1, tuple.size()); // THIS FAILS WITH NPE - assertNull(tuple.get(Expressions.nullExpression())); - } - } - - @Test - public void nested_tupleProjection() { - Concatenation concat = new Concatenation(cat.name, cat.name); - List tuples = CollQueryFactory.from(cat, data) - .select(concat, cat.name, cat.birthdate).fetch(); - for (Tuple tuple : tuples) { - assertNotNull(tuple.get(cat.name)); - assertNotNull(tuple.get(cat.birthdate)); - assertEquals(tuple.get(cat.name) + tuple.get(cat.name), tuple.get(concat)); - } - } - - @SuppressWarnings("unchecked") - @Test - public void arrayProjection() { - List results = CollQueryFactory.from(cat, data) - .select(new ArrayConstructorExpression(String[].class, cat.name)).fetch(); - assertFalse(results.isEmpty()); - for (String[] result : results) { - assertNotNull(result[0]); - } + } + + @Test + public void tupleOneFieldProjection() { + List tuples = + CollQueryFactory.from(cat, data).select(new Expression[] {cat.name}).fetch(); + for (Tuple tuple : tuples) { + assertEquals(1, tuple.size()); + assertNotNull(tuple.get(cat.name)); } - - @Test - public void constructorProjection() { - List projections = CollQueryFactory.from(cat, data) - .select(Projections.constructor(Projection.class, cat.name, cat)).fetch(); - assertFalse(projections.isEmpty()); - for (Projection projection : projections) { - assertNotNull(projection); - } - } - - @Test - public void params() { - Param name = new Param(String.class,"name"); - assertEquals("Bob", CollQueryFactory.from(cat, data).where(cat.name.eq(name)).set(name,"Bob").select(cat.name).fetchOne()); + } + + @Test + public void tupleOneNullFieldProjection() { + List tuples = + CollQueryFactory.from(cat, data) + .select(new Expression[] {Expressions.nullExpression()}) + .fetch(); + for (Tuple tuple : tuples) { + assertNotNull(tuple); + assertEquals(1, tuple.size()); // THIS FAILS WITH NPE + assertNull(tuple.get(Expressions.nullExpression())); } - - @Test - public void params_anon() { - Param name = new Param(String.class); - assertEquals("Bob", CollQueryFactory.from(cat, data).where(cat.name.eq(name)).set(name,"Bob").select(cat.name).fetchOne()); + } + + @Test + public void nested_tupleProjection() { + Concatenation concat = new Concatenation(cat.name, cat.name); + List tuples = + CollQueryFactory.from(cat, data).select(concat, cat.name, cat.birthdate).fetch(); + for (Tuple tuple : tuples) { + assertNotNull(tuple.get(cat.name)); + assertNotNull(tuple.get(cat.birthdate)); + assertEquals(tuple.get(cat.name) + tuple.get(cat.name), tuple.get(concat)); } - - @Test(expected = ParamNotSetException.class) - public void params_not_set() { - Param name = new Param(String.class,"name"); - assertEquals("Bob", CollQueryFactory.from(cat, data).where(cat.name.eq(name)).select(cat.name).fetchOne()); + } + + @SuppressWarnings("unchecked") + @Test + public void arrayProjection() { + List results = + CollQueryFactory.from(cat, data) + .select(new ArrayConstructorExpression(String[].class, cat.name)) + .fetch(); + assertFalse(results.isEmpty()); + for (String[] result : results) { + assertNotNull(result[0]); } - - @Test - public void limit() { - assertEquals(data, CollQueryFactory.from(cat, data).limit(Long.MAX_VALUE).fetch()); + } + + @Test + public void constructorProjection() { + List projections = + CollQueryFactory.from(cat, data) + .select(Projections.constructor(Projection.class, cat.name, cat)) + .fetch(); + assertFalse(projections.isEmpty()); + for (Projection projection : projections) { + assertNotNull(projection); } - + } + + @Test + public void params() { + Param name = new Param(String.class, "name"); + assertEquals( + "Bob", + CollQueryFactory.from(cat, data) + .where(cat.name.eq(name)) + .set(name, "Bob") + .select(cat.name) + .fetchOne()); + } + + @Test + public void params_anon() { + Param name = new Param(String.class); + assertEquals( + "Bob", + CollQueryFactory.from(cat, data) + .where(cat.name.eq(name)) + .set(name, "Bob") + .select(cat.name) + .fetchOne()); + } + + @Test(expected = ParamNotSetException.class) + public void params_not_set() { + Param name = new Param(String.class, "name"); + assertEquals( + "Bob", + CollQueryFactory.from(cat, data).where(cat.name.eq(name)).select(cat.name).fetchOne()); + } + + @Test + public void limit() { + assertEquals(data, CollQueryFactory.from(cat, data).limit(Long.MAX_VALUE).fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTemplatesTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTemplatesTest.java index 981eca2af1..c4b3376f47 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTemplatesTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTemplatesTest.java @@ -2,27 +2,25 @@ import static org.junit.Assert.assertEquals; -import org.junit.Test; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.TemplatesTestUtils; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.StringPath; +import org.junit.Test; public class CollQueryTemplatesTest { - @Test - public void generic_precedence() { - TemplatesTestUtils.testPrecedence(CollQueryTemplates.DEFAULT); - } - - @Test - public void concat() { - StringPath a = Expressions.stringPath("a"); - StringPath b = Expressions.stringPath("b"); - Expression expr = a.append(b).toLowerCase(); - String str = new CollQuerySerializer(CollQueryTemplates.DEFAULT).handle(expr).toString(); - assertEquals("(a + b).toLowerCase()", str); - } + @Test + public void generic_precedence() { + TemplatesTestUtils.testPrecedence(CollQueryTemplates.DEFAULT); + } + @Test + public void concat() { + StringPath a = Expressions.stringPath("a"); + StringPath b = Expressions.stringPath("b"); + Expression expr = a.append(b).toLowerCase(); + String str = new CollQuerySerializer(CollQueryTemplates.DEFAULT).handle(expr).toString(); + assertEquals("(a + b).toLowerCase()", str); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTest.java index dfef345b29..582a0d4834 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollQueryTest.java @@ -17,14 +17,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import org.junit.Test; - import com.querydsl.core.Tuple; import com.querydsl.core.types.Expression; import com.querydsl.core.types.Ops; @@ -32,140 +24,170 @@ import com.querydsl.core.types.dsl.NumberExpression; import com.querydsl.core.types.dsl.NumberPath; import com.querydsl.core.types.dsl.StringPath; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import org.junit.Test; public class CollQueryTest extends AbstractQueryTest { - @Test - public void customTemplates() { - CollQueryTemplates templates = new CollQueryTemplates() { - { - add(Ops.DateTimeOps.MONTH, "{0}.getMonthOfYear()"); - add(Ops.DateTimeOps.YEAR, "{0}.getYear()"); - } + @Test + public void customTemplates() { + CollQueryTemplates templates = + new CollQueryTemplates() { + { + add(Ops.DateTimeOps.MONTH, "{0}.getMonthOfYear()"); + add(Ops.DateTimeOps.YEAR, "{0}.getYear()"); + } + }; + new CollQuery(templates); + } + + @Test + public void instanceOf() { + assertEquals( + Arrays.asList(c1, c2), + query() + .from(cat, Arrays.asList(c1, c2)) + .where(cat.instanceOf(Cat.class)) + .select(cat) + .fetch()); + } + + @Test + public void after_and_before() { + query() + .from(cat, Arrays.asList(c1, c2)) + .where( + cat.birthdate.lt(new Date()), + cat.birthdate.loe(new Date()), + cat.birthdate.gt(new Date()), + cat.birthdate.goe(new Date())) + .select(cat) + .fetch(); + } + + @Test + public void arrayProjection() { + // select pairs of cats with different names + query() + .from(cat, cats) + .from(otherCat, cats) + .where(cat.name.ne(otherCat.name)) + .select(cat.name, otherCat.name) + .fetch(); + assertEquals(4 * 3, last.res.size()); + } + + @Test + public void cast() { + NumberExpression num = cat.id; + Expression[] expr = + new Expression[] { + num.byteValue(), + num.doubleValue(), + num.floatValue(), + num.intValue(), + num.longValue(), + num.shortValue(), + num.stringValue() }; - new CollQuery(templates); - } - - @Test - public void instanceOf() { - assertEquals( - Arrays.asList(c1, c2), - query().from(cat, Arrays.asList(c1, c2)).where(cat.instanceOf(Cat.class)) - .select(cat).fetch()); - } - - @Test - public void after_and_before() { - query().from(cat, Arrays.asList(c1, c2)) - .where( - cat.birthdate.lt(new Date()), - cat.birthdate.loe(new Date()), - cat.birthdate.gt(new Date()), - cat.birthdate.goe(new Date())) - .select(cat).fetch(); - } - - @Test - public void arrayProjection() { - // select pairs of cats with different names - query().from(cat, cats).from(otherCat, cats).where(cat.name.ne(otherCat.name)) - .select(cat.name, otherCat.name).fetch(); - assertEquals(4 * 3, last.res.size()); - } - - @Test - public void cast() { - NumberExpression num = cat.id; - Expression[] expr = new Expression[] {num.byteValue(), num.doubleValue(), - num.floatValue(), num.intValue(), num.longValue(), - num.shortValue(), num.stringValue()}; - - for (Expression e : expr) { - query().from(cat, Arrays.asList(c1, c2)).select(e).fetch(); - } + for (Expression e : expr) { + query().from(cat, Arrays.asList(c1, c2)).select(e).fetch(); } - - @Test - public void clone_() { - CollQuery query = new CollQuery().from(cat, Collections.emptyList()).where(cat.isNotNull()).clone(); - assertEquals("cat is not null", query.getMetadata().getWhere().toString()); + } + + @Test + public void clone_() { + CollQuery query = + new CollQuery() + .from(cat, Collections.emptyList()) + .where(cat.isNotNull()) + .clone(); + assertEquals("cat is not null", query.getMetadata().getWhere().toString()); + } + + @Test + public void primitives() { + // select cats with kittens + query().from(cat, cats).where(cat.kittens.size().ne(0)).select(cat.name).fetch(); + assertTrue(last.res.size() == 4); + + // select cats without kittens + query().from(cat, cats).where(cat.kittens.size().eq(0)).select(cat.name).fetch(); + assertTrue(last.res.size() == 0); + } + + @Test + public void simpleCases() { + // select all cat names + query().from(cat, cats).select(cat.name).fetch(); + assertTrue(last.res.size() == 4); + + // select all kittens + query().from(cat, cats).select(cat.kittens).fetch(); + assertTrue(last.res.size() == 4); + + // select cats with kittens + query().from(cat, cats).where(cat.kittens.size().gt(0)).select(cat.name).fetch(); + assertTrue(last.res.size() == 4); + + // select cats named Kitty + query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetch(); + assertTrue(last.res.size() == 1); + + // select cats named Kitt% + query().from(cat, cats).where(cat.name.matches("Kitt.*")).select(cat.name).fetch(); + assertTrue(last.res.size() == 1); + + query().from(cat, cats).select(cat.bodyWeight.add(cat.weight)).fetch(); + } + + @Test + public void various() { + StringPath a = Expressions.stringPath("a"); + StringPath b = Expressions.stringPath("b"); + for (Tuple strs : + from(a, "aa", "bb", "cc") + .from(b, Arrays.asList("a", "b")) + .where(a.startsWith(b)) + .select(a, b) + .fetch()) { + assertEquals(strs.get(a), strs.get(b) + strs.get(b)); } - @Test - public void primitives() { - // select cats with kittens - query().from(cat, cats).where(cat.kittens.size().ne(0)).select(cat.name).fetch(); - assertTrue(last.res.size() == 4); - - // select cats without kittens - query().from(cat, cats).where(cat.kittens.size().eq(0)).select(cat.name).fetch(); - assertTrue(last.res.size() == 0); - } + query().from(cat, cats).select(cat.mate).fetch(); - @Test - public void simpleCases() { - // select all cat names - query().from(cat, cats).select(cat.name).fetch(); - assertTrue(last.res.size() == 4); + query().from(cat, cats).select(cat.kittens).fetch(); - // select all kittens - query().from(cat, cats).select(cat.kittens).fetch(); - assertTrue(last.res.size() == 4); - - // select cats with kittens - query().from(cat, cats).where(cat.kittens.size().gt(0)).select(cat.name).fetch(); - assertTrue(last.res.size() == 4); - - // select cats named Kitty - query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetch(); - assertTrue(last.res.size() == 1); - - // select cats named Kitt% - query().from(cat, cats).where(cat.name.matches("Kitt.*")).select(cat.name).fetch(); - assertTrue(last.res.size() == 1); - - query().from(cat, cats).select(cat.bodyWeight.add(cat.weight)).fetch(); - } + query().from(cat, cats).where(cat.kittens.isEmpty()).select(cat).fetch(); - @Test - public void various() { - StringPath a = Expressions.stringPath("a"); - StringPath b = Expressions.stringPath("b"); - for (Tuple strs : from(a, "aa", "bb", "cc") - .from(b, Arrays.asList("a","b")) - .where(a.startsWith(b)).select(a, b).fetch()) { - assertEquals(strs.get(a), strs.get(b) + strs.get(b)); - } + query().from(cat, cats).where(cat.kittens.isNotEmpty()).select(cat).fetch(); - query().from(cat, cats).select(cat.mate).fetch(); + query().from(cat, cats).where(cat.name.matches("fri.*")).select(cat.name).fetch(); + } - query().from(cat, cats).select(cat.kittens).fetch(); + @Test + public void bigDecimals() { + NumberPath a = Expressions.numberPath(BigDecimal.class, "cost"); + List nums = + from(a, new BigDecimal("2.1"), new BigDecimal("20.21"), new BigDecimal("44.4")) + .where(a.lt(new BigDecimal("35.1"))) + .select(a) + .fetch(); + assertEquals(Arrays.asList(new BigDecimal("2.1"), new BigDecimal("20.21")), nums); + } - query().from(cat, cats).where(cat.kittens.isEmpty()).select(cat).fetch(); - - query().from(cat, cats).where(cat.kittens.isNotEmpty()).select(cat).fetch(); - - query().from(cat, cats).where(cat.name.matches("fri.*")).select(cat.name).fetch(); - - } - - @Test - public void bigDecimals() { - NumberPath a = Expressions.numberPath(BigDecimal.class, "cost"); - List nums = from(a, new BigDecimal("2.1"), new BigDecimal("20.21"), - new BigDecimal("44.4")).where(a.lt(new BigDecimal("35.1"))).select(a).fetch(); - assertEquals(Arrays.asList(new BigDecimal("2.1"), new BigDecimal("20.21")), nums); - } - - @Test(expected = UnsupportedOperationException.class) - public void groupBy() { - query().from(cat, cats).groupBy(cat.name); - } - - @Test(expected = UnsupportedOperationException.class) - public void having() { - query().from(cat, cats).having(cat.name.isNull()); - } + @Test(expected = UnsupportedOperationException.class) + public void groupBy() { + query().from(cat, cats).groupBy(cat.name); + } + @Test(expected = UnsupportedOperationException.class) + public void having() { + query().from(cat, cats).having(cat.name.isNull()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollUpdateClauseTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollUpdateClauseTest.java index 74f1c0c549..3653f9427a 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollUpdateClauseTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollUpdateClauseTest.java @@ -17,22 +17,21 @@ import java.util.Arrays; import java.util.List; - import org.junit.Test; public class CollUpdateClauseTest { - @Test - public void execute() { - QCat cat = QCat.cat; - List cats = Arrays.asList(new Cat("Ann"), new Cat("Bob"), new Cat("John"), new Cat("Carl")); - - CollUpdateClause updateClause = new CollUpdateClause(cat, cats); - updateClause.where(cat.name.eq("Bob")); - updateClause.set(cat.name, "Bobby"); - assertEquals(1, updateClause.execute()); + @Test + public void execute() { + QCat cat = QCat.cat; + List cats = + Arrays.asList(new Cat("Ann"), new Cat("Bob"), new Cat("John"), new Cat("Carl")); - assertEquals("Bobby", cats.get(1).getName()); - } + CollUpdateClause updateClause = new CollUpdateClause(cat, cats); + updateClause.where(cat.name.eq("Bob")); + updateClause.set(cat.name, "Bobby"); + assertEquals(1, updateClause.execute()); + assertEquals("Bobby", cats.get(1).getName()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollectionAnyTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollectionAnyTest.java index 94a4667e09..26d036ebd3 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollectionAnyTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollectionAnyTest.java @@ -5,97 +5,107 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Test; public class CollectionAnyTest extends AbstractQueryTest { - @Test - public void any_null() { - Cat a = new Cat("a"); - a.setKittens(null); - - assertEquals(0, CollQueryFactory. from(cat, Collections.singletonList(a)) - .where(cat.kittens.any().name.startsWith("a")).fetchCount()); - } - - @Test - public void any_in_projection() { - Cat a = new Cat("a"); - Cat aa = new Cat("aa"); - Cat ab = new Cat("ab"); - Cat ac = new Cat("ac"); - a.setKittens(Arrays.asList(aa,ab,ac)); - - Cat b = new Cat("b"); - Cat ba = new Cat("ba"); - Cat bb = new Cat("bb"); - b.setKittens(Arrays.asList(ba, bb)); - - QCat cat = QCat.cat; - List kittens = CollQueryFactory. from(cat, Arrays. asList(a,b)). select(cat.kittens.any()).fetch(); - assertEquals(Arrays.asList(aa,ab,ac,ba,bb), kittens); - } - - @Test - public void any_in_projection2() { - Cat a = new Cat("a"); - Cat aa = new Cat("aa"); - Cat ab = new Cat("ab"); - Cat ac = new Cat("ac"); - a.setKittens(Arrays.asList(aa,ab,ac)); - - Cat b = new Cat("b"); - Cat ba = new Cat("ba"); - Cat bb = new Cat("bb"); - b.setKittens(Arrays.asList(ba, bb)); - - QCat cat = QCat.cat; - List kittens = CollQueryFactory. from(cat, Arrays. asList(a,b)) - .select(cat.kittens.any().name).fetch(); - assertEquals(Arrays.asList("aa","ab","ac","ba","bb"), kittens); - } - - @Test - public void any_in_where_and_projection() { - Cat a = new Cat("a"); - Cat aa = new Cat("aa"); - Cat ab = new Cat("ab"); - Cat ac = new Cat("ac"); - a.setKittens(Arrays.asList(aa,ab,ac)); - - Cat b = new Cat("b"); - Cat ba = new Cat("ba"); - Cat bb = new Cat("bb"); - b.setKittens(Arrays.asList(ba, bb)); - - QCat cat = QCat.cat; - List kittens = CollQueryFactory. from(cat, Arrays. asList(a,b)) - .where(cat.kittens.any().name.startsWith("a")) - .select(cat.kittens.any()).fetch(); - - assertEquals(Arrays.asList(aa,ab,ac), kittens); - } - - @Test - public void any_in_where_and_projection2() { - Cat a = new Cat("a"); - Cat aa = new Cat("aa"); - Cat ab = new Cat("ab"); - Cat ac = new Cat("ac"); - a.setKittens(Arrays.asList(aa,ab,ac)); - - Cat b = new Cat("b"); - Cat ba = new Cat("ba"); - Cat bb = new Cat("bb"); - b.setKittens(Arrays.asList(ba, bb)); - - QCat cat = QCat.cat; - List kittens = CollQueryFactory. from(cat, Arrays. asList(a,b)) - .where(cat.kittens.any().name.startsWith("a")) - .select(cat.kittens.any().name).fetch(); - - assertEquals(Arrays.asList("aa","ab","ac"), kittens); - } - + @Test + public void any_null() { + Cat a = new Cat("a"); + a.setKittens(null); + + assertEquals( + 0, + CollQueryFactory.from(cat, Collections.singletonList(a)) + .where(cat.kittens.any().name.startsWith("a")) + .fetchCount()); + } + + @Test + public void any_in_projection() { + Cat a = new Cat("a"); + Cat aa = new Cat("aa"); + Cat ab = new Cat("ab"); + Cat ac = new Cat("ac"); + a.setKittens(Arrays.asList(aa, ab, ac)); + + Cat b = new Cat("b"); + Cat ba = new Cat("ba"); + Cat bb = new Cat("bb"); + b.setKittens(Arrays.asList(ba, bb)); + + QCat cat = QCat.cat; + List kittens = + CollQueryFactory.from(cat, Arrays.asList(a, b)) + .select(cat.kittens.any()) + .fetch(); + assertEquals(Arrays.asList(aa, ab, ac, ba, bb), kittens); + } + + @Test + public void any_in_projection2() { + Cat a = new Cat("a"); + Cat aa = new Cat("aa"); + Cat ab = new Cat("ab"); + Cat ac = new Cat("ac"); + a.setKittens(Arrays.asList(aa, ab, ac)); + + Cat b = new Cat("b"); + Cat ba = new Cat("ba"); + Cat bb = new Cat("bb"); + b.setKittens(Arrays.asList(ba, bb)); + + QCat cat = QCat.cat; + List kittens = + CollQueryFactory.from(cat, Arrays.asList(a, b)) + .select(cat.kittens.any().name) + .fetch(); + assertEquals(Arrays.asList("aa", "ab", "ac", "ba", "bb"), kittens); + } + + @Test + public void any_in_where_and_projection() { + Cat a = new Cat("a"); + Cat aa = new Cat("aa"); + Cat ab = new Cat("ab"); + Cat ac = new Cat("ac"); + a.setKittens(Arrays.asList(aa, ab, ac)); + + Cat b = new Cat("b"); + Cat ba = new Cat("ba"); + Cat bb = new Cat("bb"); + b.setKittens(Arrays.asList(ba, bb)); + + QCat cat = QCat.cat; + List kittens = + CollQueryFactory.from(cat, Arrays.asList(a, b)) + .where(cat.kittens.any().name.startsWith("a")) + .select(cat.kittens.any()) + .fetch(); + + assertEquals(Arrays.asList(aa, ab, ac), kittens); + } + + @Test + public void any_in_where_and_projection2() { + Cat a = new Cat("a"); + Cat aa = new Cat("aa"); + Cat ab = new Cat("ab"); + Cat ac = new Cat("ac"); + a.setKittens(Arrays.asList(aa, ab, ac)); + + Cat b = new Cat("b"); + Cat ba = new Cat("ba"); + Cat bb = new Cat("bb"); + b.setKittens(Arrays.asList(ba, bb)); + + QCat cat = QCat.cat; + List kittens = + CollQueryFactory.from(cat, Arrays.asList(a, b)) + .where(cat.kittens.any().name.startsWith("a")) + .select(cat.kittens.any().name) + .fetch(); + + assertEquals(Arrays.asList("aa", "ab", "ac"), kittens); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CollectionTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CollectionTest.java index d891088a4e..fb515f4bfb 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CollectionTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CollectionTest.java @@ -18,90 +18,108 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Before; import org.junit.Test; public class CollectionTest { - private final QCat cat = new QCat("cat"); - - private final QCat other = new QCat("other"); - - private List cats; - - @Before - public void setUp() { - Cat cat1 = new Cat("1"); - cat1.setKittens(Collections.singletonList(cat1)); - Cat cat2 = new Cat("2"); - cat2.setKittens(Arrays.asList(cat1, cat2)); - Cat cat3 = new Cat("3"); - cat3.setKittens(Arrays.asList(cat1, cat2, cat3)); - Cat cat4 = new Cat("4"); - cat4.setKittens(Arrays.asList(cat1, cat2, cat3, cat4)); - - cats = Arrays.asList(cat1, cat2, cat3, cat4); - } - - @Test - public void join() { - assertEquals("4", CollQueryFactory.from(cat, cats) - .innerJoin(cat.kittens, other) - .where(other.name.eq("4")).select(cat.name).fetchFirst()); - } - - @Test - public void join_from_two_sources() { - QCat catKittens = new QCat("cat_kittens"); - QCat otherKittens = new QCat("other_kittens"); - assertEquals(30, CollQueryFactory - .from(cat, cats).from(other, cats) - .innerJoin(cat.kittens, catKittens) - .innerJoin(other.kittens, otherKittens) - .where(catKittens.eq(otherKittens)).fetchCount()); - } - - @Test - public void any_uniqueResult() { - assertEquals("4", CollQueryFactory.from(cat, cats) - .where(cat.kittens.any().name.eq("4")).select(cat.name).fetchOne()); - } - - @Test - public void any_count() { - assertEquals(4, CollQueryFactory.from(cat, cats) - .where(cat.kittens.any().name.isNotNull()).fetchCount()); - } - - @Test - public void any_two_levels() { - assertEquals(4, CollQueryFactory.from(cat, cats).where( - cat.kittens.any().kittens.any().isNotNull()).fetchCount()); - } - - @Test - public void any_two_levels2() { - assertEquals(4, CollQueryFactory.from(cat, cats).where( - cat.kittens.any().name.isNotNull(), - cat.kittens.any().kittens.any().isNotNull()).fetchCount()); - } - - @Test - public void any_from_two_sources() { - assertEquals(16, CollQueryFactory.from(cat, cats).from(other, cats).where( - cat.kittens.any().name.eq(other.kittens.any().name)).fetchCount()); - } - - @Test - public void list_size() { - assertEquals(4, CollQueryFactory.from(cat, cats).where(cat.kittens.size().gt(0)).fetchCount()); - assertEquals(2, CollQueryFactory.from(cat, cats).where(cat.kittens.size().gt(2)).fetchCount()); - } - - @Test - public void list_is_empty() { - assertEquals(0, CollQueryFactory.from(cat, cats).where(cat.kittens.isEmpty()).fetchCount()); - } - + private final QCat cat = new QCat("cat"); + + private final QCat other = new QCat("other"); + + private List cats; + + @Before + public void setUp() { + Cat cat1 = new Cat("1"); + cat1.setKittens(Collections.singletonList(cat1)); + Cat cat2 = new Cat("2"); + cat2.setKittens(Arrays.asList(cat1, cat2)); + Cat cat3 = new Cat("3"); + cat3.setKittens(Arrays.asList(cat1, cat2, cat3)); + Cat cat4 = new Cat("4"); + cat4.setKittens(Arrays.asList(cat1, cat2, cat3, cat4)); + + cats = Arrays.asList(cat1, cat2, cat3, cat4); + } + + @Test + public void join() { + assertEquals( + "4", + CollQueryFactory.from(cat, cats) + .innerJoin(cat.kittens, other) + .where(other.name.eq("4")) + .select(cat.name) + .fetchFirst()); + } + + @Test + public void join_from_two_sources() { + QCat catKittens = new QCat("cat_kittens"); + QCat otherKittens = new QCat("other_kittens"); + assertEquals( + 30, + CollQueryFactory.from(cat, cats) + .from(other, cats) + .innerJoin(cat.kittens, catKittens) + .innerJoin(other.kittens, otherKittens) + .where(catKittens.eq(otherKittens)) + .fetchCount()); + } + + @Test + public void any_uniqueResult() { + assertEquals( + "4", + CollQueryFactory.from(cat, cats) + .where(cat.kittens.any().name.eq("4")) + .select(cat.name) + .fetchOne()); + } + + @Test + public void any_count() { + assertEquals( + 4, CollQueryFactory.from(cat, cats).where(cat.kittens.any().name.isNotNull()).fetchCount()); + } + + @Test + public void any_two_levels() { + assertEquals( + 4, + CollQueryFactory.from(cat, cats) + .where(cat.kittens.any().kittens.any().isNotNull()) + .fetchCount()); + } + + @Test + public void any_two_levels2() { + assertEquals( + 4, + CollQueryFactory.from(cat, cats) + .where(cat.kittens.any().name.isNotNull(), cat.kittens.any().kittens.any().isNotNull()) + .fetchCount()); + } + + @Test + public void any_from_two_sources() { + assertEquals( + 16, + CollQueryFactory.from(cat, cats) + .from(other, cats) + .where(cat.kittens.any().name.eq(other.kittens.any().name)) + .fetchCount()); + } + + @Test + public void list_size() { + assertEquals(4, CollQueryFactory.from(cat, cats).where(cat.kittens.size().gt(0)).fetchCount()); + assertEquals(2, CollQueryFactory.from(cat, cats).where(cat.kittens.size().gt(2)).fetchCount()); + } + + @Test + public void list_is_empty() { + assertEquals(0, CollQueryFactory.from(cat, cats).where(cat.kittens.isEmpty()).fetchCount()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Color.java b/querydsl-collections/src/test/java/com/querydsl/collections/Color.java index 1883b51df6..61bb6a4593 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Color.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Color.java @@ -14,5 +14,6 @@ package com.querydsl.collections; public enum Color { - BLACK, TABBY + BLACK, + TABBY } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Comment.java b/querydsl-collections/src/test/java/com/querydsl/collections/Comment.java index 97a838273e..a9078d01bf 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Comment.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Comment.java @@ -19,61 +19,59 @@ @QueryEntity public class Comment { - private int id; + private int id; - private String text; + private String text; - private User user; + private User user; - private Post post; + private Post post; - public Comment() { } + public Comment() {} - @QueryProjection - public Comment(int id, String text) { - this.id = id; - this.text = text; - } + @QueryProjection + public Comment(int id, String text) { + this.id = id; + this.text = text; + } - @QueryProjection - public Comment(int id, String text, User user, Post post) { - this.id = id; - this.text = text; - this.user = user; - this.post = post; - } + @QueryProjection + public Comment(int id, String text, User user, Post post) { + this.id = id; + this.text = text; + this.user = user; + this.post = post; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText(String text) { + this.text = text; + } - public User getUser() { - return user; - } + public User getUser() { + return user; + } - public void setUser(User user) { - this.user = user; - } + public void setUser(User user) { + this.user = user; + } - public Post getPost() { - return post; - } + public Post getPost() { + return post; + } - public void setPost(Post post) { - this.post = post; - } - - -} \ No newline at end of file + public void setPost(Post post) { + this.post = post; + } +} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/CompilationOverheadTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/CompilationOverheadTest.java index 34648d4b08..e314a365bf 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/CompilationOverheadTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/CompilationOverheadTest.java @@ -13,45 +13,42 @@ */ package com.querydsl.collections; +import com.querydsl.core.types.dsl.BooleanExpression; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Test; -import com.querydsl.core.types.dsl.BooleanExpression; - public class CompilationOverheadTest { - private static final QCat cat = QCat.cat; + private static final QCat cat = QCat.cat; - @Test - public void test() { - List conditions = Arrays.asList( + @Test + public void test() { + List conditions = + Arrays.asList( cat.mate.isNull(), cat.mate.isNotNull(), cat.mate.name.eq("Kitty"), cat.mate.name.ne("Kitty"), cat.mate.isNotNull().and(cat.mate.name.eq("Kitty")), - cat.mate.isNotNull().and(cat.mate.name.eq("Kitty")).and(cat.kittens.isEmpty()) - ); - - // 1st - for (BooleanExpression condition : conditions) { - query(condition); - } + cat.mate.isNotNull().and(cat.mate.name.eq("Kitty")).and(cat.kittens.isEmpty())); - // 2nd - for (BooleanExpression condition : conditions) { - query(condition); - } + // 1st + for (BooleanExpression condition : conditions) { + query(condition); } - private void query(BooleanExpression condition) { - long start = System.currentTimeMillis(); - CollQueryFactory.from(cat, Collections.emptyList()).where(condition).fetch(); - long duration = System.currentTimeMillis() - start; - System.out.println(condition + " : " + duration + "ms"); + // 2nd + for (BooleanExpression condition : conditions) { + query(condition); } - + } + + private void query(BooleanExpression condition) { + long start = System.currentTimeMillis(); + CollQueryFactory.from(cat, Collections.emptyList()).where(condition).fetch(); + long duration = System.currentTimeMillis() - start; + System.out.println(condition + " : " + duration + "ms"); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/DistinctTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/DistinctTest.java index 62dd48d5c2..565c3ba636 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/DistinctTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/DistinctTest.java @@ -15,51 +15,70 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.NumberPath; import java.util.Arrays; import java.util.List; - import org.junit.Test; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.NumberPath; - public class DistinctTest extends AbstractQueryTest { - private NumberPath intVar1 = Expressions.numberPath(Integer.class, "var1"); - private NumberPath intVar2 = Expressions.numberPath(Integer.class, "var2"); - private List list1 = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4, 4); - private List list2 = Arrays.asList(2, 2, 3, 3, 3, 4, 4, 4, 4, 4); - - @Test - public void singleSource() { - assertEquals(list1, CollQueryFactory.from(intVar1, list1).fetch()); - assertEquals(Arrays.asList(1, 2, 3, 4), CollQueryFactory.from(intVar1, list1).distinct().fetch()); - assertEquals(Arrays.asList(2, 3, 4), CollQueryFactory.from(intVar2, list2).distinct().fetch()); + private NumberPath intVar1 = Expressions.numberPath(Integer.class, "var1"); + private NumberPath intVar2 = Expressions.numberPath(Integer.class, "var2"); + private List list1 = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4, 4); + private List list2 = Arrays.asList(2, 2, 3, 3, 3, 4, 4, 4, 4, 4); - assertEquals(Arrays.asList(2, 3, 4), CollQueryFactory.from(intVar2, list2).distinct().fetch()); - } + @Test + public void singleSource() { + assertEquals(list1, CollQueryFactory.from(intVar1, list1).fetch()); + assertEquals( + Arrays.asList(1, 2, 3, 4), CollQueryFactory.from(intVar1, list1).distinct().fetch()); + assertEquals(Arrays.asList(2, 3, 4), CollQueryFactory.from(intVar2, list2).distinct().fetch()); - @Test - public void bothSources() { - assertEquals(100, CollQueryFactory.from(intVar1, list1).from(intVar2, list2).select(intVar1, intVar2).fetch().size()); - assertEquals(12, CollQueryFactory.from(intVar1, list1).from(intVar2, list2).distinct().select(intVar1, intVar2).fetch().size()); + assertEquals(Arrays.asList(2, 3, 4), CollQueryFactory.from(intVar2, list2).distinct().fetch()); + } - assertEquals(12, CollQueryFactory.from(intVar1, list1).from(intVar2, list2).distinct().select(intVar1, intVar2).fetch().size()); - } + @Test + public void bothSources() { + assertEquals( + 100, + CollQueryFactory.from(intVar1, list1) + .from(intVar2, list2) + .select(intVar1, intVar2) + .fetch() + .size()); + assertEquals( + 12, + CollQueryFactory.from(intVar1, list1) + .from(intVar2, list2) + .distinct() + .select(intVar1, intVar2) + .fetch() + .size()); - @Test - public void countDistinct() { - assertEquals(10, CollQueryFactory.from(intVar1, list1).fetchCount()); - assertEquals(4, CollQueryFactory.from(intVar1, list1).distinct().fetchCount()); - assertEquals(3, CollQueryFactory.from(intVar2, list2).distinct().fetchCount()); + assertEquals( + 12, + CollQueryFactory.from(intVar1, list1) + .from(intVar2, list2) + .distinct() + .select(intVar1, intVar2) + .fetch() + .size()); + } - assertEquals(3, CollQueryFactory.from(intVar2, list2).distinct().fetchCount()); - } + @Test + public void countDistinct() { + assertEquals(10, CollQueryFactory.from(intVar1, list1).fetchCount()); + assertEquals(4, CollQueryFactory.from(intVar1, list1).distinct().fetchCount()); + assertEquals(3, CollQueryFactory.from(intVar2, list2).distinct().fetchCount()); - @Test - public void null_() { - assertEquals(Arrays.asList(null, 1), - CollQueryFactory. from(intVar1, Arrays.asList(null, 1)).distinct().fetch()); - } + assertEquals(3, CollQueryFactory.from(intVar2, list2).distinct().fetchCount()); + } + @Test + public void null_() { + assertEquals( + Arrays.asList(null, 1), + CollQueryFactory.from(intVar1, Arrays.asList(null, 1)).distinct().fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Document.java b/querydsl-collections/src/test/java/com/querydsl/collections/Document.java index ca00156f36..2ea5169a8b 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Document.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Document.java @@ -1,31 +1,29 @@ package com.querydsl.collections; +import com.querydsl.core.annotations.QueryEntity; import java.util.ArrayList; import java.util.List; -import com.querydsl.core.annotations.QueryEntity; - @QueryEntity public class Document { - private Long id; - - private List meshThesaurusTerms = new ArrayList(); + private Long id; - public Long getId() { - return id; - } + private List meshThesaurusTerms = new ArrayList(); - public void setId(Long id) { - this.id = id; - } + public Long getId() { + return id; + } - public List getMeshThesaurusTerms() { - return meshThesaurusTerms; - } + public void setId(Long id) { + this.id = id; + } - public void setMeshThesaurusTerms(List meshThesaurusTerms) { - this.meshThesaurusTerms = meshThesaurusTerms; - } + public List getMeshThesaurusTerms() { + return meshThesaurusTerms; + } -} \ No newline at end of file + public void setMeshThesaurusTerms(List meshThesaurusTerms) { + this.meshThesaurusTerms = meshThesaurusTerms; + } +} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/DocumentTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/DocumentTest.java index f04c6e9fc5..94681e3711 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/DocumentTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/DocumentTest.java @@ -2,60 +2,61 @@ import static org.junit.Assert.assertTrue; +import com.querydsl.core.types.Predicate; import java.util.List; - import org.junit.Before; import org.junit.Test; -import com.querydsl.core.types.Predicate; - public class DocumentTest { - private Document doc1, doc2, doc3; - - private QDocument qDoc = QDocument.document; - - @Before - public void setUp() { - doc1 = new Document(); - doc1.setId(1L); - doc1.getMeshThesaurusTerms().add("x"); - - doc2 = new Document(); - doc2.setId(2L); - - doc3 = new Document(); - doc3.setId(3L); - } - - @Test - public void test1() { - Predicate crit = qDoc.id.eq(3L); - List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); - assertTrue(expResult.contains(doc3)); //ok - } - - @Test - public void test2() { - Predicate crit = qDoc.meshThesaurusTerms.any().eq("x"); - List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); - assertTrue(expResult.contains(doc1)); //ok - } - - @Test - public void test3() { - Predicate crit = qDoc.meshThesaurusTerms.any().eq("x").or(qDoc.id.eq(3L)); - List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); - assertTrue(expResult.contains(doc1)); - assertTrue(expResult.contains(doc3)); //fails, expResult contains only doc1, but should contain doc1 and doc3! - } - - @Test - public void test4() { - Predicate crit = qDoc.id.eq(3L).or(qDoc.meshThesaurusTerms.any().eq("x")); - List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); - assertTrue(expResult.contains(doc1)); - assertTrue(expResult.contains(doc3)); //fails, expResult contains only doc1, but should contain doc1 and doc3! - } - + private Document doc1, doc2, doc3; + + private QDocument qDoc = QDocument.document; + + @Before + public void setUp() { + doc1 = new Document(); + doc1.setId(1L); + doc1.getMeshThesaurusTerms().add("x"); + + doc2 = new Document(); + doc2.setId(2L); + + doc3 = new Document(); + doc3.setId(3L); + } + + @Test + public void test1() { + Predicate crit = qDoc.id.eq(3L); + List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); + assertTrue(expResult.contains(doc3)); // ok + } + + @Test + public void test2() { + Predicate crit = qDoc.meshThesaurusTerms.any().eq("x"); + List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); + assertTrue(expResult.contains(doc1)); // ok + } + + @Test + public void test3() { + Predicate crit = qDoc.meshThesaurusTerms.any().eq("x").or(qDoc.id.eq(3L)); + List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); + assertTrue(expResult.contains(doc1)); + assertTrue( + expResult.contains( + doc3)); // fails, expResult contains only doc1, but should contain doc1 and doc3! + } + + @Test + public void test4() { + Predicate crit = qDoc.id.eq(3L).or(qDoc.meshThesaurusTerms.any().eq("x")); + List expResult = CollQueryFactory.from(qDoc, doc1, doc2, doc3).where(crit).fetch(); + assertTrue(expResult.contains(doc1)); + assertTrue( + expResult.contains( + doc3)); // fails, expResult contains only doc1, but should contain doc1 and doc3! + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/ECJEvaluatorFactoryTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/ECJEvaluatorFactoryTest.java index f4bc4eae0c..5c8fe69ceb 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/ECJEvaluatorFactoryTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/ECJEvaluatorFactoryTest.java @@ -1,19 +1,17 @@ package com.querydsl.collections; -import org.junit.Test; - import com.querydsl.codegen.utils.ECJEvaluatorFactory; +import org.junit.Test; public class ECJEvaluatorFactoryTest extends AbstractQueryTest { - @Test - public void evaluator_factory() { - DefaultEvaluatorFactory evaluatorFactory = new DefaultEvaluatorFactory( - CollQueryTemplates.DEFAULT, - new ECJEvaluatorFactory(getClass().getClassLoader())); - QueryEngine queryEngine = new DefaultQueryEngine(evaluatorFactory); - CollQuery query = new CollQuery(queryEngine); - query.from(cat, cats).select(cat.name).fetch(); - } - + @Test + public void evaluator_factory() { + DefaultEvaluatorFactory evaluatorFactory = + new DefaultEvaluatorFactory( + CollQueryTemplates.DEFAULT, new ECJEvaluatorFactory(getClass().getClassLoader())); + QueryEngine queryEngine = new DefaultQueryEngine(evaluatorFactory); + CollQuery query = new CollQuery(queryEngine); + query.from(cat, cats).select(cat.name).fetch(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongId.java b/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongId.java index 6c34fa792a..7707284461 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongId.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongId.java @@ -6,18 +6,18 @@ @QueryEntity public class EntityWithLongId { - private Long id; + private Long id; - @QueryProjection - public EntityWithLongId(Long id) { - this.id = id; - } + @QueryProjection + public EntityWithLongId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongIdTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongIdTest.java index 20de545c38..6592e36c74 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongIdTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/EntityWithLongIdTest.java @@ -5,47 +5,51 @@ import java.util.Arrays; import java.util.List; - import org.junit.Test; public class EntityWithLongIdTest { - private List entities = Arrays.asList( - new EntityWithLongId(999L), - new EntityWithLongId(1000L), - new EntityWithLongId(1001L), - new EntityWithLongId(1003L) - ); - - @Test - public void simpleEquals() { - QEntityWithLongId root = QEntityWithLongId.entityWithLongId; - CollQuery query = new CollQuery().from(root, entities); - query.where(root.id.eq(1000L)); - - Long found = query.select(root.id).fetchFirst(); - assertNotNull(found); - assertEquals(found.longValue(), 1000); - } - - @Test - public void cartesianEquals() { - QEntityWithLongId root = new QEntityWithLongId("root1"); - QEntityWithLongId root2 = new QEntityWithLongId("root2"); - assertEquals(entities.size(), new CollQuery() - .from(root, entities).from(root2, entities) + private List entities = + Arrays.asList( + new EntityWithLongId(999L), + new EntityWithLongId(1000L), + new EntityWithLongId(1001L), + new EntityWithLongId(1003L)); + + @Test + public void simpleEquals() { + QEntityWithLongId root = QEntityWithLongId.entityWithLongId; + CollQuery query = new CollQuery().from(root, entities); + query.where(root.id.eq(1000L)); + + Long found = query.select(root.id).fetchFirst(); + assertNotNull(found); + assertEquals(found.longValue(), 1000); + } + + @Test + public void cartesianEquals() { + QEntityWithLongId root = new QEntityWithLongId("root1"); + QEntityWithLongId root2 = new QEntityWithLongId("root2"); + assertEquals( + entities.size(), + new CollQuery() + .from(root, entities) + .from(root2, entities) .where(root2.id.eq(root.id)) .fetchCount()); - } - - @Test - public void cartesianPlus1() { - QEntityWithLongId root = new QEntityWithLongId("root1"); - QEntityWithLongId root2 = new QEntityWithLongId("root2"); - assertEquals(2, new CollQuery() - .from(root, entities).from(root2, entities) + } + + @Test + public void cartesianPlus1() { + QEntityWithLongId root = new QEntityWithLongId("root1"); + QEntityWithLongId root2 = new QEntityWithLongId("root2"); + assertEquals( + 2, + new CollQuery() + .from(root, entities) + .from(root2, entities) .where(root2.id.eq(root.id.add(1))) .fetchCount()); - } - + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/EvaluatorTransformerTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/EvaluatorTransformerTest.java index e03d10ec9a..643ce7ec78 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/EvaluatorTransformerTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/EvaluatorTransformerTest.java @@ -15,28 +15,27 @@ import static org.junit.Assert.assertEquals; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.codegen.utils.Evaluator; import com.querydsl.core.DefaultQueryMetadata; import com.querydsl.core.QueryMetadata; +import java.util.Collections; +import org.junit.Test; public class EvaluatorTransformerTest { - private QueryMetadata metadata = new DefaultQueryMetadata(); - - @SuppressWarnings("unchecked") - @Test - public void test() { - DefaultEvaluatorFactory evaluatorFactory = new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); - QCat cat = QCat.cat; - Evaluator projectionEvaluator = evaluatorFactory.create(metadata, Collections.singletonList(cat), cat.name); - EvaluatorFunction transformer = new EvaluatorFunction(projectionEvaluator); - - Cat c = new Cat("Kitty"); - assertEquals("Kitty", transformer.apply(c)); - } - + private QueryMetadata metadata = new DefaultQueryMetadata(); + + @SuppressWarnings("unchecked") + @Test + public void test() { + DefaultEvaluatorFactory evaluatorFactory = + new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); + QCat cat = QCat.cat; + Evaluator projectionEvaluator = + evaluatorFactory.create(metadata, Collections.singletonList(cat), cat.name); + EvaluatorFunction transformer = new EvaluatorFunction(projectionEvaluator); + + Cat c = new Cat("Kitty"); + assertEquals("Kitty", transformer.apply(c)); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/FirstResultContractTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/FirstResultContractTest.java index 2ca9e8be78..369fce5021 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/FirstResultContractTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/FirstResultContractTest.java @@ -19,9 +19,8 @@ public class FirstResultContractTest extends AbstractQueryTest { - @Test - public void singleResult() { - assertNotNull(CollQueryFactory.from(cat, cats).where(cat.name.isNotNull()).fetchFirst()); - } - + @Test + public void singleResult() { + assertNotNull(CollQueryFactory.from(cat, cats).where(cat.name.isNotNull()).fetchFirst()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/FunctionalHelpersTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/FunctionalHelpersTest.java index d8c8d4434a..0857b02958 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/FunctionalHelpersTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/FunctionalHelpersTest.java @@ -1,28 +1,26 @@ package com.querydsl.collections; -import org.junit.Test; - -import java.util.function.Function; -import java.util.function.Predicate; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -public class FunctionalHelpersTest { +import java.util.function.Function; +import java.util.function.Predicate; +import org.junit.Test; - @Test - public void predicate() { - Predicate predicate = FunctionalHelpers.wrap(QCat.cat.name.startsWith("Ann")); - assertTrue(predicate.test(new Cat("Ann"))); - assertFalse(predicate.test(new Cat("Bob"))); - } +public class FunctionalHelpersTest { - @Test - public void function() { - Function function = FunctionalHelpers.wrap(QCat.cat.name); - assertEquals("Ann", function.apply(new Cat("Ann"))); - assertEquals("Bob", function.apply(new Cat("Bob"))); - } + @Test + public void predicate() { + Predicate predicate = FunctionalHelpers.wrap(QCat.cat.name.startsWith("Ann")); + assertTrue(predicate.test(new Cat("Ann"))); + assertFalse(predicate.test(new Cat("Bob"))); + } + @Test + public void function() { + Function function = FunctionalHelpers.wrap(QCat.cat.name); + assertEquals("Ann", function.apply(new Cat("Ann"))); + assertEquals("Bob", function.apply(new Cat("Bob"))); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy2Test.java b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy2Test.java index 1f9208656c..60b13358c5 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy2Test.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy2Test.java @@ -4,156 +4,155 @@ import static com.querydsl.core.group.GroupBy.map; import static org.junit.Assert.assertEquals; +import com.querydsl.core.annotations.QueryEntity; +import com.querydsl.core.annotations.QueryProjection; +import com.querydsl.core.group.GroupBy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; - import org.junit.Before; import org.junit.Test; -import com.querydsl.core.annotations.QueryEntity; -import com.querydsl.core.annotations.QueryProjection; -import com.querydsl.core.group.GroupBy; - public class GroupBy2Test { -// select u1.id,u1.name,r1.id,r1.name,s1.name from users u1 -// join roles r1 on u1.role = r1.id -// join security_groups s1 on r1.secgroup = s1.id - - @QueryEntity - public static class User { - public Long id; - public String name; - public List roles; + // select u1.id,u1.name,r1.id,r1.name,s1.name from users u1 + // join roles r1 on u1.role = r1.id + // join security_groups s1 on r1.secgroup = s1.id + + @QueryEntity + public static class User { + public Long id; + public String name; + public List roles; + } + + @QueryEntity + public static class Role { + public Long id; + public String name; + public List groups; + } + + @QueryEntity + public static class SecurityGroup { + public Long id; + public String name; + + public SecurityGroup(Long id, String name) { + this.id = id; + this.name = name; } - - @QueryEntity - public static class Role { - public Long id; - public String name; - public List groups; + } + + public static class UserDto { + public Long id; + public String name; + public List roleIds; + public List roleNames; + public List secIds; + + @QueryProjection + public UserDto( + Long id, String name, List roleIds, List roleNames, List secIds) { + this.id = id; + this.name = name; + this.roleIds = roleIds; + this.roleNames = roleNames; + this.secIds = secIds; } - @QueryEntity - public static class SecurityGroup { - public Long id; - public String name; - - public SecurityGroup(Long id, String name) { - this.id = id; - this.name = name; - } + @QueryProjection + public UserDto(Long id, String name, Map roles, Map groups) { + this.id = id; + this.name = name; + this.roleIds = new ArrayList<>(roles.keySet()); + this.roleNames = new ArrayList<>(roles.values()); + this.secIds = new ArrayList<>(groups.keySet()); } - - public static class UserDto { - public Long id; - public String name; - public List roleIds; - public List roleNames; - public List secIds; - - @QueryProjection - public UserDto(Long id, String name, List roleIds, List roleNames, List secIds) { - this.id = id; - this.name = name; - this.roleIds = roleIds; - this.roleNames = roleNames; - this.secIds = secIds; - } - - @QueryProjection - public UserDto(Long id, String name, Map roles, Map groups) { - this.id = id; - this.name = name; - this.roleIds = new ArrayList<>(roles.keySet()); - this.roleNames = new ArrayList<>(roles.values()); - this.secIds = new ArrayList<>(groups.keySet()); - } - } - - private List users; - - @Before - public void setUp() { - Role r1 = new Role(); - r1.id = 1L; - r1.name = "User"; - r1.groups = Arrays.asList(new SecurityGroup(1L, "User 1")); - - Role r2 = new Role(); - r2.id = 2L; - r2.name = null; // NOTE this is null on purpose - r2.groups = Arrays.asList(new SecurityGroup(2L, "Admin 1"), - new SecurityGroup(3L, "Admin 2")); - - User u1 = new User(); - u1.id = 3L; - u1.name = "Bob"; - u1.roles = Arrays.asList(r1); - - User u2 = new User(); - u2.id = 32L; - u2.name = "Ann"; - u2.roles = Arrays.asList(r1, r2); - - users = Arrays.asList(u1, u2); - } - - @Test - public void test() { - QGroupBy2Test_User user = QGroupBy2Test_User.user; - QGroupBy2Test_Role role = QGroupBy2Test_Role.role; - QGroupBy2Test_SecurityGroup group = QGroupBy2Test_SecurityGroup.securityGroup; - - Map userDtos = CollQueryFactory.from(user, users) - .innerJoin(user.roles, role) - .innerJoin(role.groups, group) - .transform(GroupBy.groupBy(user.id) - .as(new QGroupBy2Test_UserDto( - user.id, - user.name, - list(role.id), - list(role.name), - list(group.id)))); - - UserDto dto1 = userDtos.get(3L); - assertEquals(1, dto1.roleIds.size()); - assertEquals(1, dto1.roleNames.size()); - assertEquals(1, dto1.secIds.size()); - - UserDto dto2 = userDtos.get(32L); - assertEquals(3, dto2.roleIds.size()); - assertEquals(1, dto2.roleNames.size()); - assertEquals(3, dto2.secIds.size()); - } - - @Test - public void test2() { - QGroupBy2Test_User user = QGroupBy2Test_User.user; - QGroupBy2Test_Role role = QGroupBy2Test_Role.role; - QGroupBy2Test_SecurityGroup group = QGroupBy2Test_SecurityGroup.securityGroup; - - Map userDtos = CollQueryFactory.from(user, users) - .innerJoin(user.roles, role) - .innerJoin(role.groups, group) - .transform(GroupBy.groupBy(user.id) - .as(new QGroupBy2Test_UserDto( + } + + private List users; + + @Before + public void setUp() { + Role r1 = new Role(); + r1.id = 1L; + r1.name = "User"; + r1.groups = Arrays.asList(new SecurityGroup(1L, "User 1")); + + Role r2 = new Role(); + r2.id = 2L; + r2.name = null; // NOTE this is null on purpose + r2.groups = Arrays.asList(new SecurityGroup(2L, "Admin 1"), new SecurityGroup(3L, "Admin 2")); + + User u1 = new User(); + u1.id = 3L; + u1.name = "Bob"; + u1.roles = Arrays.asList(r1); + + User u2 = new User(); + u2.id = 32L; + u2.name = "Ann"; + u2.roles = Arrays.asList(r1, r2); + + users = Arrays.asList(u1, u2); + } + + @Test + public void test() { + QGroupBy2Test_User user = QGroupBy2Test_User.user; + QGroupBy2Test_Role role = QGroupBy2Test_Role.role; + QGroupBy2Test_SecurityGroup group = QGroupBy2Test_SecurityGroup.securityGroup; + + Map userDtos = + CollQueryFactory.from(user, users) + .innerJoin(user.roles, role) + .innerJoin(role.groups, group) + .transform( + GroupBy.groupBy(user.id) + .as( + new QGroupBy2Test_UserDto( + user.id, user.name, list(role.id), list(role.name), list(group.id)))); + + UserDto dto1 = userDtos.get(3L); + assertEquals(1, dto1.roleIds.size()); + assertEquals(1, dto1.roleNames.size()); + assertEquals(1, dto1.secIds.size()); + + UserDto dto2 = userDtos.get(32L); + assertEquals(3, dto2.roleIds.size()); + assertEquals(1, dto2.roleNames.size()); + assertEquals(3, dto2.secIds.size()); + } + + @Test + public void test2() { + QGroupBy2Test_User user = QGroupBy2Test_User.user; + QGroupBy2Test_Role role = QGroupBy2Test_Role.role; + QGroupBy2Test_SecurityGroup group = QGroupBy2Test_SecurityGroup.securityGroup; + + Map userDtos = + CollQueryFactory.from(user, users) + .innerJoin(user.roles, role) + .innerJoin(role.groups, group) + .transform( + GroupBy.groupBy(user.id) + .as( + new QGroupBy2Test_UserDto( user.id, user.name, map(role.id, role.name), map(group.id, group.name)))); - UserDto dto1 = userDtos.get(3L); - assertEquals(1, dto1.roleIds.size()); - assertEquals(1, dto1.roleNames.size()); - assertEquals(1, dto1.secIds.size()); - - UserDto dto2 = userDtos.get(32L); - assertEquals(2, dto2.roleIds.size()); - assertEquals(2, dto2.roleNames.size()); - assertEquals(3, dto2.secIds.size()); - } + UserDto dto1 = userDtos.get(3L); + assertEquals(1, dto1.roleIds.size()); + assertEquals(1, dto1.roleNames.size()); + assertEquals(1, dto1.secIds.size()); + UserDto dto2 = userDtos.get(32L); + assertEquals(2, dto2.roleIds.size()); + assertEquals(2, dto2.roleNames.size()); + assertEquals(3, dto2.secIds.size()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy3Test.java b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy3Test.java index 362c5ffc33..c1bfe4ed93 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy3Test.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy3Test.java @@ -4,98 +4,105 @@ import static com.querydsl.core.group.GroupBy.set; import static org.easymock.EasyMock.*; -import java.util.Map; -import java.util.Set; - -import org.junit.Test; - import com.mysema.commons.lang.CloseableIterator; import com.querydsl.core.FetchableQuery; import com.querydsl.core.ResultTransformer; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.group.Group; import com.querydsl.core.types.Projections; +import java.util.Map; +import java.util.Set; +import org.junit.Test; public class GroupBy3Test { - @QueryEntity - public static class RiskAnalysis { - public String id; - public Set assetThreats; - } - - @QueryEntity - public static class AssetThreat { - public String id; - public Set threats; - } - - @QueryEntity - public static class Threat { - public String id; - } - - @Test - public void nested_expressions() { - QGroupBy3Test_RiskAnalysis riskAnalysis = QGroupBy3Test_RiskAnalysis.riskAnalysis; - QGroupBy3Test_AssetThreat assetThreat = QGroupBy3Test_AssetThreat.assetThreat; - QGroupBy3Test_Threat threat = QGroupBy3Test_Threat.threat; - - ResultTransformer> transformer = - groupBy(riskAnalysis.id) - .as(Projections.bean(RiskAnalysis.class, - riskAnalysis.id, - set(Projections.bean(AssetThreat.class, - assetThreat.id, - set(Projections.bean(Threat.class, threat.id)).as("threats"))) - .as("assetThreats"))); - - CloseableIterator iter = createMock(CloseableIterator.class); - FetchableQuery projectable = createMock(FetchableQuery.class); - expect(projectable.select(Projections.tuple( - riskAnalysis.id, + @QueryEntity + public static class RiskAnalysis { + public String id; + public Set assetThreats; + } + + @QueryEntity + public static class AssetThreat { + public String id; + public Set threats; + } + + @QueryEntity + public static class Threat { + public String id; + } + + @Test + public void nested_expressions() { + QGroupBy3Test_RiskAnalysis riskAnalysis = QGroupBy3Test_RiskAnalysis.riskAnalysis; + QGroupBy3Test_AssetThreat assetThreat = QGroupBy3Test_AssetThreat.assetThreat; + QGroupBy3Test_Threat threat = QGroupBy3Test_Threat.threat; + + ResultTransformer> transformer = + groupBy(riskAnalysis.id) + .as( + Projections.bean( + RiskAnalysis.class, + riskAnalysis.id, + set(Projections.bean( + AssetThreat.class, + assetThreat.id, + set(Projections.bean(Threat.class, threat.id)).as("threats"))) + .as("assetThreats"))); + + CloseableIterator iter = createMock(CloseableIterator.class); + FetchableQuery projectable = createMock(FetchableQuery.class); + expect( + projectable.select( + Projections.tuple( + riskAnalysis.id, + riskAnalysis.id, + assetThreat.id, + Projections.bean(Threat.class, threat.id)))) + .andReturn(projectable); + expect(projectable.iterate()).andReturn(iter); + expect(iter.hasNext()).andReturn(false); + iter.close(); + replay(iter, projectable); + + transformer.transform(projectable); + verify(projectable); + } + + @Test + public void alias_usage() { + QGroupBy3Test_RiskAnalysis riskAnalysis = QGroupBy3Test_RiskAnalysis.riskAnalysis; + QGroupBy3Test_AssetThreat assetThreat = QGroupBy3Test_AssetThreat.assetThreat; + QGroupBy3Test_Threat threat = QGroupBy3Test_Threat.threat; + + ResultTransformer> transformer = + groupBy(riskAnalysis.id) + .as( riskAnalysis.id, - assetThreat.id, - Projections.bean(Threat.class, threat.id)))) - .andReturn(projectable); - expect(projectable.iterate()).andReturn(iter); - expect(iter.hasNext()).andReturn(false); - iter.close(); - replay(iter, projectable); - - transformer.transform(projectable); - verify(projectable); - } - - @Test - public void alias_usage() { - QGroupBy3Test_RiskAnalysis riskAnalysis = QGroupBy3Test_RiskAnalysis.riskAnalysis; - QGroupBy3Test_AssetThreat assetThreat = QGroupBy3Test_AssetThreat.assetThreat; - QGroupBy3Test_Threat threat = QGroupBy3Test_Threat.threat; - - ResultTransformer> transformer = - groupBy(riskAnalysis.id) - .as(riskAnalysis.id, - set(Projections.bean(AssetThreat.class, - assetThreat.id, - set(Projections.bean(Threat.class, threat.id)).as("threats")) - .as("assetThreats"))); - - CloseableIterator iter = createMock(CloseableIterator.class); - FetchableQuery projectable = createMock(FetchableQuery.class); - expect(projectable.select(Projections.tuple( - riskAnalysis.id, - riskAnalysis.id, - assetThreat.id, - Projections.bean(Threat.class, threat.id)))) - .andReturn(projectable); - expect(projectable.iterate()).andReturn(iter); - expect(iter.hasNext()).andReturn(false); - iter.close(); - replay(iter, projectable); - - transformer.transform(projectable); - verify(projectable); - } - + set( + Projections.bean( + AssetThreat.class, + assetThreat.id, + set(Projections.bean(Threat.class, threat.id)).as("threats")) + .as("assetThreats"))); + + CloseableIterator iter = createMock(CloseableIterator.class); + FetchableQuery projectable = createMock(FetchableQuery.class); + expect( + projectable.select( + Projections.tuple( + riskAnalysis.id, + riskAnalysis.id, + assetThreat.id, + Projections.bean(Threat.class, threat.id)))) + .andReturn(projectable); + expect(projectable.iterate()).andReturn(iter); + expect(iter.hasNext()).andReturn(false); + iter.close(); + replay(iter, projectable); + + transformer.transform(projectable); + verify(projectable); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy4Test.java b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy4Test.java index 16d4f79084..478e308748 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy4Test.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/GroupBy4Test.java @@ -14,6 +14,11 @@ package com.querydsl.collections; +import static com.querydsl.core.group.GroupBy.list; +import static com.querydsl.core.group.guava.GuavaGroupBy.groupBy; +import static com.querydsl.core.group.guava.GuavaGroupBy.map; +import static org.junit.Assert.assertEquals; + import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -23,251 +28,295 @@ import com.google.common.collect.Multimap; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.group.guava.GuavaGroupBy; -import org.junit.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; - -import static com.querydsl.core.group.GroupBy.list; -import static com.querydsl.core.group.guava.GuavaGroupBy.groupBy; -import static com.querydsl.core.group.guava.GuavaGroupBy.map; -import static org.junit.Assert.assertEquals; - +import org.junit.Test; public class GroupBy4Test { - @QueryEntity - public static class Table { - String col1, col2, col3; - - public Table(String c1, String c2, String c3) { - col1 = c1; - col2 = c2; - col3 = c3; - } - } - - @Test - public void test() { - List data = new ArrayList<>(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - Map> grouped = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).as(map(table.col2, table.col3))); - - assertEquals(3, grouped.size()); - assertEquals(2, grouped.get("1").size()); - assertEquals(new HashSet<>(Arrays.asList("abc", "pqr")), grouped.get("1").keySet()); - - } + @QueryEntity + public static class Table { + String col1, col2, col3; - @Test - public void test2() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - Multimap transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).asMultimap(table.col2)); - - Multimap expected = HashMultimap.create( - ImmutableMultimap. builder() - .putAll("1", "abc", "pqr") - .putAll("2", "abc", "pqr") - .putAll("3", "abc", "pqr") - .build()); - - assertEquals(expected, transform); + public Table(String c1, String c2, String c3) { + col1 = c1; + col2 = c2; + col3 = c3; } - - @Test - public void test3() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - Multimap> transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).asMultimap( - map(table.col2, table.col3) - )); - - HashMultimap> expected = HashMultimap.create(ImmutableMultimap.>builder() + } + + @Test + public void test() { + List
data = new ArrayList<>(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + Map> grouped = + CollQueryFactory.from(table, data) + .transform(groupBy(table.col1).as(map(table.col2, table.col3))); + + assertEquals(3, grouped.size()); + assertEquals(2, grouped.get("1").size()); + assertEquals(new HashSet<>(Arrays.asList("abc", "pqr")), grouped.get("1").keySet()); + } + + @Test + public void test2() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + Multimap transform = + CollQueryFactory.from(table, data).transform(groupBy(table.col1).asMultimap(table.col2)); + + Multimap expected = + HashMultimap.create( + ImmutableMultimap.builder() + .putAll("1", "abc", "pqr") + .putAll("2", "abc", "pqr") + .putAll("3", "abc", "pqr") + .build()); + + assertEquals(expected, transform); + } + + @Test + public void test3() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + Multimap> transform = + CollQueryFactory.from(table, data) + .transform(groupBy(table.col1).asMultimap(map(table.col2, table.col3))); + + HashMultimap> expected = + HashMultimap.create( + ImmutableMultimap.>builder() .putAll("1", ImmutableMap.of("abc", "111"), ImmutableMap.of("pqr", "222")) .putAll("2", ImmutableMap.of("abc", "333"), ImmutableMap.of("pqr", "444")) .putAll("3", ImmutableMap.of("abc", "555"), ImmutableMap.of("pqr", "666")) - .build() - ); - - assertEquals(expected, transform); - } - - @Test - public void test4() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - com.google.common.collect.Table transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).asTable(table.col2, table.col3)); - - ImmutableTable expected = ImmutableTable. builder() - .put("1", "abc", "111") - .put("1", "pqr", "222") - .put("2", "abc", "333") - .put("2", "pqr", "444") - .put("3", "abc", "555") - .put("3", "pqr", "666") - .build(); - - assertEquals(expected, transform); - } - - @Test - public void test5() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - data.add(new Table("3", "pqr", "777")); - - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - com.google.common.collect.Table> transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).asTable(table.col2, list(table.col3))); - - ImmutableTable> expected = ImmutableTable.> builder() - .put("1", "abc", ImmutableList.of("111")) - .put("1", "pqr", ImmutableList.of("222")) - .put("2", "abc", ImmutableList.of("333")) - .put("2", "pqr", ImmutableList.of("444")) - .put("3", "abc", ImmutableList.of("555")) - .put("3", "pqr", ImmutableList.of("666", "777")) - .build(); - - assertEquals(expected, transform); - } - - @Test - public void test6() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - data.add(new Table("3", "pqr", "777")); - - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - Map> transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).as(GuavaGroupBy.multimap(table.col2, table.col3))); - - ImmutableMap> expected = ImmutableMap.> builder() - .put("1", HashMultimap.create(ImmutableMultimap. builder().putAll("abc", "111").putAll("pqr", "222").build())) - .put("2", HashMultimap.create(ImmutableMultimap. builder().putAll("abc", "333").putAll("pqr", "444").build())) - .put("3", HashMultimap.create(ImmutableMultimap. builder().putAll("abc", "555").putAll("pqr", "666", "777").build())) - .build(); - - assertEquals(expected, transform); - } - - @Test - public void test7() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - data.add(new Table("3", "pqr", "777")); - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - Map>>> transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).as(GuavaGroupBy.table( - table.col1, table.col2, map(table.col2, list(table.col3))))); - - ImmutableMap>>> expected = - ImmutableMap.>>>builder() - .put("1", ImmutableTable.>>builder() - .put("1", "abc", ImmutableMap.> of("abc", ImmutableList.of("111"))) - .put("1", "pqr", ImmutableMap.> of("pqr", ImmutableList.of("222"))) + .build()); + + assertEquals(expected, transform); + } + + @Test + public void test4() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + com.google.common.collect.Table transform = + CollQueryFactory.from(table, data) + .transform(groupBy(table.col1).asTable(table.col2, table.col3)); + + ImmutableTable expected = + ImmutableTable.builder() + .put("1", "abc", "111") + .put("1", "pqr", "222") + .put("2", "abc", "333") + .put("2", "pqr", "444") + .put("3", "abc", "555") + .put("3", "pqr", "666") + .build(); + + assertEquals(expected, transform); + } + + @Test + public void test5() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + data.add(new Table("3", "pqr", "777")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + com.google.common.collect.Table> transform = + CollQueryFactory.from(table, data) + .transform(groupBy(table.col1).asTable(table.col2, list(table.col3))); + + ImmutableTable> expected = + ImmutableTable.>builder() + .put("1", "abc", ImmutableList.of("111")) + .put("1", "pqr", ImmutableList.of("222")) + .put("2", "abc", ImmutableList.of("333")) + .put("2", "pqr", ImmutableList.of("444")) + .put("3", "abc", ImmutableList.of("555")) + .put("3", "pqr", ImmutableList.of("666", "777")) + .build(); + + assertEquals(expected, transform); + } + + @Test + public void test6() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + data.add(new Table("3", "pqr", "777")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + Map> transform = + CollQueryFactory.from(table, data) + .transform(groupBy(table.col1).as(GuavaGroupBy.multimap(table.col2, table.col3))); + + ImmutableMap> expected = + ImmutableMap.>builder() + .put( + "1", + HashMultimap.create( + ImmutableMultimap.builder() + .putAll("abc", "111") + .putAll("pqr", "222") + .build())) + .put( + "2", + HashMultimap.create( + ImmutableMultimap.builder() + .putAll("abc", "333") + .putAll("pqr", "444") + .build())) + .put( + "3", + HashMultimap.create( + ImmutableMultimap.builder() + .putAll("abc", "555") + .putAll("pqr", "666", "777") + .build())) + .build(); + + assertEquals(expected, transform); + } + + @Test + public void test7() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + data.add(new Table("3", "pqr", "777")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + Map>>> + transform = + CollQueryFactory.from(table, data) + .transform( + groupBy(table.col1) + .as( + GuavaGroupBy.table( + table.col1, table.col2, map(table.col2, list(table.col3))))); + + ImmutableMap>>> + expected = + ImmutableMap + .>>> + builder() + .put( + "1", + ImmutableTable.>>builder() + .put( + "1", + "abc", + ImmutableMap.>of("abc", ImmutableList.of("111"))) + .put( + "1", + "pqr", + ImmutableMap.>of("pqr", ImmutableList.of("222"))) .build()) - .put("2", ImmutableTable.>>builder() - .put("2", "abc", ImmutableMap.> of("abc", ImmutableList.of("333"))) - .put("2", "pqr", ImmutableMap.> of("pqr", ImmutableList.of("444"))) + .put( + "2", + ImmutableTable.>>builder() + .put( + "2", + "abc", + ImmutableMap.>of("abc", ImmutableList.of("333"))) + .put( + "2", + "pqr", + ImmutableMap.>of("pqr", ImmutableList.of("444"))) .build()) - .put("3", ImmutableTable.>>builder() - .put("3", "abc", ImmutableMap.> of("abc", ImmutableList.of("555"))) - .put("3", "pqr", ImmutableMap.> of("pqr", ImmutableList.of("666", "777"))) + .put( + "3", + ImmutableTable.>>builder() + .put( + "3", + "abc", + ImmutableMap.>of("abc", ImmutableList.of("555"))) + .put( + "3", + "pqr", + ImmutableMap.>of( + "pqr", ImmutableList.of("666", "777"))) .build()) .build(); - assertEquals(expected, transform); - } - - @Test - public void test8() { - List
data = Lists.newArrayList(); - data.add(new Table("1", "abc", "111")); - data.add(new Table("1", "pqr", "222")); - data.add(new Table("2", "abc", "333")); - data.add(new Table("2", "pqr", "444")); - data.add(new Table("3", "abc", "555")); - data.add(new Table("3", "pqr", "666")); - data.add(new Table("3", "pqr", "777")); - - QGroupBy4Test_Table table = QGroupBy4Test_Table.table; - com.google.common.collect.Table, List> transform = CollQueryFactory - .from(table, data) - .transform(groupBy(table.col1).asTable(map(table.col1, table.col2), GuavaGroupBy.list(table.col3))); - - ImmutableTable, List> expected = ImmutableTable., List> builder() - .put("1", ImmutableMap.of("1", "abc"), ImmutableList.of("111")) - .put("1", ImmutableMap.of("1", "pqr"), ImmutableList.of("222")) - .put("2", ImmutableMap.of("2", "abc"), ImmutableList.of("333")) - .put("2", ImmutableMap.of("2", "pqr"), ImmutableList.of("444")) - .put("3", ImmutableMap.of("3", "abc"), ImmutableList.of("555")) - .put("3", ImmutableMap.of("3", "pqr"), ImmutableList.of("666", "777")) - .build(); - - assertEquals(expected, transform); - } - + assertEquals(expected, transform); + } + + @Test + public void test8() { + List
data = Lists.newArrayList(); + data.add(new Table("1", "abc", "111")); + data.add(new Table("1", "pqr", "222")); + data.add(new Table("2", "abc", "333")); + data.add(new Table("2", "pqr", "444")); + data.add(new Table("3", "abc", "555")); + data.add(new Table("3", "pqr", "666")); + data.add(new Table("3", "pqr", "777")); + + QGroupBy4Test_Table table = QGroupBy4Test_Table.table; + com.google.common.collect.Table, List> transform = + CollQueryFactory.from(table, data) + .transform( + groupBy(table.col1) + .asTable(map(table.col1, table.col2), GuavaGroupBy.list(table.col3))); + + ImmutableTable, List> expected = + ImmutableTable., List>builder() + .put("1", ImmutableMap.of("1", "abc"), ImmutableList.of("111")) + .put("1", ImmutableMap.of("1", "pqr"), ImmutableList.of("222")) + .put("2", ImmutableMap.of("2", "abc"), ImmutableList.of("333")) + .put("2", ImmutableMap.of("2", "pqr"), ImmutableList.of("444")) + .put("3", ImmutableMap.of("3", "abc"), ImmutableList.of("555")) + .put("3", ImmutableMap.of("3", "pqr"), ImmutableList.of("666", "777")) + .build(); + + assertEquals(expected, transform); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/GroupByTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/GroupByTest.java index f88d0d8323..b788acbc67 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/GroupByTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/GroupByTest.java @@ -13,264 +13,316 @@ */ package com.querydsl.collections; - import static com.querydsl.core.group.GroupBy.*; import static org.junit.Assert.*; -import java.util.*; - -import org.junit.Ignore; -import org.junit.Test; - import com.querydsl.core.group.Group; import com.querydsl.core.types.ConstructorExpression; import com.querydsl.core.types.Projections; +import java.util.*; +import org.junit.Ignore; +import org.junit.Test; public class GroupByTest { - private static final List users = Arrays.asList(new User("Bob"), new User("Jane"), new User("Jack")); + private static final List users = + Arrays.asList(new User("Bob"), new User("Jane"), new User("Jack")); - private static final List posts = Arrays.asList( - new Post(1, "Post 1", users.get(0)), - new Post(2, "Post 2", users.get(0)), - new Post(3, "Post 3", users.get(1))); + private static final List posts = + Arrays.asList( + new Post(1, "Post 1", users.get(0)), + new Post(2, "Post 2", users.get(0)), + new Post(3, "Post 3", users.get(1))); - private static final List comments = Arrays.asList( - new Comment(1, "Comment 1", users.get(0), posts.get(0)), - new Comment(2, "Comment 2", users.get(1), posts.get(1)), - new Comment(3, "Comment 3", users.get(2), posts.get(1)), - new Comment(4, "Comment 4", users.get(0), posts.get(2)), - new Comment(5, "Comment 5", users.get(1), posts.get(2)), - new Comment(6, "Comment 6", users.get(2), posts.get(2))); + private static final List comments = + Arrays.asList( + new Comment(1, "Comment 1", users.get(0), posts.get(0)), + new Comment(2, "Comment 2", users.get(1), posts.get(1)), + new Comment(3, "Comment 3", users.get(2), posts.get(1)), + new Comment(4, "Comment 4", users.get(0), posts.get(2)), + new Comment(5, "Comment 5", users.get(1), posts.get(2)), + new Comment(6, "Comment 6", users.get(2), posts.get(2))); - private static final QUser user = QUser.user; + private static final QUser user = QUser.user; - private static final QComment comment = QComment.comment; + private static final QComment comment = QComment.comment; - private static final QPost post = QPost.post; + private static final QPost post = QPost.post; - private static final ConstructorExpression qComment = QComment.create(comment.id, comment.text); + private static final ConstructorExpression qComment = + QComment.create(comment.id, comment.text); - @Test - public void group_min() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + @Test + public void group_min() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(min(comment.text))); - assertEquals("Comment 1", results.get(1)); - assertEquals("Comment 2", results.get(2)); - assertEquals("Comment 4", results.get(3)); - } + assertEquals("Comment 1", results.get(1)); + assertEquals("Comment 2", results.get(2)); + assertEquals("Comment 4", results.get(3)); + } - public void comments_by_post() { - Map> results = CollQueryFactory.from(post, posts).from(comment, comments) - .where(comment.post.id.eq(post.id)) - .transform(groupBy(post.id).as(list(comment))); - - assertEquals(1, results.get(1).size()); - assertEquals(2, results.get(2).size()); - assertEquals(3, results.get(3).size()); - } - - @Test - public void group_max() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + public void comments_by_post() { + Map> results = + CollQueryFactory.from(post, posts) + .from(comment, comments) + .where(comment.post.id.eq(post.id)) + .transform(groupBy(post.id).as(list(comment))); + + assertEquals(1, results.get(1).size()); + assertEquals(2, results.get(2).size()); + assertEquals(3, results.get(3).size()); + } + + @Test + public void group_max() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(max(comment.text))); - assertEquals("Comment 1", results.get(1)); - assertEquals("Comment 3", results.get(2)); - assertEquals("Comment 6", results.get(3)); - } - - @Test - public void group_sum() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) - .where(comment.post.id.eq(post.id)) - .transform(groupBy(post.id).as(sum(comment.id))); - - assertEquals(1, results.get(1).intValue()); - assertEquals(5, results.get(2).intValue()); - assertEquals(15, results.get(3).intValue()); - } - - @Test - public void group_avg() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) - .where(comment.post.id.eq(post.id)) - .transform(groupBy(post.id).as(avg(comment.id))); - - assertEquals(1, results.get(1).intValue()); - assertEquals(2, results.get(2).intValue()); - assertEquals(5, results.get(3).intValue()); - } - - @Test - public void group_order() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + assertEquals("Comment 1", results.get(1)); + assertEquals("Comment 3", results.get(2)); + assertEquals("Comment 6", results.get(3)); + } + + @Test + public void group_sum() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) + .where(comment.post.id.eq(post.id)) + .transform(groupBy(post.id).as(sum(comment.id))); + + assertEquals(1, results.get(1).intValue()); + assertEquals(5, results.get(2).intValue()); + assertEquals(15, results.get(3).intValue()); + } + + @Test + public void group_avg() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) + .where(comment.post.id.eq(post.id)) + .transform(groupBy(post.id).as(avg(comment.id))); + + assertEquals(1, results.get(1).intValue()); + assertEquals(2, results.get(2).intValue()); + assertEquals(5, results.get(3).intValue()); + } + + @Test + public void group_order() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, set(comment.id))); - assertEquals(3, results.size()); - } + assertEquals(3, results.size()); + } - @Test - public void first_set_and_list() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + @Test + public void first_set_and_list() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, set(comment.id), list(comment.text))); - Group group = results.get(1); - assertEquals(toInt(1), group.getOne(post.id)); - assertEquals("Post 1", group.getOne(post.name)); - assertEquals(toSet(1), group.getSet(comment.id)); - assertEquals(Collections.singletonList("Comment 1"), group.getList(comment.text)); - } - - @Test - @Ignore - public void group_by_null() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + Group group = results.get(1); + assertEquals(toInt(1), group.getOne(post.id)); + assertEquals("Post 1", group.getOne(post.name)); + assertEquals(toSet(1), group.getSet(comment.id)); + assertEquals(Collections.singletonList("Comment 1"), group.getList(comment.text)); + } + + @Test + @Ignore + public void group_by_null() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, set(comment.id), list(comment.text))); - Group group = results.get(null); - assertNull(group.getOne(post.id)); - assertEquals("null post", group.getOne(post.name)); - assertEquals(toSet(7, 8), group.getSet(comment.id)); - assertEquals(Arrays.asList("comment 7", "comment 8"), group.getList(comment.text)); - - } - -// @Test(expected=NoSuchElementException.class) -// public void noSuchElementException() { -// Map results = BASIC_RESULTS.transform( -// groupBy(postId, postName, set(commentId), list(commentText))); -// -// Group group = results.get(1); -// group.getSet(qComment); -// } - - @Test(expected = ClassCastException.class) - public void classCastException() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + Group group = results.get(null); + assertNull(group.getOne(post.id)); + assertEquals("null post", group.getOne(post.name)); + assertEquals(toSet(7, 8), group.getSet(comment.id)); + assertEquals(Arrays.asList("comment 7", "comment 8"), group.getList(comment.text)); + } + + // @Test(expected=NoSuchElementException.class) + // public void noSuchElementException() { + // Map results = BASIC_RESULTS.transform( + // groupBy(postId, postName, set(commentId), list(commentText))); + // + // Group group = results.get(1); + // group.getSet(qComment); + // } + + @Test(expected = ClassCastException.class) + public void classCastException() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, set(comment.id), list(comment.text))); - Group group = results.get(1); - group.getList(comment.id); - } + Group group = results.get(1); + group.getList(comment.id); + } - @Test - @Ignore - public void map_() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + @Test + @Ignore + public void map_() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, map(comment.id, comment.text))); - Group group = results.get(1); - Map comments = group.getMap(comment.id, comment.text); - assertEquals(1, comments.size()); -// assertEquals("comment 2", comments.get(2)); - } - - @Test - public void array_access() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + Group group = results.get(1); + Map comments = group.getMap(comment.id, comment.text); + assertEquals(1, comments.size()); + // assertEquals("comment 2", comments.get(2)); + } + + @Test + public void array_access() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(post.name, set(comment.id), list(comment.text))); - Group group = results.get(1); - Object[] array = group.toArray(); - assertEquals(toInt(1), array[0]); - assertEquals("Post 1", array[1]); - assertEquals(toSet(1), array[2]); - assertEquals(Collections.singletonList("Comment 1"), array[3]); - } - - @Test - public void transform_results() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + Group group = results.get(1); + Object[] array = group.toArray(); + assertEquals(toInt(1), array[0]); + assertEquals("Post 1", array[1]); + assertEquals(toSet(1), array[2]); + assertEquals(Collections.singletonList("Comment 1"), array[3]); + } + + @Test + public void transform_results() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) .transform(groupBy(post.id).as(QPost.create(post.id, post.name, set(qComment)))); - Post post = results.get(1); - assertNotNull(post); - assertEquals(1, post.getId()); - assertEquals("Post 1", post.getName()); - assertEquals(1, post.getComments().size()); - } - - @Test - public void transform_as_bean() { - Map results = CollQueryFactory.from(post, posts).from(comment, comments) + Post post = results.get(1); + assertNotNull(post); + assertEquals(1, post.getId()); + assertEquals("Post 1", post.getName()); + assertEquals(1, post.getComments().size()); + } + + @Test + public void transform_as_bean() { + Map results = + CollQueryFactory.from(post, posts) + .from(comment, comments) .where(comment.post.id.eq(post.id)) - .transform(groupBy(post.id).as(Projections.bean(Post.class, post.id, post.name, set(qComment).as("comments")))); - - Post post = results.get(1); - assertNotNull(post); - assertEquals(1, post.getId()); - assertEquals("Post 1", post.getName()); - assertEquals(1, post.getComments().size()); - } - - - @Test - public void oneToOneToMany_projection() { - Map results = CollQueryFactory.from(user, users).from(post, posts).from(comment, comments) + .transform( + groupBy(post.id) + .as( + Projections.bean( + Post.class, post.id, post.name, set(qComment).as("comments")))); + + Post post = results.get(1); + assertNotNull(post); + assertEquals(1, post.getId()); + assertEquals("Post 1", post.getName()); + assertEquals(1, post.getComments().size()); + } + + @Test + public void oneToOneToMany_projection() { + Map results = + CollQueryFactory.from(user, users) + .from(post, posts) + .from(comment, comments) .where(user.name.eq(post.user.name), post.id.eq(comment.post.id)) - .transform(groupBy(user.name).as(Projections.constructor(User.class, user.name, - QPost.create(post.id, post.name, set(qComment))))); - - assertEquals(2, results.size()); - - User user = results.get("Jane"); - Post post = user.getLatestPost(); - assertEquals(3, post.getId()); - assertEquals("Post 3", post.getName()); - assertEquals(3, post.getComments().size()); - } - - - @Test - public void oneToOneToMany_projection_as_bean() { - Map results = CollQueryFactory.from(user, users).from(post, posts).from(comment, comments) + .transform( + groupBy(user.name) + .as( + Projections.constructor( + User.class, + user.name, + QPost.create(post.id, post.name, set(qComment))))); + + assertEquals(2, results.size()); + + User user = results.get("Jane"); + Post post = user.getLatestPost(); + assertEquals(3, post.getId()); + assertEquals("Post 3", post.getName()); + assertEquals(3, post.getComments().size()); + } + + @Test + public void oneToOneToMany_projection_as_bean() { + Map results = + CollQueryFactory.from(user, users) + .from(post, posts) + .from(comment, comments) .where(user.name.eq(post.user.name), post.id.eq(comment.post.id)) - .transform(groupBy(user.name).as(Projections.bean(User.class, user.name, - Projections.bean(Post.class, post.id, post.name, set(qComment).as("comments")).as("latestPost")))); - - assertEquals(2, results.size()); - - User user = results.get("Jane"); - Post post = user.getLatestPost(); - assertEquals(3, post.getId()); - assertEquals("Post 3", post.getName()); - assertEquals(3, post.getComments().size()); - } - - @Test - public void oneToOneToMany_projection_as_bean_and_constructor() { - Map results = CollQueryFactory.from(user, users).from(post, posts).from(comment, comments) + .transform( + groupBy(user.name) + .as( + Projections.bean( + User.class, + user.name, + Projections.bean( + Post.class, post.id, post.name, set(qComment).as("comments")) + .as("latestPost")))); + + assertEquals(2, results.size()); + + User user = results.get("Jane"); + Post post = user.getLatestPost(); + assertEquals(3, post.getId()); + assertEquals("Post 3", post.getName()); + assertEquals(3, post.getComments().size()); + } + + @Test + public void oneToOneToMany_projection_as_bean_and_constructor() { + Map results = + CollQueryFactory.from(user, users) + .from(post, posts) + .from(comment, comments) .where(user.name.eq(post.user.name), post.id.eq(comment.post.id)) - .transform(groupBy(user.name).as(Projections.bean(User.class, user.name, - QPost.create(post.id, post.name, set(qComment)).as("latestPost")))); - - assertEquals(2, results.size()); - - User user = results.get("Jane"); - Post post = user.getLatestPost(); - assertEquals(3, post.getId()); - assertEquals("Post 3", post.getName()); - assertEquals(3, post.getComments().size()); - } - - private Integer toInt(int i) { - return i; - } - - private Set toSet(T... s) { - return new HashSet(Arrays.asList(s)); - } - - + .transform( + groupBy(user.name) + .as( + Projections.bean( + User.class, + user.name, + QPost.create(post.id, post.name, set(qComment)).as("latestPost")))); + + assertEquals(2, results.size()); + + User user = results.get("Jane"); + Post post = user.getLatestPost(); + assertEquals(3, post.getId()); + assertEquals("Post 3", post.getName()); + assertEquals(3, post.getComments().size()); + } + + private Integer toInt(int i) { + return i; + } + + private Set toSet(T... s) { + return new HashSet(Arrays.asList(s)); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/InnerClassTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/InnerClassTest.java index 940313f5fa..6d3928ba02 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/InnerClassTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/InnerClassTest.java @@ -19,27 +19,31 @@ import static org.junit.Assert.assertTrue; import java.util.Collections; - import org.junit.Test; public class InnerClassTest { - public static class Example { - - public String getId() { - return null; - } - } + public static class Example { - @Test - public void query() { - Example example = alias(Example.class); - assertFalse(CollQueryFactory. from($(example), Collections.singletonList(new Example())) - .where($(example.getId()).isNull()) - .fetch().isEmpty()); - assertTrue(CollQueryFactory. from($(example), Collections.singletonList(new Example())) - .where($(example.getId()).isNotNull()) - .fetch().isEmpty()); + public String getId() { + return null; } - + } + + @Test + public void query() { + Example example = alias(Example.class); + assertFalse( + CollQueryFactory.from( + $(example), Collections.singletonList(new Example())) + .where($(example.getId()).isNull()) + .fetch() + .isEmpty()); + assertTrue( + CollQueryFactory.from( + $(example), Collections.singletonList(new Example())) + .where($(example.getId()).isNotNull()) + .fetch() + .isEmpty()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/InnerJoinTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/InnerJoinTest.java index d47ff18cf0..9f8e4dfeff 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/InnerJoinTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/InnerJoinTest.java @@ -21,67 +21,66 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Before; import org.junit.Test; public class InnerJoinTest extends AbstractQueryTest { - private QCat cat, kitten; + private QCat cat, kitten; - private List cats; + private List cats; - @Before - public void setUp() { - super.setUp(); - cat = new QCat("c"); - kitten = new QCat("k"); - Cat bob = new Cat("Bob"); - Cat bob2 = new Cat("Bob"); - Cat kate = new Cat("Kate"); - Cat kate2 = new Cat("Kate"); - Cat franz = new Cat("Franz"); + @Before + public void setUp() { + super.setUp(); + cat = new QCat("c"); + kitten = new QCat("k"); + Cat bob = new Cat("Bob"); + Cat bob2 = new Cat("Bob"); + Cat kate = new Cat("Kate"); + Cat kate2 = new Cat("Kate"); + Cat franz = new Cat("Franz"); - bob.setKittens(Collections.singletonList(bob2)); - bob.setKittensByName(Collections.singletonMap(bob2.getName(), bob2)); - kate.setKittens(Collections.singletonList(kate2)); - kate.setKittensByName(Collections.singletonMap(kate2.getName(), kate)); - cats = Arrays.asList(bob, bob2, kate, kate2, franz); - } + bob.setKittens(Collections.singletonList(bob2)); + bob.setKittensByName(Collections.singletonMap(bob2.getName(), bob2)); + kate.setKittens(Collections.singletonList(kate2)); + kate.setKittensByName(Collections.singletonMap(kate2.getName(), kate)); + cats = Arrays.asList(bob, bob2, kate, kate2, franz); + } - @Test - public void list() { - List rv = CollQueryFactory.from(cat, cats) + @Test + public void list() { + List rv = + CollQueryFactory.from(cat, cats) .innerJoin(cat.kittens, kitten) .where(cat.name.eq(kitten.name)) .orderBy(cat.name.asc()) .fetch(); - assertEquals("Bob", rv.get(0).getName()); - assertEquals("Kate", rv.get(1).getName()); - - } - - @Test - public void alias_() { - Cat cc = alias(Cat.class, "cat1"); - Cat ck = alias(Cat.class, "cat2"); - List rv = CollQueryFactory.from($(cc), cats) - .innerJoin($(cc.getKittens()), $(ck)) - .where($(cc.getName()).eq($(ck.getName()))) - .fetch(); - assertFalse(rv.isEmpty()); - } + assertEquals("Bob", rv.get(0).getName()); + assertEquals("Kate", rv.get(1).getName()); + } + @Test + public void alias_() { + Cat cc = alias(Cat.class, "cat1"); + Cat ck = alias(Cat.class, "cat2"); + List rv = + CollQueryFactory.from($(cc), cats) + .innerJoin($(cc.getKittens()), $(ck)) + .where($(cc.getName()).eq($(ck.getName()))) + .fetch(); + assertFalse(rv.isEmpty()); + } - @Test - public void map() { - List rv = CollQueryFactory.from(cat, cats) + @Test + public void map() { + List rv = + CollQueryFactory.from(cat, cats) .innerJoin(cat.kittensByName, kitten) .where(cat.name.eq(kitten.name)) .orderBy(cat.name.asc()) .fetch(); - assertEquals("Bob", rv.get(0).getName()); - assertEquals("Kate", rv.get(1).getName()); - } - + assertEquals("Bob", rv.get(0).getName()); + assertEquals("Kate", rv.get(1).getName()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/IterationTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/IterationTest.java index a4f924eaa9..7ee6d4e6c4 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/IterationTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/IterationTest.java @@ -19,44 +19,50 @@ import java.util.Arrays; import java.util.List; - import org.junit.Test; public class IterationTest { - public static class Data { - - private String data = "data"; + public static class Data { - public String getData() { - return data; - } + private String data = "data"; + public String getData() { + return data; } + } - private List allData = Arrays.asList(new Data(), new Data()); + private List allData = Arrays.asList(new Data(), new Data()); - private Data lt = alias(Data.class,"Data"); + private Data lt = alias(Data.class, "Data"); - private List expected = Arrays.asList("data","data"); + private List expected = Arrays.asList("data", "data"); - @Test - public void test() { - assertEquals(expected, CollQueryFactory.from($(lt), allData).select($(lt.getData())).fetch()); - } + @Test + public void test() { + assertEquals(expected, CollQueryFactory.from($(lt), allData).select($(lt.getData())).fetch()); + } - @Test - public void test2() { - assertEquals(expected, CollQueryFactory. from($(lt), Arrays. asList(allData.toArray(new Data[0]))).select($(lt.getData())).fetch()); - } + @Test + public void test2() { + assertEquals( + expected, + CollQueryFactory.from($(lt), Arrays.asList(allData.toArray(new Data[0]))) + .select($(lt.getData())) + .fetch()); + } - @Test - public void test3() { - assertEquals(expected, CollQueryFactory.from(lt, allData).select($(lt.getData())).fetch()); - } + @Test + public void test3() { + assertEquals(expected, CollQueryFactory.from(lt, allData).select($(lt.getData())).fetch()); + } - @Test - public void test4() { - assertEquals(expected, CollQueryFactory. from(lt, Arrays. asList(allData.toArray(new Data[0]))).select($(lt.getData())).fetch()); - } + @Test + public void test4() { + assertEquals( + expected, + CollQueryFactory.from(lt, Arrays.asList(allData.toArray(new Data[0]))) + .select($(lt.getData())) + .fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/JacocoTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/JacocoTest.java index 00651842c3..d152c895d2 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/JacocoTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/JacocoTest.java @@ -3,68 +3,65 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import com.querydsl.core.alias.Alias; +import com.querydsl.core.types.dsl.EntityPathBase; import java.util.ArrayList; import java.util.List; - import org.junit.Test; -import com.querydsl.core.alias.Alias; -import com.querydsl.core.types.dsl.EntityPathBase; - public class JacocoTest { - public static class CloneableVO { } + public static class CloneableVO {} - public static class CloneableKlasse implements Cloneable { - private CloneableVO value; - private Integer otherValue; + public static class CloneableKlasse implements Cloneable { + private CloneableVO value; + private Integer otherValue; - public CloneableVO getValue() { - return value; - } - - public void setValue(CloneableVO value) { - this.value = value; - } + public CloneableVO getValue() { + return value; + } - public Integer getOtherValue() { - return otherValue; - } + public void setValue(CloneableVO value) { + this.value = value; + } - public void setOtherValue(Integer otherValue) { - this.otherValue = otherValue; - } + public Integer getOtherValue() { + return otherValue; + } - @Override - public Object clone() { - try { - return super.clone(); - } catch (final CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } + public void setOtherValue(Integer otherValue) { + this.otherValue = otherValue; } - @Test - public void withSimpleClass() { - List vos = new ArrayList(); - for (int i = 0; i < 5; i++) { - CloneableKlasse vo = new CloneableKlasse(); - vo.setOtherValue(i); - vos.add(vo); - } - CloneableKlasse vo = Alias.alias(CloneableKlasse.class, "vo"); - assertNotNull(vo); - CollQuery query = new CollQuery(); - final EntityPathBase fromVo = Alias.$(vo); - assertNotNull(fromVo); - query.from(fromVo, vos); - query.where(Alias.$(vo.getOtherValue()).eq(1)); - List result = query.select(Alias.$(vo)).fetch(); + @Override + public Object clone() { + try { + return super.clone(); + } catch (final CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + } - assertNotNull(result); - assertEquals(1, result.size()); - assertEquals(Integer.valueOf(1), result.get(0).getOtherValue()); + @Test + public void withSimpleClass() { + List vos = new ArrayList(); + for (int i = 0; i < 5; i++) { + CloneableKlasse vo = new CloneableKlasse(); + vo.setOtherValue(i); + vos.add(vo); } + CloneableKlasse vo = Alias.alias(CloneableKlasse.class, "vo"); + assertNotNull(vo); + CollQuery query = new CollQuery(); + final EntityPathBase fromVo = Alias.$(vo); + assertNotNull(fromVo); + query.from(fromVo, vos); + query.where(Alias.$(vo.getOtherValue()).eq(1)); + List result = query.select(Alias.$(vo)).fetch(); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(Integer.valueOf(1), result.get(0).getOtherValue()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/JodaTimeTemplatesTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/JodaTimeTemplatesTest.java index ccfe4859bc..acfbebe7b5 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/JodaTimeTemplatesTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/JodaTimeTemplatesTest.java @@ -1,46 +1,61 @@ package com.querydsl.collections; +import com.querydsl.core.types.dsl.DatePath; +import com.querydsl.core.types.dsl.DateTimePath; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.TimePath; import java.util.Arrays; - import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.junit.Test; -import com.querydsl.core.types.dsl.DatePath; -import com.querydsl.core.types.dsl.DateTimePath; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.TimePath; - public class JodaTimeTemplatesTest { - private CollQuery query = new CollQuery(JodaTimeTemplates.DEFAULT); - - @Test - public void dateTime() { - DateTimePath entity = Expressions.dateTimePath(DateTime.class, "entity"); - query.from(entity, Arrays.asList(new DateTime(), new DateTime(0L))) - .select(entity.year(), entity.yearMonth(), entity.month(), entity.week(), - entity.dayOfMonth(), entity.dayOfWeek(), entity.dayOfYear(), - entity.hour(), entity.minute(), entity.second(), entity.milliSecond()) - .fetch(); - } - - @Test - public void localDate() { - DatePath entity = Expressions.datePath(LocalDate.class, "entity"); - query.from(entity, Arrays.asList(new LocalDate(), new LocalDate(0L))) - .select(entity.year(), entity.yearMonth(), entity.month(), entity.week(), - entity.dayOfMonth(), entity.dayOfWeek(), entity.dayOfYear()) - .fetch(); - } - - @Test - public void localTime() { - TimePath entity = Expressions.timePath(LocalTime.class, "entity"); - query.from(entity, Arrays.asList(new LocalTime(), new LocalTime(0L))) - .select(entity.hour(), entity.minute(), entity.second(), entity.milliSecond()) - .fetch(); - } - + private CollQuery query = new CollQuery(JodaTimeTemplates.DEFAULT); + + @Test + public void dateTime() { + DateTimePath entity = Expressions.dateTimePath(DateTime.class, "entity"); + query + .from(entity, Arrays.asList(new DateTime(), new DateTime(0L))) + .select( + entity.year(), + entity.yearMonth(), + entity.month(), + entity.week(), + entity.dayOfMonth(), + entity.dayOfWeek(), + entity.dayOfYear(), + entity.hour(), + entity.minute(), + entity.second(), + entity.milliSecond()) + .fetch(); + } + + @Test + public void localDate() { + DatePath entity = Expressions.datePath(LocalDate.class, "entity"); + query + .from(entity, Arrays.asList(new LocalDate(), new LocalDate(0L))) + .select( + entity.year(), + entity.yearMonth(), + entity.month(), + entity.week(), + entity.dayOfMonth(), + entity.dayOfWeek(), + entity.dayOfYear()) + .fetch(); + } + + @Test + public void localTime() { + TimePath entity = Expressions.timePath(LocalTime.class, "entity"); + query + .from(entity, Arrays.asList(new LocalTime(), new LocalTime(0L))) + .select(entity.hour(), entity.minute(), entity.second(), entity.milliSecond()) + .fetch(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/LeftJoinTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/LeftJoinTest.java index 5d2b7ecde9..4938203aa3 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/LeftJoinTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/LeftJoinTest.java @@ -21,67 +21,67 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Before; import org.junit.Test; public class LeftJoinTest extends AbstractQueryTest { - private QCat cat, kitten; + private QCat cat, kitten; - private List cats; + private List cats; - @Before - public void setUp() { - super.setUp(); - cat = new QCat("c"); - kitten = new QCat("k"); - Cat bob = new Cat("Bob"); - Cat bob2 = new Cat("Bob"); - Cat kate = new Cat("Kate"); - Cat kate2 = new Cat("Kate"); - Cat franz = new Cat("Franz"); + @Before + public void setUp() { + super.setUp(); + cat = new QCat("c"); + kitten = new QCat("k"); + Cat bob = new Cat("Bob"); + Cat bob2 = new Cat("Bob"); + Cat kate = new Cat("Kate"); + Cat kate2 = new Cat("Kate"); + Cat franz = new Cat("Franz"); - bob.setKittens(Collections.singletonList(bob2)); - bob.setKittensByName(Collections.singletonMap(bob2.getName(), bob2)); - kate.setKittens(Collections.emptyList()); - kate.setKittensByName(Collections.singletonMap(kate2.getName(), kate)); - cats = Arrays.asList(bob, bob2, kate, kate2, franz); - } + bob.setKittens(Collections.singletonList(bob2)); + bob.setKittensByName(Collections.singletonMap(bob2.getName(), bob2)); + kate.setKittens(Collections.emptyList()); + kate.setKittensByName(Collections.singletonMap(kate2.getName(), kate)); + cats = Arrays.asList(bob, bob2, kate, kate2, franz); + } - @Test - public void list() { - List rv = CollQueryFactory.from(cat, cats) + @Test + public void list() { + List rv = + CollQueryFactory.from(cat, cats) .leftJoin(cat.kittens, kitten) .where(kitten.isNotNull(), cat.name.eq(kitten.name)) .orderBy(cat.name.asc()) .fetch(); - assertEquals(1, rv.size()); - assertEquals("Bob", rv.get(0).getName()); - } - - @Test - public void alias_() { - Cat cc = alias(Cat.class, "cat1"); - Cat ck = alias(Cat.class, "cat2"); - List rv = CollQueryFactory.from($(cc), cats) - .leftJoin($(cc.getKittens()), $(ck)) - .where($(ck).isNotNull(), $(cc.getName()).eq($(ck.getName()))) - .fetch(); - assertFalse(rv.isEmpty()); - } + assertEquals(1, rv.size()); + assertEquals("Bob", rv.get(0).getName()); + } + @Test + public void alias_() { + Cat cc = alias(Cat.class, "cat1"); + Cat ck = alias(Cat.class, "cat2"); + List rv = + CollQueryFactory.from($(cc), cats) + .leftJoin($(cc.getKittens()), $(ck)) + .where($(ck).isNotNull(), $(cc.getName()).eq($(ck.getName()))) + .fetch(); + assertFalse(rv.isEmpty()); + } - @Test - public void map() { - List rv = CollQueryFactory.from(cat, cats) + @Test + public void map() { + List rv = + CollQueryFactory.from(cat, cats) .leftJoin(cat.kittensByName, kitten) .where(cat.name.eq(kitten.name)) .orderBy(cat.name.asc()) .fetch(); - assertEquals("Bob", rv.get(0).getName()); - assertEquals("Kate", rv.get(1).getName()); - } - + assertEquals("Bob", rv.get(0).getName()); + assertEquals("Kate", rv.get(1).getName()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/LoadTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/LoadTest.java index 5e0f63729d..9291c9ab64 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/LoadTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/LoadTest.java @@ -15,87 +15,86 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.core.DefaultQueryMetadata; +import com.querydsl.core.QueryMetadata; +import com.querydsl.core.testutil.Performance; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.junit.Test; import org.junit.experimental.categories.Category; -import com.querydsl.core.DefaultQueryMetadata; -import com.querydsl.core.QueryMetadata; -import com.querydsl.core.testutil.Performance; - @Category(Performance.class) public class LoadTest { - private QCat cat = QCat.cat; + private QCat cat = QCat.cat; - private DefaultEvaluatorFactory evaluatorFactory = new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); + private DefaultEvaluatorFactory evaluatorFactory = + new DefaultEvaluatorFactory(CollQueryTemplates.DEFAULT); - private QueryMetadata metadata = new DefaultQueryMetadata(); + private QueryMetadata metadata = new DefaultQueryMetadata(); - @Test - public void creation() { - System.out.println("Evaluator creation #1"); - for (int i = 0; i < 5; i++) { - long s = System.currentTimeMillis(); - evaluatorFactory.create(metadata, Collections.singletonList(cat), cat.name.startsWith("Bob")); - long e = System.currentTimeMillis(); - System.out.println(" " + (e - s) + "ms"); - } - System.out.println(); + @Test + public void creation() { + System.out.println("Evaluator creation #1"); + for (int i = 0; i < 5; i++) { + long s = System.currentTimeMillis(); + evaluatorFactory.create(metadata, Collections.singletonList(cat), cat.name.startsWith("Bob")); + long e = System.currentTimeMillis(); + System.out.println(" " + (e - s) + "ms"); + } + System.out.println(); - System.out.println("Evaluator creation #2"); - for (int i = 0; i < 5; i++) { - long s = System.currentTimeMillis(); - evaluatorFactory.create(metadata, Collections.singletonList(cat), cat.name.startsWith("Bob" + i)); - long e = System.currentTimeMillis(); - System.out.println(" " + (e - s) + "ms"); - } - System.out.println(); + System.out.println("Evaluator creation #2"); + for (int i = 0; i < 5; i++) { + long s = System.currentTimeMillis(); + evaluatorFactory.create( + metadata, Collections.singletonList(cat), cat.name.startsWith("Bob" + i)); + long e = System.currentTimeMillis(); + System.out.println(" " + (e - s) + "ms"); } + System.out.println(); + } - @Test - public void test() { - List data = new ArrayList(5000); - for (int i = 0; i < 1000; i++) { - data.addAll(Arrays.asList( - new Cat("Bob" + i), - new Cat("Ruth" + i), - new Cat("Felix" + i), - new Cat("Allen" + i), - new Cat("Mary" + i) - )); - } + @Test + public void test() { + List data = new ArrayList(5000); + for (int i = 0; i < 1000; i++) { + data.addAll( + Arrays.asList( + new Cat("Bob" + i), + new Cat("Ruth" + i), + new Cat("Felix" + i), + new Cat("Allen" + i), + new Cat("Mary" + i))); + } - // #1 - System.out.println("Querydsl iteration"); - for (int i = 0; i < 5; i++) { - long s1 = System.currentTimeMillis(); - List bobs1 = CollQueryFactory.from(cat, data).where(cat.name.startsWith("Bob")).fetch(); - assertEquals(1000, bobs1.size()); - long e1 = System.currentTimeMillis(); - System.out.println(" " + (e1 - s1) + "ms"); - } - System.out.println(); + // #1 + System.out.println("Querydsl iteration"); + for (int i = 0; i < 5; i++) { + long s1 = System.currentTimeMillis(); + List bobs1 = CollQueryFactory.from(cat, data).where(cat.name.startsWith("Bob")).fetch(); + assertEquals(1000, bobs1.size()); + long e1 = System.currentTimeMillis(); + System.out.println(" " + (e1 - s1) + "ms"); + } + System.out.println(); - // #2 - System.out.println("Normal iteration"); - for (int i = 0; i < 5; i++) { - long s2 = System.currentTimeMillis(); - List bobs2 = new ArrayList(); - for (Cat c : data) { - if (c.getName().startsWith("Bob")) { - bobs2.add(c); - } - } - assertEquals(1000, bobs2.size()); - long e2 = System.currentTimeMillis(); - System.out.println(" " + (e2 - s2) + "ms"); + // #2 + System.out.println("Normal iteration"); + for (int i = 0; i < 5; i++) { + long s2 = System.currentTimeMillis(); + List bobs2 = new ArrayList(); + for (Cat c : data) { + if (c.getName().startsWith("Bob")) { + bobs2.add(c); } - System.out.println(); + } + assertEquals(1000, bobs2.size()); + long e2 = System.currentTimeMillis(); + System.out.println(" " + (e2 - s2) + "ms"); } - + System.out.println(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/MappingProjectionTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/MappingProjectionTest.java index f160ac3303..3d74dc0287 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/MappingProjectionTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/MappingProjectionTest.java @@ -2,47 +2,43 @@ import static org.junit.Assert.assertEquals; -import java.util.List; - -import org.junit.Test; - import com.querydsl.core.Tuple; import com.querydsl.core.types.MappingProjection; +import java.util.List; +import org.junit.Test; @SuppressWarnings("serial") public class MappingProjectionTest extends AbstractQueryTest { - public class ResultPart { - - } - - public class ResultObject { + public class ResultPart {} - } + public class ResultObject {} - @Test - public void test() { - final MappingProjection key = new MappingProjection(ResultPart.class, - cat.name) { - - @Override - protected ResultPart map(Tuple row) { - return new ResultPart(); - } + @Test + public void test() { + final MappingProjection key = + new MappingProjection(ResultPart.class, cat.name) { + @Override + protected ResultPart map(Tuple row) { + return new ResultPart(); + } }; - List list = query().from(cat, cats).select( - new MappingProjection(ResultObject.class, key) { + List list = + query() + .from(cat, cats) + .select( + new MappingProjection(ResultObject.class, key) { - @Override - protected ResultObject map(Tuple row) { + @Override + protected ResultObject map(Tuple row) { ResultPart consolidationKey = row.get(key); return new ResultObject(); - } - }).fetch(); - - assertEquals(cats.size(), list.size()); - } + } + }) + .fetch(); + assertEquals(cats.size(), list.size()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/MathTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/MathTest.java index c8eeabb825..f172de4385 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/MathTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/MathTest.java @@ -2,68 +2,65 @@ import static org.junit.Assert.assertEquals; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.MathExpressions; import com.querydsl.core.types.dsl.NumberPath; +import java.util.Collections; +import org.junit.Test; public class MathTest { - private NumberPath num = Expressions.numberPath(Double.class, "num"); - - @Test - public void math() { - Expression expr = num; - - assertEquals(Math.acos(0.5), unique(MathExpressions.acos(expr)), 0.001); - assertEquals(Math.asin(0.5), unique(MathExpressions.asin(expr)), 0.001); - assertEquals(Math.atan(0.5), unique(MathExpressions.atan(expr)), 0.001); - assertEquals(Math.cos(0.5), unique(MathExpressions.cos(expr)), 0.001); - assertEquals(Math.cosh(0.5), unique(MathExpressions.cosh(expr)), 0.001); - assertEquals(cot(0.5), unique(MathExpressions.cot(expr)), 0.001); - assertEquals(coth(0.5), unique(MathExpressions.coth(expr)), 0.001); - assertEquals(degrees(0.5), unique(MathExpressions.degrees(expr)), 0.001); - assertEquals(Math.exp(0.5), unique(MathExpressions.exp(expr)), 0.001); - assertEquals(Math.log(0.5), unique(MathExpressions.ln(expr)), 0.001); - assertEquals(log(0.5, 10), unique(MathExpressions.log(expr, 10)), 0.001); - assertEquals(0.25, unique(MathExpressions.power(expr, 2)), 0.001); - assertEquals(radians(0.5), unique(MathExpressions.radians(expr)), 0.001); - assertEquals(Integer.valueOf(1), - unique(MathExpressions.sign(expr))); - assertEquals(Math.sin(0.5), unique(MathExpressions.sin(expr)), 0.001); - assertEquals(Math.sinh(0.5), unique(MathExpressions.sinh(expr)), 0.001); - assertEquals(Math.tan(0.5), unique(MathExpressions.tan(expr)), 0.001); - assertEquals(Math.tanh(0.5), unique(MathExpressions.tanh(expr)), 0.001); - - } - - private double cot(double x) { - return Math.cos(x) / Math.sin(x); - } - - private double coth(double x) { - return Math.cosh(x) / Math.sinh(x); - } - - private double degrees(double x) { - return x * 180.0 / Math.PI; - } - - private double radians(double x) { - return x * Math.PI / 180.0; - } - - private double log(double x, int y) { - return Math.log(x) / Math.log(y); - } - - private T unique(Expression expr) { - //return query().fetchOne(expr); - return CollQueryFactory. from(num, Collections.singletonList(0.5)).select(expr).fetchOne(); - } - + private NumberPath num = Expressions.numberPath(Double.class, "num"); + + @Test + public void math() { + Expression expr = num; + + assertEquals(Math.acos(0.5), unique(MathExpressions.acos(expr)), 0.001); + assertEquals(Math.asin(0.5), unique(MathExpressions.asin(expr)), 0.001); + assertEquals(Math.atan(0.5), unique(MathExpressions.atan(expr)), 0.001); + assertEquals(Math.cos(0.5), unique(MathExpressions.cos(expr)), 0.001); + assertEquals(Math.cosh(0.5), unique(MathExpressions.cosh(expr)), 0.001); + assertEquals(cot(0.5), unique(MathExpressions.cot(expr)), 0.001); + assertEquals(coth(0.5), unique(MathExpressions.coth(expr)), 0.001); + assertEquals(degrees(0.5), unique(MathExpressions.degrees(expr)), 0.001); + assertEquals(Math.exp(0.5), unique(MathExpressions.exp(expr)), 0.001); + assertEquals(Math.log(0.5), unique(MathExpressions.ln(expr)), 0.001); + assertEquals(log(0.5, 10), unique(MathExpressions.log(expr, 10)), 0.001); + assertEquals(0.25, unique(MathExpressions.power(expr, 2)), 0.001); + assertEquals(radians(0.5), unique(MathExpressions.radians(expr)), 0.001); + assertEquals(Integer.valueOf(1), unique(MathExpressions.sign(expr))); + assertEquals(Math.sin(0.5), unique(MathExpressions.sin(expr)), 0.001); + assertEquals(Math.sinh(0.5), unique(MathExpressions.sinh(expr)), 0.001); + assertEquals(Math.tan(0.5), unique(MathExpressions.tan(expr)), 0.001); + assertEquals(Math.tanh(0.5), unique(MathExpressions.tanh(expr)), 0.001); + } + + private double cot(double x) { + return Math.cos(x) / Math.sin(x); + } + + private double coth(double x) { + return Math.cosh(x) / Math.sinh(x); + } + + private double degrees(double x) { + return x * 180.0 / Math.PI; + } + + private double radians(double x) { + return x * Math.PI / 180.0; + } + + private double log(double x, int y) { + return Math.log(x) / Math.log(y); + } + + private T unique(Expression expr) { + // return query().fetchOne(expr); + return CollQueryFactory.from(num, Collections.singletonList(0.5)) + .select(expr) + .fetchOne(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/MockTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/MockTest.java index 64fe6a8d0e..e6bce1f739 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/MockTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/MockTest.java @@ -2,23 +2,20 @@ import static org.junit.Assert.assertTrue; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.SimplePath; import java.util.Arrays; import java.util.List; - import org.easymock.EasyMock; import org.junit.Test; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.SimplePath; - public class MockTest { - @Test - public void test() { - List tests = Arrays.asList(new MockTest(), new MockTest(), new MockTest()); - SimplePath path = Expressions.path(MockTest.class, "obj"); - MockTest mock = EasyMock.createMock(MockTest.class); - assertTrue(CollQueryFactory.from(path, tests).where(path.eq(mock)).fetch().isEmpty()); - } - + @Test + public void test() { + List tests = Arrays.asList(new MockTest(), new MockTest(), new MockTest()); + SimplePath path = Expressions.path(MockTest.class, "obj"); + MockTest mock = EasyMock.createMock(MockTest.class); + assertTrue(CollQueryFactory.from(path, tests).where(path.eq(mock)).fetch().isEmpty()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/MultiComparatorTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/MultiComparatorTest.java index 0714878981..2d5df05d49 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/MultiComparatorTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/MultiComparatorTest.java @@ -15,30 +15,31 @@ import static org.junit.Assert.assertTrue; -import org.junit.Test; - import com.querydsl.codegen.utils.Evaluator; +import org.junit.Test; public class MultiComparatorTest { - private final Evaluator evaluator = new Evaluator() { + private final Evaluator evaluator = + new Evaluator() { @Override public Object[] evaluate(Object... args) { - return args; + return args; } + @Override public Class getType() { - return Object[].class; + return Object[].class; } - }; - - @Test - public void test() { - MultiComparator comparator = new MultiComparator(evaluator, new boolean[]{true, true}, - new boolean[]{true, true}); - assertTrue(comparator.compare(new Object[]{"a", "b"}, new Object[]{"a","c"}) < 0); - assertTrue(comparator.compare(new Object[]{"b", "a"}, new Object[]{"a","b"}) > 0); - assertTrue(comparator.compare(new Object[]{"b", "b"}, new Object[]{"b","b"}) == 0); - } + }; + @Test + public void test() { + MultiComparator comparator = + new MultiComparator( + evaluator, new boolean[] {true, true}, new boolean[] {true, true}); + assertTrue(comparator.compare(new Object[] {"a", "b"}, new Object[] {"a", "c"}) < 0); + assertTrue(comparator.compare(new Object[] {"b", "a"}, new Object[] {"a", "b"}) > 0); + assertTrue(comparator.compare(new Object[] {"b", "b"}, new Object[] {"b", "b"}) == 0); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/NullSafetyTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/NullSafetyTest.java index aaaf30dd7c..68b3210d63 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/NullSafetyTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/NullSafetyTest.java @@ -3,30 +3,31 @@ import static org.junit.Assert.assertEquals; import java.util.Arrays; - import org.junit.Test; public class NullSafetyTest extends AbstractQueryTest { - @Test - public void filters() { - QCat cat = QCat.cat; - CollQuery query = CollQueryFactory. from(cat, Arrays. asList(new Cat(), new Cat("Bob"))); - assertEquals(1L, query.where(cat.name.eq("Bob")).fetchCount()); - } - - @Test - public void joins() { - Cat kitten1 = new Cat(); - Cat kitten2 = new Cat("Bob"); - Cat cat1 = new Cat(); - cat1.setKittens(Arrays.asList(kitten1, kitten2)); - Cat cat2 = new Cat(); - - QCat cat = QCat.cat; - QCat kitten = new QCat("kitten"); - CollQuery query = CollQueryFactory. from(cat, Arrays. asList(cat1, cat2)).innerJoin(cat.kittens, kitten); - assertEquals(1, query.where(kitten.name.eq("Bob")).fetchCount()); - } - + @Test + public void filters() { + QCat cat = QCat.cat; + CollQuery query = + CollQueryFactory.from(cat, Arrays.asList(new Cat(), new Cat("Bob"))); + assertEquals(1L, query.where(cat.name.eq("Bob")).fetchCount()); + } + + @Test + public void joins() { + Cat kitten1 = new Cat(); + Cat kitten2 = new Cat("Bob"); + Cat cat1 = new Cat(); + cat1.setKittens(Arrays.asList(kitten1, kitten2)); + Cat cat2 = new Cat(); + + QCat cat = QCat.cat; + QCat kitten = new QCat("kitten"); + CollQuery query = + CollQueryFactory.from(cat, Arrays.asList(cat1, cat2)) + .innerJoin(cat.kittens, kitten); + assertEquals(1, query.where(kitten.name.eq("Bob")).fetchCount()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/NumberTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/NumberTest.java index 1c701f79a4..4eb5136160 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/NumberTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/NumberTest.java @@ -2,21 +2,21 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.NumberPath; import java.math.BigDecimal; import java.util.Arrays; - import org.junit.Test; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.NumberPath; - public class NumberTest { - @Test - public void sum() throws Exception { - NumberPath num = Expressions.numberPath(BigDecimal.class, "num"); - CollQuery query = CollQueryFactory. from(num, Arrays. asList(new BigDecimal("1.6"), new BigDecimal("1.3"))); + @Test + public void sum() throws Exception { + NumberPath num = Expressions.numberPath(BigDecimal.class, "num"); + CollQuery query = + CollQueryFactory.from( + num, Arrays.asList(new BigDecimal("1.6"), new BigDecimal("1.3"))); - assertEquals(new BigDecimal("2.9"), query. select(num.sum()).fetchOne()); - } + assertEquals(new BigDecimal("2.9"), query.select(num.sum()).fetchOne()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/OrderTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/OrderTest.java index f515888e11..ccc3d05f10 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/OrderTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/OrderTest.java @@ -17,68 +17,86 @@ import java.util.Arrays; import java.util.List; - import org.junit.Test; public class OrderTest extends AbstractQueryTest { - @Test - public void test() { - query().from(cat, cats).orderBy(cat.name.asc()).select(cat.name).fetch(); - assertArrayEquals(new Object[] {"Alex", "Bob", "Francis", "Kitty"}, last.res.toArray()); + @Test + public void test() { + query().from(cat, cats).orderBy(cat.name.asc()).select(cat.name).fetch(); + assertArrayEquals(new Object[] {"Alex", "Bob", "Francis", "Kitty"}, last.res.toArray()); - query().from(cat, cats).orderBy(cat.name.desc()).select(cat.name).fetch(); - assertArrayEquals(new Object[] {"Kitty", "Francis", "Bob", "Alex"}, last.res.toArray()); + query().from(cat, cats).orderBy(cat.name.desc()).select(cat.name).fetch(); + assertArrayEquals(new Object[] {"Kitty", "Francis", "Bob", "Alex"}, last.res.toArray()); - query().from(cat, cats).orderBy(cat.name.substring(1).asc()).select(cat.name).fetch(); - assertArrayEquals(new Object[] {"Kitty", "Alex", "Bob", "Francis"}, last.res.toArray()); + query().from(cat, cats).orderBy(cat.name.substring(1).asc()).select(cat.name).fetch(); + assertArrayEquals(new Object[] {"Kitty", "Alex", "Bob", "Francis"}, last.res.toArray()); - query().from(cat, cats).from(otherCat, cats) - .orderBy(cat.name.asc(), otherCat.name.desc()) - .select(cat.name, otherCat.name).fetch(); + query() + .from(cat, cats) + .from(otherCat, cats) + .orderBy(cat.name.asc(), otherCat.name.desc()) + .select(cat.name, otherCat.name) + .fetch(); - // TODO : more tests - } + // TODO : more tests + } - @Test - public void test2() { - List orderedNames = Arrays.asList("Alex","Bob","Francis","Kitty"); - assertEquals(orderedNames, query().from(cat,cats).orderBy(cat.name.asc()).select(cat.name).fetch()); - assertEquals(orderedNames, query().from(cat,cats).orderBy(cat.name.asc()).distinct().select(cat.name).fetch()); - } + @Test + public void test2() { + List orderedNames = Arrays.asList("Alex", "Bob", "Francis", "Kitty"); + assertEquals( + orderedNames, query().from(cat, cats).orderBy(cat.name.asc()).select(cat.name).fetch()); + assertEquals( + orderedNames, + query().from(cat, cats).orderBy(cat.name.asc()).distinct().select(cat.name).fetch()); + } - @Test - public void with_count() { - CollQuery q = new CollQuery(); - q.from(cat, cats); - long size = q.distinct().fetchCount(); - assertTrue(size > 0); - q.offset(0).limit(10); - q.orderBy(cat.name.asc()); - assertEquals(Arrays.asList("Alex","Bob","Francis","Kitty"), q.distinct().select(cat.name).fetch()); - } + @Test + public void with_count() { + CollQuery q = new CollQuery(); + q.from(cat, cats); + long size = q.distinct().fetchCount(); + assertTrue(size > 0); + q.offset(0).limit(10); + q.orderBy(cat.name.asc()); + assertEquals( + Arrays.asList("Alex", "Bob", "Francis", "Kitty"), q.distinct().select(cat.name).fetch()); + } - @Test - public void with_null() { - Cat unknown = new Cat(); - Cat bob = new Cat("Bob"); - Cat alex = new Cat("Alex"); - List cats = Arrays.asList(alex, unknown, bob); - assertEquals(Arrays.asList(unknown, alex, bob), - query().from(cat, cats).orderBy(cat.name.asc()).select(cat).fetch()); - assertEquals(Arrays.asList(unknown, bob, alex), - query().from(cat, cats).orderBy(cat.name.desc()).select(cat).fetch()); - } + @Test + public void with_null() { + Cat unknown = new Cat(); + Cat bob = new Cat("Bob"); + Cat alex = new Cat("Alex"); + List cats = Arrays.asList(alex, unknown, bob); + assertEquals( + Arrays.asList(unknown, alex, bob), + query().from(cat, cats).orderBy(cat.name.asc()).select(cat).fetch()); + assertEquals( + Arrays.asList(unknown, bob, alex), + query().from(cat, cats).orderBy(cat.name.desc()).select(cat).fetch()); + } - @Test - public void with_nulls_last() { - Cat unknown = new Cat(); - Cat bob = new Cat("Bob"); - Cat alex = new Cat("Alex"); - List cats = Arrays.asList(alex, unknown, bob); - assertEquals(Arrays.asList(bob, alex, unknown), - query().from(this.cat, cats).orderBy(this.cat.name.desc().nullsLast()).select(this.cat).fetch()); - assertEquals(Arrays.asList(alex, bob, unknown), - query().from(this.cat, cats).orderBy(this.cat.name.asc().nullsLast()).select(this.cat).fetch()); - } + @Test + public void with_nulls_last() { + Cat unknown = new Cat(); + Cat bob = new Cat("Bob"); + Cat alex = new Cat("Alex"); + List cats = Arrays.asList(alex, unknown, bob); + assertEquals( + Arrays.asList(bob, alex, unknown), + query() + .from(this.cat, cats) + .orderBy(this.cat.name.desc().nullsLast()) + .select(this.cat) + .fetch()); + assertEquals( + Arrays.asList(alex, bob, unknown), + query() + .from(this.cat, cats) + .orderBy(this.cat.name.asc().nullsLast()) + .select(this.cat) + .fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/PagingTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/PagingTest.java index aaa7754890..91cd402e42 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/PagingTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/PagingTest.java @@ -15,56 +15,54 @@ import static org.junit.Assert.assertEquals; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - import com.mysema.commons.lang.IteratorAdapter; import com.querydsl.core.QueryModifiers; import com.querydsl.core.QueryResults; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.NumberPath; +import java.util.Arrays; +import java.util.List; +import org.junit.Test; public class PagingTest extends AbstractQueryTest { - private List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); + private List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - private NumberPath var = Expressions.numberPath(Integer.class, "var"); + private NumberPath var = Expressions.numberPath(Integer.class, "var"); - @Test - public void test() { - assertResultSize(9, 9, QueryModifiers.EMPTY); - assertResultSize(9, 2, new QueryModifiers(2L, null)); - assertResultSize(9, 2, new QueryModifiers(2L, 0L)); - assertResultSize(9, 2, new QueryModifiers(2L, 3L)); - assertResultSize(9, 9, new QueryModifiers(20L, null)); - assertResultSize(9, 9, new QueryModifiers(20L, 0L)); - assertResultSize(9, 5, new QueryModifiers(20L, 4L)); - assertResultSize(9, 0, new QueryModifiers(10L, 9L)); - } + @Test + public void test() { + assertResultSize(9, 9, QueryModifiers.EMPTY); + assertResultSize(9, 2, new QueryModifiers(2L, null)); + assertResultSize(9, 2, new QueryModifiers(2L, 0L)); + assertResultSize(9, 2, new QueryModifiers(2L, 3L)); + assertResultSize(9, 9, new QueryModifiers(20L, null)); + assertResultSize(9, 9, new QueryModifiers(20L, 0L)); + assertResultSize(9, 5, new QueryModifiers(20L, 4L)); + assertResultSize(9, 0, new QueryModifiers(10L, 9L)); + } - private void assertResultSize(int total, int size, QueryModifiers modifiers) { - // via fetch - assertEquals(size, createQuery(modifiers).select(var).fetch().size()); + private void assertResultSize(int total, int size, QueryModifiers modifiers) { + // via fetch + assertEquals(size, createQuery(modifiers).select(var).fetch().size()); - // via results - QueryResults results = createQuery(modifiers).select(var).fetchResults(); - assertEquals(total, results.getTotal()); - assertEquals(size, results.getResults().size()); + // via results + QueryResults results = createQuery(modifiers).select(var).fetchResults(); + assertEquals(total, results.getTotal()); + assertEquals(size, results.getResults().size()); - // via fetchCount (ignore limit and offset) - assertEquals(total, createQuery(modifiers).fetchCount()); + // via fetchCount (ignore limit and offset) + assertEquals(total, createQuery(modifiers).fetchCount()); - // via iterator - assertEquals(size, IteratorAdapter.asList(createQuery(modifiers).select(var).iterate()).size()); - } + // via iterator + assertEquals(size, IteratorAdapter.asList(createQuery(modifiers).select(var).iterate()).size()); + } - private CollQuery createQuery(QueryModifiers modifiers) { - CollQuery query = new CollQuery().from(var, ints); - if (modifiers != null) { - query.restrict(modifiers); - } - return query; + private CollQuery createQuery(QueryModifiers modifiers) { + CollQuery query = new CollQuery().from(var, ints); + if (modifiers != null) { + query.restrict(modifiers); } + return query; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/PathComparatorTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/PathComparatorTest.java index c7f3f24202..9af9897cba 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/PathComparatorTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/PathComparatorTest.java @@ -4,57 +4,55 @@ import static org.junit.Assert.assertEquals; import java.util.Comparator; - import org.junit.Before; import org.junit.Test; public class PathComparatorTest { - private Comparator comparator; - - @Before - public void setUpComparator() { - comparator = pathComparator(QCar.car.horsePower); - } + private Comparator comparator; - @Test - public void equalReference() { - Car car = new Car(); - assertEquals(0, comparator.compare(car, car)); - } + @Before + public void setUpComparator() { + comparator = pathComparator(QCar.car.horsePower); + } - @Test - public void semanticallyEqual() { - Car car = new Car(); - car.setModel("car"); - car.setHorsePower(50); + @Test + public void equalReference() { + Car car = new Car(); + assertEquals(0, comparator.compare(car, car)); + } - Car similarCar = new Car(); - similarCar.setModel("car"); - similarCar.setHorsePower(50); + @Test + public void semanticallyEqual() { + Car car = new Car(); + car.setModel("car"); + car.setHorsePower(50); - assertEquals(0, comparator.compare(car, similarCar)); - } + Car similarCar = new Car(); + similarCar.setModel("car"); + similarCar.setHorsePower(50); - @Test - public void leftIsNull() { - assertEquals(-1, comparator.compare(null, new Car())); - } + assertEquals(0, comparator.compare(car, similarCar)); + } - @Test - public void rightIsNull() { - assertEquals(1, comparator.compare(new Car(), null)); - } + @Test + public void leftIsNull() { + assertEquals(-1, comparator.compare(null, new Car())); + } - @Test - public void compareOnValue() { - Car car = new Car(); - car.setHorsePower(50); + @Test + public void rightIsNull() { + assertEquals(1, comparator.compare(new Car(), null)); + } - Car betterCar = new Car(); - betterCar.setHorsePower(150); + @Test + public void compareOnValue() { + Car car = new Car(); + car.setHorsePower(50); - assertEquals(-1, comparator.compare(car, betterCar)); - } + Car betterCar = new Car(); + betterCar.setHorsePower(150); + assertEquals(-1, comparator.compare(car, betterCar)); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/PathMatcherTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/PathMatcherTest.java index a7c172f950..847d42bda3 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/PathMatcherTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/PathMatcherTest.java @@ -11,32 +11,31 @@ public class PathMatcherTest { - private static final QCar $ = QCar.car; - - @Test - public void match() { - Car car = new Car(); - car.setHorsePower(123); - - assertThat(car, hasValue($.horsePower)); - assertThat(car, hasValue($.horsePower, equalTo(123))); - } - - @Test - public void mismatch() { - Car car = new Car(); - car.setHorsePower(123); - - Description mismatchDescription = new StringDescription(); - hasValue($.horsePower, equalTo(321)).describeMismatch(car, mismatchDescription); - assertEquals("value \"car.horsePower\" was <123>", mismatchDescription.toString()); - } - - @Test - public void describe() { - Description description = new StringDescription(); - hasValue($.horsePower, equalTo(321)).describeTo(description); - assertEquals("valueOf(\"car.horsePower\", <321>)", description.toString()); - } - + private static final QCar $ = QCar.car; + + @Test + public void match() { + Car car = new Car(); + car.setHorsePower(123); + + assertThat(car, hasValue($.horsePower)); + assertThat(car, hasValue($.horsePower, equalTo(123))); + } + + @Test + public void mismatch() { + Car car = new Car(); + car.setHorsePower(123); + + Description mismatchDescription = new StringDescription(); + hasValue($.horsePower, equalTo(321)).describeMismatch(car, mismatchDescription); + assertEquals("value \"car.horsePower\" was <123>", mismatchDescription.toString()); + } + + @Test + public void describe() { + Description description = new StringDescription(); + hasValue($.horsePower, equalTo(321)).describeTo(description); + assertEquals("valueOf(\"car.horsePower\", <321>)", description.toString()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/PatternsTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/PatternsTest.java index 9269f0fe21..1e039ccccd 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/PatternsTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/PatternsTest.java @@ -16,17 +16,16 @@ import static org.junit.Assert.assertTrue; import java.util.regex.Pattern; - import org.junit.Test; public class PatternsTest { - @Test - public void matches() { - assertTrue(Pattern.matches("Bob","Bob")); - assertTrue(Pattern.matches("^Bob$","Bob")); - assertTrue(Pattern.matches("^Bo.*","Bob")); - assertTrue(Pattern.matches(".*ob$","Bob")); - assertTrue(Pattern.matches(".*o.*","Bob")); - } + @Test + public void matches() { + assertTrue(Pattern.matches("Bob", "Bob")); + assertTrue(Pattern.matches("^Bob$", "Bob")); + assertTrue(Pattern.matches("^Bo.*", "Bob")); + assertTrue(Pattern.matches(".*ob$", "Bob")); + assertTrue(Pattern.matches(".*o.*", "Bob")); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Person.java b/querydsl-collections/src/test/java/com/querydsl/collections/Person.java index 9bf494b9a1..f41d910a02 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Person.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Person.java @@ -1,13 +1,13 @@ package com.querydsl.collections; public class Person { - private String name; + private String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Post.java b/querydsl-collections/src/test/java/com/querydsl/collections/Post.java index a07ee2e8e6..9c6634a4d1 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Post.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Post.java @@ -13,70 +13,66 @@ */ package com.querydsl.collections; -import java.util.Set; - import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QueryProjection; +import java.util.Set; @QueryEntity public class Post { - private int id; - - private String name; - - private User user; - - private Set comments; + private int id; - public Post() { } + private String name; - @QueryProjection - public Post(int id, String name, User user) { - this.id = id; - this.name = name; - this.user = user; - } + private User user; - @QueryProjection - public Post(int id, String name, Set comments) { - this.id = id; - this.name = name; - this.comments = comments; - } + private Set comments; - public int getId() { - return id; - } + public Post() {} - public void setId(int id) { - this.id = id; - } + @QueryProjection + public Post(int id, String name, User user) { + this.id = id; + this.name = name; + this.user = user; + } - public String getName() { - return name; - } + @QueryProjection + public Post(int id, String name, Set comments) { + this.id = id; + this.name = name; + this.comments = comments; + } - public void setName(String name) { - this.name = name; - } + public int getId() { + return id; + } - public User getUser() { - return user; - } + public void setId(int id) { + this.id = id; + } - public void setUser(User user) { - this.user = user; - } + public String getName() { + return name; + } - public Set getComments() { - return comments; - } + public void setName(String name) { + this.name = name; + } - public void setComments(Set comments) { - this.comments = comments; - } + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + public Set getComments() { + return comments; + } -} \ No newline at end of file + public void setComments(Set comments) { + this.comments = comments; + } +} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/Projection.java b/querydsl-collections/src/test/java/com/querydsl/collections/Projection.java index c5633fd3a1..76f5e5ead1 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/Projection.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/Projection.java @@ -2,7 +2,5 @@ public class Projection { - public Projection(String str, Cat cat) { - } - -} \ No newline at end of file + public Projection(String str, Cat cat) {} +} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/PropertiesTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/PropertiesTest.java index 3e6e41ad03..b2d0df9200 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/PropertiesTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/PropertiesTest.java @@ -4,25 +4,28 @@ import java.util.Collections; import java.util.List; - import org.junit.Test; public class PropertiesTest { - @Test - public void hidden() { - QStateHistory history = QStateHistory.stateHistory; - List histories = Collections.singletonList(new StateHistory()); - assertEquals(1, CollQueryFactory.from(history, histories) - .where(history.changedAt.isNull()).fetch().size()); - } - - @Test - public void hidden2() { - QStateHistoryOwner historyOwner = QStateHistoryOwner.stateHistoryOwner; - List historyOwners = Collections.singletonList(new StateHistoryOwner()); - assertEquals(1, CollQueryFactory.from(historyOwner, historyOwners) - .where(historyOwner.stateHistory.isNull()).fetch().size()); - } + @Test + public void hidden() { + QStateHistory history = QStateHistory.stateHistory; + List histories = Collections.singletonList(new StateHistory()); + assertEquals( + 1, + CollQueryFactory.from(history, histories).where(history.changedAt.isNull()).fetch().size()); + } + @Test + public void hidden2() { + QStateHistoryOwner historyOwner = QStateHistoryOwner.stateHistoryOwner; + List historyOwners = Collections.singletonList(new StateHistoryOwner()); + assertEquals( + 1, + CollQueryFactory.from(historyOwner, historyOwners) + .where(historyOwner.stateHistory.isNull()) + .fetch() + .size()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/QCar.java b/querydsl-collections/src/test/java/com/querydsl/collections/QCar.java index 4f10df5f9f..b56a7689b7 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/QCar.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/QCar.java @@ -7,20 +7,19 @@ public class QCar extends BeanPath { - public final StringPath model = createString("model"); + public final StringPath model = createString("model"); - public final NumberPath horsePower = createNumber("horsePower", Integer.class); + public final NumberPath horsePower = createNumber("horsePower", Integer.class); - public final QPerson owner = new QPerson(new BeanPath(Person.class, this, "owner")); + public final QPerson owner = new QPerson(new BeanPath(Person.class, this, "owner")); - public static QCar car = new QCar(new BeanPath(Car.class, "car")); + public static QCar car = new QCar(new BeanPath(Car.class, "car")); - public QCar(BeanPath entity) { - super(entity.getType(), entity.getMetadata()); - } - - public QCar(PathMetadata metadata) { - super(Car.class, metadata); - } + public QCar(BeanPath entity) { + super(entity.getType(), entity.getMetadata()); + } + public QCar(PathMetadata metadata) { + super(Car.class, metadata); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/QPerson.java b/querydsl-collections/src/test/java/com/querydsl/collections/QPerson.java index 767d56ad66..c225591e46 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/QPerson.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/QPerson.java @@ -6,16 +6,15 @@ public class QPerson extends BeanPath { - public final StringPath name = createString("name"); + public final StringPath name = createString("name"); - public static QPerson car = new QPerson(new BeanPath(Person.class, "person")); + public static QPerson car = new QPerson(new BeanPath(Person.class, "person")); - public QPerson(BeanPath entity) { - super(entity.getType(), entity.getMetadata()); - } - - public QPerson(PathMetadata metadata) { - super(Person.class, metadata); - } + public QPerson(BeanPath entity) { + super(entity.getType(), entity.getMetadata()); + } + public QPerson(PathMetadata metadata) { + super(Person.class, metadata); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/QueryMetadataTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/QueryMetadataTest.java index c5d7a172dd..65ee0192b8 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/QueryMetadataTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/QueryMetadataTest.java @@ -15,25 +15,22 @@ import static org.junit.Assert.assertEquals; -import java.util.Collections; - -import org.junit.Test; - import com.querydsl.core.DefaultQueryMetadata; import com.querydsl.core.JoinType; import com.querydsl.core.QueryMetadata; +import java.util.Collections; +import org.junit.Test; public class QueryMetadataTest extends AbstractQueryTest { - @Test - public void reusage() { - QueryMetadata metadata = new DefaultQueryMetadata(); - metadata.addJoin(JoinType.DEFAULT, cat); - metadata.addWhere(cat.name.startsWith("A")); - - CollQuery query = new CollQuery(metadata); - query.bind(cat, cats); - assertEquals(Collections.singletonList(c3), query.select(cat).fetch()); - } + @Test + public void reusage() { + QueryMetadata metadata = new DefaultQueryMetadata(); + metadata.addJoin(JoinType.DEFAULT, cat); + metadata.addWhere(cat.name.startsWith("A")); + CollQuery query = new CollQuery(metadata); + query.bind(cat, cats); + assertEquals(Collections.singletonList(c3), query.select(cat).fetch()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/QueryMutabilityTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/QueryMutabilityTest.java index e9bfe8567a..49deaca5b1 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/QueryMutabilityTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/QueryMutabilityTest.java @@ -13,25 +13,25 @@ */ package com.querydsl.collections; +import com.querydsl.core.QueryMutability; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collections; - import org.junit.Test; -import com.querydsl.core.QueryMutability; - public class QueryMutabilityTest { - @Test - public void test() throws SecurityException, IllegalArgumentException, - NoSuchMethodException, IllegalAccessException, - InvocationTargetException, IOException { - QCat cat = QCat.cat; - CollQuery query = new CollQuery(); - query.from(cat, Collections. emptyList()); - new QueryMutability(query).test(cat.id, cat.name); - - } - + @Test + public void test() + throws SecurityException, + IllegalArgumentException, + NoSuchMethodException, + IllegalAccessException, + InvocationTargetException, + IOException { + QCat cat = QCat.cat; + CollQuery query = new CollQuery(); + query.from(cat, Collections.emptyList()); + new QueryMutability(query).test(cat.id, cat.name); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/QueryPerformanceTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/QueryPerformanceTest.java index a2dc102f10..2e7a5ce71a 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/QueryPerformanceTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/QueryPerformanceTest.java @@ -1,22 +1,20 @@ package com.querydsl.collections; +import com.querydsl.core.testutil.Performance; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; - import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; - -import com.querydsl.core.testutil.Performance; -import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; @@ -25,43 +23,46 @@ @Category(Performance.class) public class QueryPerformanceTest { - private static final int size = 1000; - - private static List cats = new ArrayList(size); + private static final int size = 1000; - @BeforeClass - public static void setUpClass() throws SQLException, ClassNotFoundException { - for (int i = 0; i < size; i++) { - cats.add(new Cat(String.valueOf(i), i)); - } - } + private static List cats = new ArrayList(size); - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MICROSECONDS) - public void benchmark1() { - // 15857 - QCat cat = QCat.cat; - CollQueryFactory.from(cat, cats).where(cat.id.eq(ThreadLocalRandom.current().nextInt(100) % size)).select(cat).fetch(); + @BeforeClass + public static void setUpClass() throws SQLException, ClassNotFoundException { + for (int i = 0; i < size; i++) { + cats.add(new Cat(String.valueOf(i), i)); } + } - @Test - public void launchBenchmark() throws Exception { - Options opt = new OptionsBuilder() - .include(this.getClass().getName() + ".*") - .mode(Mode.AverageTime) - .timeUnit(TimeUnit.MICROSECONDS) - .warmupTime(TimeValue.seconds(1)) - .warmupIterations(3) - .measurementTime(TimeValue.seconds(1)) - .measurementIterations(3) - .threads(2) - .forks(1) - .shouldFailOnError(true) - .shouldDoGC(true) - .build(); + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void benchmark1() { + // 15857 + QCat cat = QCat.cat; + CollQueryFactory.from(cat, cats) + .where(cat.id.eq(ThreadLocalRandom.current().nextInt(100) % size)) + .select(cat) + .fetch(); + } - new Runner(opt).run(); - } + @Test + public void launchBenchmark() throws Exception { + Options opt = + new OptionsBuilder() + .include(this.getClass().getName() + ".*") + .mode(Mode.AverageTime) + .timeUnit(TimeUnit.MICROSECONDS) + .warmupTime(TimeValue.seconds(1)) + .warmupIterations(3) + .measurementTime(TimeValue.seconds(1)) + .measurementIterations(3) + .threads(2) + .forks(1) + .shouldFailOnError(true) + .shouldDoGC(true) + .build(); + new Runner(opt).run(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/SerializationTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/SerializationTest.java index 74c3469ff4..4001139d59 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/SerializationTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/SerializationTest.java @@ -13,150 +13,155 @@ */ package com.querydsl.collections; +import com.querydsl.core.Tuple; +import com.querydsl.core.types.Projections; +import com.querydsl.core.types.QTuple; import java.util.ArrayList; import java.util.List; - import org.junit.Ignore; import org.junit.Test; -import com.querydsl.core.Tuple; -import com.querydsl.core.types.Projections; -import com.querydsl.core.types.QTuple; - public class SerializationTest extends AbstractQueryTest { - // TODO : order - - // TODO : subqueries - - private QTuple tuple = Projections.tuple(cat, otherCat); - - @Test - public void oneSource_list() { - query().from(cat, cats).select(cat).fetch(); - } - - public List oneSource_list(List cats) { - return cats; - } - - @Test - public void twoSources_list() { - query().from(cat,cats).from(otherCat, cats).select(cat).fetch(); - } - - public List twoSources_list(List cats, List otherCats) { - return cats; - } - - @Test - public void oneSource_filteredList() { - query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat).fetch(); - } - - public List oneSource_filteredList(List cats) { - List rv = new ArrayList(); - for (Cat cat : cats) { // from - if (cat.getName().equals("Kitty")) { // where - rv.add(cat); // list - } - } - return rv; - } - - @Test - public void oneSource_projectedList() { - query().from(cat, cats).select(cat.name).fetch(); - } - - public List oneSource_projectedList(List cats) { - List rv = new ArrayList(); - for (Cat cat : cats) { // from - rv.add(cat.getName()); // list + // TODO : order + + // TODO : subqueries + + private QTuple tuple = Projections.tuple(cat, otherCat); + + @Test + public void oneSource_list() { + query().from(cat, cats).select(cat).fetch(); + } + + public List oneSource_list(List cats) { + return cats; + } + + @Test + public void twoSources_list() { + query().from(cat, cats).from(otherCat, cats).select(cat).fetch(); + } + + public List twoSources_list(List cats, List otherCats) { + return cats; + } + + @Test + public void oneSource_filteredList() { + query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat).fetch(); + } + + public List oneSource_filteredList(List cats) { + List rv = new ArrayList(); + for (Cat cat : cats) { // from + if (cat.getName().equals("Kitty")) { // where + rv.add(cat); // list + } + } + return rv; + } + + @Test + public void oneSource_projectedList() { + query().from(cat, cats).select(cat.name).fetch(); + } + + public List oneSource_projectedList(List cats) { + List rv = new ArrayList(); + for (Cat cat : cats) { // from + rv.add(cat.getName()); // list + } + return rv; + } + + @Test + public void oneSource_filtered_projectedList() { + query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetch(); + } + + public List oneSource_filtered_projectedList(List cats) { + List rv = new ArrayList(); + for (Cat cat : cats) { // from + if (cat.getName().equals("Kitty")) { // where + rv.add(cat.getName()); // list + } + } + return rv; + } + + @Test + public void oneSource_filtered_projectedUnique() { + query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetchOne(); + } + + public String oneSource_filtered_projectedUnique(List cats) { + for (Cat cat : cats) { // from + if (cat.getName().equals("Kitty")) { // where + return cat.getName(); // unique + } + } + throw new IllegalArgumentException(); + } + + @Test + @Ignore + public void join_list() { + query() + .from(cat, cats) + .innerJoin(cat.kittens, kitten) + .where(kitten.name.eq("Kitty")) + .select(cat) + .fetch(); + } + + public List join_list(List cats) { + List rv = new ArrayList(); + for (Cat cat : cats) { // from + for (Cat kitten : cat.getKittens()) { // inner join + if (kitten.getName().equals("Kitty")) { // where + rv.add(cat); // list } - return rv; - } - - @Test - public void oneSource_filtered_projectedList() { - query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetch(); - } - - public List oneSource_filtered_projectedList(List cats) { - List rv = new ArrayList(); - for (Cat cat : cats) { // from - if (cat.getName().equals("Kitty")) { // where - rv.add(cat.getName()); // list - } + } + } + return rv; + } + + public List pairs(List cats, List otherCats) { + query() + .from(cat, cats) + .from(otherCat, otherCats) + .where(cat.name.eq(otherCat.name)) + .select(cat, otherCat) + .fetch(); + + List rv = new ArrayList(); + for (Cat cat : cats) { // from + for (Cat otherCat : otherCats) { // from + if (cat.getName().equals(otherCat.getName())) { // where + rv.add(new Object[] {cat, otherCat}); // list } - return rv; - } - - @Test - public void oneSource_filtered_projectedUnique() { - query().from(cat, cats).where(cat.name.eq("Kitty")).select(cat.name).fetchOne(); - } - - public String oneSource_filtered_projectedUnique(List cats) { - for (Cat cat : cats) { // from - if (cat.getName().equals("Kitty")) { // where - return cat.getName(); // unique - } + } + } + return rv; + } + + public List pairsAsTuple(List cats, List otherCats) { + query() + .from(cat, cats) + .from(otherCat, cats) + .where(cat.name.eq(otherCat.name)) + .select(Projections.tuple(cat, otherCat)) + .fetch(); + + List rv = new ArrayList(); + for (Cat cat : cats) { // from + for (Cat otherCat : otherCats) { // from + if (cat.getName().equals(otherCat.getName())) { // where + rv.add(tuple.newInstance(cat, otherCat)); // list } - throw new IllegalArgumentException(); + } } - - @Test - @Ignore - public void join_list() { - query().from(cat, cats) - .innerJoin(cat.kittens, kitten).where(kitten.name.eq("Kitty")) - .select(cat).fetch(); - } - - public List join_list(List cats) { - List rv = new ArrayList(); - for (Cat cat : cats) { // from - for (Cat kitten : cat.getKittens()) { // inner join - if (kitten.getName().equals("Kitty")) { // where - rv.add(cat); // list - } - } - } - return rv; - } - - public List pairs(List cats, List otherCats) { - query().from(cat, cats) - .from(otherCat, otherCats) - .where(cat.name.eq(otherCat.name)) - .select(cat, otherCat).fetch(); - - List rv = new ArrayList(); - for (Cat cat : cats) { // from - for (Cat otherCat : otherCats) { // from - if (cat.getName().equals(otherCat.getName())) { // where - rv.add(new Object[]{cat,otherCat}); // list - } - } - } - return rv; - } - - public List pairsAsTuple(List cats, List otherCats) { - query().from(cat, cats).from(otherCat, cats) - .where(cat.name.eq(otherCat.name)) - .select(Projections.tuple(cat, otherCat)).fetch(); - - List rv = new ArrayList(); - for (Cat cat : cats) { // from - for (Cat otherCat : otherCats) { // from - if (cat.getName().equals(otherCat.getName())) { // where - rv.add(tuple.newInstance(cat, otherCat)); // list - } - } - } - return rv; - } - + return rv; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/StateHistory.java b/querydsl-collections/src/test/java/com/querydsl/collections/StateHistory.java index 7bb5eaf131..c422b4b05c 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/StateHistory.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/StateHistory.java @@ -1,16 +1,14 @@ package com.querydsl.collections; -import java.util.Date; - import com.querydsl.core.annotations.QueryEntity; +import java.util.Date; @QueryEntity public class StateHistory { - private Date changedAt; - - protected final Date getChangedAtTime() { - return changedAt; - } + private Date changedAt; -} \ No newline at end of file + protected final Date getChangedAtTime() { + return changedAt; + } +} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/StateHistoryOwner.java b/querydsl-collections/src/test/java/com/querydsl/collections/StateHistoryOwner.java index 18ede574d3..8122b9e3c9 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/StateHistoryOwner.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/StateHistoryOwner.java @@ -5,10 +5,9 @@ @QueryEntity public class StateHistoryOwner { - private StateHistory stateHistory; - - protected final StateHistory getStateHistory() { - return stateHistory; - } + private StateHistory stateHistory; + protected final StateHistory getStateHistory() { + return stateHistory; + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/StringHandlingTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/StringHandlingTest.java index 3ed08e2198..b0e15739cb 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/StringHandlingTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/StringHandlingTest.java @@ -15,50 +15,47 @@ import static org.junit.Assert.assertEquals; +import com.querydsl.core.Tuple; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.StringPath; import java.util.Arrays; import java.util.Iterator; import java.util.List; - import org.junit.Test; -import com.querydsl.core.Tuple; -import com.querydsl.core.types.dsl.Expressions; -import com.querydsl.core.types.dsl.StringPath; - public class StringHandlingTest extends AbstractQueryTest { - private List data1 = Arrays.asList("petER", "THomas", "joHAN"); - - private List data2 = Arrays.asList("PETer", "thOMAS", "JOhan"); - - private List data = Arrays.asList("abc", "aBC", "def"); + private List data1 = Arrays.asList("petER", "THomas", "joHAN"); - private final StringPath a = Expressions.stringPath("a"); + private List data2 = Arrays.asList("PETer", "thOMAS", "JOhan"); - private final StringPath b = Expressions.stringPath("b"); + private List data = Arrays.asList("abc", "aBC", "def"); - @Test - public void equalsIgnoreCase() { - Iterator res = Arrays.asList("petER - PETer", - "THomas - thOMAS", "joHAN - JOhan").iterator(); - for (Tuple arr : query() - .from(a, data1) - .from(b, data2) - .where(a.equalsIgnoreCase(b)).select(a, b).fetch()) { - assertEquals(res.next(), arr.get(a) + " - " + arr.get(b)); - } - } + private final StringPath a = Expressions.stringPath("a"); - @Test - public void startsWithIgnoreCase() { - assertEquals(2, CollQueryFactory.from(a, data).where(a.startsWithIgnoreCase("AB")).fetchCount()); - assertEquals(2, CollQueryFactory.from(a, data).where(a.startsWithIgnoreCase("ab")).fetchCount()); - } + private final StringPath b = Expressions.stringPath("b"); - @Test - public void endsWithIgnoreCase() { - assertEquals(2, CollQueryFactory.from(a, data).where(a.endsWithIgnoreCase("BC")).fetchCount()); - assertEquals(2, CollQueryFactory.from(a, data).where(a.endsWithIgnoreCase("bc")).fetchCount()); + @Test + public void equalsIgnoreCase() { + Iterator res = + Arrays.asList("petER - PETer", "THomas - thOMAS", "joHAN - JOhan").iterator(); + for (Tuple arr : + query().from(a, data1).from(b, data2).where(a.equalsIgnoreCase(b)).select(a, b).fetch()) { + assertEquals(res.next(), arr.get(a) + " - " + arr.get(b)); } - + } + + @Test + public void startsWithIgnoreCase() { + assertEquals( + 2, CollQueryFactory.from(a, data).where(a.startsWithIgnoreCase("AB")).fetchCount()); + assertEquals( + 2, CollQueryFactory.from(a, data).where(a.startsWithIgnoreCase("ab")).fetchCount()); + } + + @Test + public void endsWithIgnoreCase() { + assertEquals(2, CollQueryFactory.from(a, data).where(a.endsWithIgnoreCase("BC")).fetchCount()); + assertEquals(2, CollQueryFactory.from(a, data).where(a.endsWithIgnoreCase("bc")).fetchCount()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/TemplatesTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/TemplatesTest.java index 3301c50b4c..f78c706917 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/TemplatesTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/TemplatesTest.java @@ -17,6 +17,4 @@ import com.querydsl.core.TemplatesTestBase; -public class TemplatesTest extends TemplatesTestBase { - -} +public class TemplatesTest extends TemplatesTestBase {} diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/TypeCastTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/TypeCastTest.java index 65921a7562..0633bd73b2 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/TypeCastTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/TypeCastTest.java @@ -13,21 +13,19 @@ */ package com.querydsl.collections; +import com.querydsl.core.types.dsl.PathInits; import java.util.Collections; - import org.junit.Ignore; import org.junit.Test; -import com.querydsl.core.types.dsl.PathInits; - public class TypeCastTest { - @Test(expected = IllegalStateException.class) - @Ignore - public void cast() { - QAnimal animal = QAnimal.animal; - QCat cat = new QCat(animal.getMetadata(), new PathInits("*")); - CollQueryFactory.from(animal, Collections. emptyList()).from(cat, Collections. emptyList()); - } - + @Test(expected = IllegalStateException.class) + @Ignore + public void cast() { + QAnimal animal = QAnimal.animal; + QCat cat = new QCat(animal.getMetadata(), new PathInits("*")); + CollQueryFactory.from(animal, Collections.emptyList()) + .from(cat, Collections.emptyList()); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/UniqueResultContractTest.java b/querydsl-collections/src/test/java/com/querydsl/collections/UniqueResultContractTest.java index b38d77af3d..adc1426da1 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/UniqueResultContractTest.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/UniqueResultContractTest.java @@ -13,21 +13,23 @@ */ package com.querydsl.collections; -import org.junit.Test; - import com.querydsl.core.NonUniqueResultException; import com.querydsl.core.types.Expression; +import org.junit.Test; public class UniqueResultContractTest extends AbstractQueryTest { - @Test(expected = NonUniqueResultException.class) - public void unique_result_throws_exception_on_multiple_results() { - CollQueryFactory.from(cat, cats).where(cat.name.isNotNull()).fetchOne(); - } - - @Test - public void uniqueResult_with_array() { - CollQueryFactory.from(cat, cats).where(cat.name.isNotNull()).limit(1).select(new Expression[]{cat}).fetchOne(); - } + @Test(expected = NonUniqueResultException.class) + public void unique_result_throws_exception_on_multiple_results() { + CollQueryFactory.from(cat, cats).where(cat.name.isNotNull()).fetchOne(); + } + @Test + public void uniqueResult_with_array() { + CollQueryFactory.from(cat, cats) + .where(cat.name.isNotNull()) + .limit(1) + .select(new Expression[] {cat}) + .fetchOne(); + } } diff --git a/querydsl-collections/src/test/java/com/querydsl/collections/User.java b/querydsl-collections/src/test/java/com/querydsl/collections/User.java index 7ce184bc28..09f5733820 100644 --- a/querydsl-collections/src/test/java/com/querydsl/collections/User.java +++ b/querydsl-collections/src/test/java/com/querydsl/collections/User.java @@ -16,43 +16,39 @@ import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QueryProjection; - @QueryEntity public class User { - private String name; - - private Post latestPost; - - public User() { } - - @QueryProjection - public User(String name) { - this.name = name; - } + private String name; - @QueryProjection - public User(String name, Post latestPost) { - this.name = name; - this.latestPost = latestPost; - } + private Post latestPost; - public String getName() { - return name; - } + public User() {} - public void setName(String name) { - this.name = name; - } + @QueryProjection + public User(String name) { + this.name = name; + } - public Post getLatestPost() { - return latestPost; - } + @QueryProjection + public User(String name, Post latestPost) { + this.name = name; + this.latestPost = latestPost; + } - public void setLatestPost(Post latestPost) { - this.latestPost = latestPost; - } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Post getLatestPost() { + return latestPost; + } -} \ No newline at end of file + public void setLatestPost(Post latestPost) { + this.latestPost = latestPost; + } +} diff --git a/querydsl-core/pom.xml b/querydsl-core/pom.xml index 4877512cc2..e544e000ce 100644 --- a/querydsl-core/pom.xml +++ b/querydsl-core/pom.xml @@ -1,5 +1,5 @@ - + 4.0.0 @@ -11,17 +11,17 @@ com.querydsl querydsl-core + jar Querydsl - Core module core module for querydsl ${project.homepage} - jar - + ${project.checkout} ${project.checkout} ${project.githubpage} - + org.jetbrains @@ -38,7 +38,7 @@ classgraph test - + cglib @@ -46,16 +46,16 @@ ${cglib.version} true - - + + org.jvnet.hudson annotation-indexer 1.2 true - - + + jdepend jdepend @@ -63,7 +63,7 @@ test - + @@ -73,6 +73,13 @@ org.apache.maven.plugins maven-jar-plugin + + + + com.querydsl.core + + + test-jar @@ -81,22 +88,15 @@ - - - - com.querydsl.core - - - maven-source-plugin - package test-jar + package diff --git a/querydsl-core/src/main/java/com/querydsl/core/BooleanBuilder.java b/querydsl-core/src/main/java/com/querydsl/core/BooleanBuilder.java index b0ecede3be..a7b1d3edc4 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/BooleanBuilder.java +++ b/querydsl-core/src/main/java/com/querydsl/core/BooleanBuilder.java @@ -13,20 +13,18 @@ */ package com.querydsl.core; -import org.jetbrains.annotations.Nullable; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.ExpressionUtils; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.Visitor; - import java.util.Objects; +import org.jetbrains.annotations.Nullable; /** - * {@code BooleanBuilder} is a cascading builder for {@link Predicate} expressions. - * {@code BooleanBuilder} is a mutable {@link Expression} implementation. + * {@code BooleanBuilder} is a cascading builder for {@link Predicate} expressions. {@code + * BooleanBuilder} is a mutable {@link Expression} implementation. * - *

Usage example:

+ *

Usage example: * *

  * QEmployee employee = QEmployee.employee;
@@ -38,169 +36,165 @@
  *
  * @author tiwe
  */
-public final class BooleanBuilder implements Predicate, Cloneable  {
-
-    private static final long serialVersionUID = -4129485177345542519L;
-
-    @Nullable
-    private Predicate predicate;
-
-    /**
-     * Create an empty BooleanBuilder
-     */
-    public BooleanBuilder() {  }
-
-    /**
-     * Create a BooleanBuilder with the given initial value
-     *
-     * @param initial initial value
-     */
-    public BooleanBuilder(Predicate initial) {
-        predicate = (Predicate) ExpressionUtils.extract(initial);
-    }
-
-    @Override
-    public  R accept(Visitor v, C context) {
-        if (predicate != null) {
-            return predicate.accept(v, context);
-        } else {
-            return null;
-        }
-    }
-
-    /**
-     * Create the intersection of this and the given predicate
-     *
-     * @param right right hand side of {@code and} operation
-     * @return the current object
-     */
-    public BooleanBuilder and(@Nullable Predicate right) {
-        if (right != null) {
-            if (predicate == null) {
-                predicate = right;
-            } else {
-                predicate = ExpressionUtils.and(predicate, right);
-            }
-        }
-        return this;
-    }
-
-    /**
-     * Create the intersection of this and the union of the given args
-     * {@code (this && (arg1 || arg2 ... || argN))}
-     *
-     * @param args union of predicates
-     * @return the current object
-     */
-    public BooleanBuilder andAnyOf(Predicate... args) {
-        if (args.length > 0) {
-            and(ExpressionUtils.anyOf(args));
-        }
-        return this;
-    }
-
-    /**
-     * Create the insertion of this and the negation of the given predicate
-     *
-     * @param right predicate to be negated
-     * @return the current object
-     */
-    public BooleanBuilder andNot(Predicate right) {
-        return and(right.not());
-    }
-
-    @Override
-    public BooleanBuilder clone() throws CloneNotSupportedException {
-        return (BooleanBuilder) super.clone();
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (o == this) {
-            return true;
-        } else if (o instanceof BooleanBuilder) {
-            return Objects.equals(((BooleanBuilder) o).getValue(), predicate);
-        } else {
-            return false;
-        }
-    }
-
-    @Nullable
-    public Predicate getValue() {
-        return predicate;
-    }
-
-    @Override
-    public int hashCode() {
-        return predicate != null ? predicate.hashCode() : 0;
-    }
-
-    /**
-     * Returns true if the value is set, and false, if not
-     *
-     * @return true if initialized and false if not
-     */
-    public boolean hasValue() {
-        return predicate != null;
-    }
-
-    @Override
-    public BooleanBuilder not() {
-        if (predicate != null) {
-            predicate = predicate.not();
-        }
-        return this;
-    }
-
-    /**
-     * Create the union of this and the given predicate
-     *
-     * @param right right hand side of {@code or} operation
-     * @return the current object
-     */
-    public BooleanBuilder or(@Nullable Predicate right) {
-        if (right != null) {
-            if (predicate == null) {
-                predicate = right;
-            } else {
-                predicate = ExpressionUtils.or(predicate, right);
-            }
-        }
-        return this;
-    }
-
-    /**
-     * Create the union of this and the intersection of the given args
-     * {@code (this || (arg1 && arg2 ... && argN))}
-     *
-     * @param args intersection of predicates
-     * @return the current object
-     */
-    public BooleanBuilder orAllOf(Predicate... args) {
-        if (args.length > 0) {
-            or(ExpressionUtils.allOf(args));
-        }
-        return this;
-    }
-
-    /**
-     * Create the union of this and the negation of the given predicate
-     *
-     * @param right predicate to be negated
-     * @return the current object
-     */
-    public BooleanBuilder orNot(Predicate right) {
-        return or(right.not());
-    }
-
-    @Override
-    public Class getType() {
-        return Boolean.class;
-    }
-
-    @Override
-    public String toString() {
-        return predicate != null ? predicate.toString() : super.toString();
-    }
-
+public final class BooleanBuilder implements Predicate, Cloneable {
+
+  private static final long serialVersionUID = -4129485177345542519L;
+
+  @Nullable private Predicate predicate;
+
+  /** Create an empty BooleanBuilder */
+  public BooleanBuilder() {}
+
+  /**
+   * Create a BooleanBuilder with the given initial value
+   *
+   * @param initial initial value
+   */
+  public BooleanBuilder(Predicate initial) {
+    predicate = (Predicate) ExpressionUtils.extract(initial);
+  }
+
+  @Override
+  public  R accept(Visitor v, C context) {
+    if (predicate != null) {
+      return predicate.accept(v, context);
+    } else {
+      return null;
+    }
+  }
+
+  /**
+   * Create the intersection of this and the given predicate
+   *
+   * @param right right hand side of {@code and} operation
+   * @return the current object
+   */
+  public BooleanBuilder and(@Nullable Predicate right) {
+    if (right != null) {
+      if (predicate == null) {
+        predicate = right;
+      } else {
+        predicate = ExpressionUtils.and(predicate, right);
+      }
+    }
+    return this;
+  }
+
+  /**
+   * Create the intersection of this and the union of the given args {@code (this && (arg1 || arg2
+   * ... || argN))}
+   *
+   * @param args union of predicates
+   * @return the current object
+   */
+  public BooleanBuilder andAnyOf(Predicate... args) {
+    if (args.length > 0) {
+      and(ExpressionUtils.anyOf(args));
+    }
+    return this;
+  }
+
+  /**
+   * Create the insertion of this and the negation of the given predicate
+   *
+   * @param right predicate to be negated
+   * @return the current object
+   */
+  public BooleanBuilder andNot(Predicate right) {
+    return and(right.not());
+  }
+
+  @Override
+  public BooleanBuilder clone() throws CloneNotSupportedException {
+    return (BooleanBuilder) super.clone();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (o == this) {
+      return true;
+    } else if (o instanceof BooleanBuilder) {
+      return Objects.equals(((BooleanBuilder) o).getValue(), predicate);
+    } else {
+      return false;
+    }
+  }
+
+  @Nullable
+  public Predicate getValue() {
+    return predicate;
+  }
+
+  @Override
+  public int hashCode() {
+    return predicate != null ? predicate.hashCode() : 0;
+  }
+
+  /**
+   * Returns true if the value is set, and false, if not
+   *
+   * @return true if initialized and false if not
+   */
+  public boolean hasValue() {
+    return predicate != null;
+  }
+
+  @Override
+  public BooleanBuilder not() {
+    if (predicate != null) {
+      predicate = predicate.not();
+    }
+    return this;
+  }
+
+  /**
+   * Create the union of this and the given predicate
+   *
+   * @param right right hand side of {@code or} operation
+   * @return the current object
+   */
+  public BooleanBuilder or(@Nullable Predicate right) {
+    if (right != null) {
+      if (predicate == null) {
+        predicate = right;
+      } else {
+        predicate = ExpressionUtils.or(predicate, right);
+      }
+    }
+    return this;
+  }
+
+  /**
+   * Create the union of this and the intersection of the given args {@code (this || (arg1 && arg2
+   * ... && argN))}
+   *
+   * @param args intersection of predicates
+   * @return the current object
+   */
+  public BooleanBuilder orAllOf(Predicate... args) {
+    if (args.length > 0) {
+      or(ExpressionUtils.allOf(args));
+    }
+    return this;
+  }
+
+  /**
+   * Create the union of this and the negation of the given predicate
+   *
+   * @param right predicate to be negated
+   * @return the current object
+   */
+  public BooleanBuilder orNot(Predicate right) {
+    return or(right.not());
+  }
+
+  @Override
+  public Class getType() {
+    return Boolean.class;
+  }
+
+  @Override
+  public String toString() {
+    return predicate != null ? predicate.toString() : super.toString();
+  }
 }
diff --git a/querydsl-core/src/main/java/com/querydsl/core/DefaultQueryMetadata.java b/querydsl-core/src/main/java/com/querydsl/core/DefaultQueryMetadata.java
index 712db90e59..a61cc57c4d 100644
--- a/querydsl-core/src/main/java/com/querydsl/core/DefaultQueryMetadata.java
+++ b/querydsl-core/src/main/java/com/querydsl/core/DefaultQueryMetadata.java
@@ -15,6 +15,8 @@
 
 import static com.querydsl.core.util.CollectionUtils.*;
 
+import com.querydsl.core.types.*;
+import com.querydsl.core.util.CollectionUtils;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
@@ -24,374 +26,369 @@
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
-
 import org.jetbrains.annotations.Nullable;
 
-import com.querydsl.core.types.*;
-import com.querydsl.core.util.CollectionUtils;
-
 /**
- * {@code DefaultQueryMetadata} is the default implementation of the {@link QueryMetadata} interface.
+ * {@code DefaultQueryMetadata} is the default implementation of the {@link QueryMetadata}
+ * interface.
  *
- * 

{@code DefaultQueryMetadata} is mutable, but {@link DefaultQueryMetadata#clone()} can be used to - * created deep copies to refine the state without modifying the initial instance.

+ *

{@code DefaultQueryMetadata} is mutable, but {@link DefaultQueryMetadata#clone()} can be used + * to created deep copies to refine the state without modifying the initial instance. * * @author tiwe */ public class DefaultQueryMetadata implements QueryMetadata, Cloneable { - private static final long serialVersionUID = 317736313966701232L; - - private boolean distinct; - - private Set> exprInJoins = new LinkedHashSet<>(); - - private List> groupBy = new ArrayList<>(); - - @Nullable - private Predicate having; - - private List joins = new ArrayList<>(); - - private Expression joinTarget; - - private JoinType joinType; - - @Nullable - private Predicate joinCondition; - - private Set joinFlags = new LinkedHashSet<>(); - - private QueryModifiers modifiers = QueryModifiers.EMPTY; - - private List> orderBy = new ArrayList<>(); - - @Nullable - private Expression projection; - - // NOTE : this is not necessarily serializable - private Map, Object> params = new LinkedHashMap<>(); - - private boolean unique; - - @Nullable - private Predicate where; - - private Set flags = new LinkedHashSet<>(); - - private boolean extractParams = true; - - private boolean validate = false; - - private ValidatingVisitor validatingVisitor = ValidatingVisitor.DEFAULT; - - private static Predicate and(Predicate lhs, Predicate rhs) { - if (lhs == null) { - return rhs; - } else { - return ExpressionUtils.and(lhs, rhs); - } - } - - /** - * Create an empty DefaultQueryMetadata instance - */ - public DefaultQueryMetadata() { } - - /** - * Disable validation - * - * @return the current object - */ - public DefaultQueryMetadata noValidate() { - validate = false; - return this; - } - - - @Override - public void addFlag(QueryFlag flag) { - flags = addSorted(flags, flag); - } - - @Override - public void addJoinFlag(JoinFlag flag) { - joinFlags.add(flag); - } - - @Override - public void addGroupBy(Expression o) { - // group by elements can't be validated, since they can refer to projection elements - // that are declared later - groupBy.add(o); - } - - @Override - public void addHaving(Predicate e) { - if (e == null) { - return; - } - e = (Predicate) ExpressionUtils.extract(e); - if (e != null) { - // having elements can't be validated, since they can refer to projection elements - // that are declared later - having = and(having, e); - } - } - - private void addLastJoin() { - if (joinTarget != null) { - joins.add(new JoinExpression(joinType, joinTarget, joinCondition, CollectionUtils.unmodifiableSet(joinFlags))); - joinType = null; - joinTarget = null; - joinCondition = null; - joinFlags.clear(); - } - } - - @Override - public void addJoin(JoinType joinType, Expression expr) { - addLastJoin(); - if (!exprInJoins.contains(expr)) { - if (expr instanceof Path && ((Path) expr).getMetadata().isRoot()) { - exprInJoins.add(expr); - } else { - validate(expr); - } - this.joinType = joinType; - this.joinTarget = expr; - } else if (validate) { - throw new IllegalStateException(expr + " is already used"); - } - } + private static final long serialVersionUID = 317736313966701232L; - @Override - public void addJoinCondition(Predicate o) { - validate(o); - joinCondition = and(joinCondition, o); - } + private boolean distinct; - @Override - public void addOrderBy(OrderSpecifier o) { - // order specifiers can't be validated, since they can refer to projection elements - // that are declared later - orderBy.add(o); - } + private Set> exprInJoins = new LinkedHashSet<>(); - @Override - public void setProjection(Expression o) { - validate(o); - projection = o; - } + private List> groupBy = new ArrayList<>(); - @Override - public void addWhere(Predicate e) { - if (e == null) { - return; - } - e = (Predicate) ExpressionUtils.extract(e); - if (e != null) { - validate(e); - where = and(where, e); - } - } + @Nullable private Predicate having; - @Override - public void clearOrderBy() { - orderBy.clear(); - } + private List joins = new ArrayList<>(); - @Override - public void clearWhere() { - where = new BooleanBuilder(); - } + private Expression joinTarget; - @Override - public QueryMetadata clone() { - try { - DefaultQueryMetadata clone = (DefaultQueryMetadata) super.clone(); - clone.exprInJoins = copyOf(exprInJoins); - clone.groupBy = copyOf(groupBy); - clone.having = having; - clone.joins = copyOf(joins); - clone.joinTarget = joinTarget; - clone.joinCondition = joinCondition; - clone.joinFlags = copyOf(joinFlags); - clone.joinType = joinType; - clone.modifiers = modifiers; - clone.orderBy = copyOf(orderBy); - clone.projection = projection; - clone.params = copyOf(params); - clone.where = where; - clone.flags = copyOfSorted(flags); - return clone; - } catch (CloneNotSupportedException e) { - throw new QueryException(e); - } - } + private JoinType joinType; - @Override - public List> getGroupBy() { - return Collections.unmodifiableList(groupBy); - } + @Nullable private Predicate joinCondition; - @Override - public Predicate getHaving() { - return having; - } + private Set joinFlags = new LinkedHashSet<>(); - @Override - public List getJoins() { - if (joinTarget == null) { - return Collections.unmodifiableList(joins); - } else { - List j = new ArrayList<>(joins); - j.add(new JoinExpression(joinType, joinTarget, joinCondition, Collections.unmodifiableSet(new HashSet<>(joinFlags)))); - return j; - } - } + private QueryModifiers modifiers = QueryModifiers.EMPTY; - @Override - public QueryModifiers getModifiers() { - return modifiers; - } + private List> orderBy = new ArrayList<>(); - @Override - public Map,Object> getParams() { - return Collections.unmodifiableMap(params); - } + @Nullable private Expression projection; - @Override - public List> getOrderBy() { - return Collections.unmodifiableList(orderBy); - } + // NOTE : this is not necessarily serializable + private Map, Object> params = new LinkedHashMap<>(); - @Override - public Expression getProjection() { - return projection; - } + private boolean unique; - @Override - public Predicate getWhere() { - return where; - } + @Nullable private Predicate where; - @Override - public boolean isDistinct() { - return distinct; - } + private Set flags = new LinkedHashSet<>(); - @Override - public boolean isUnique() { - return unique; - } + private boolean extractParams = true; - @Override - public void reset() { - params = new LinkedHashMap<>(); - modifiers = QueryModifiers.EMPTY; - } + private boolean validate = false; - @Override - public void setDistinct(boolean distinct) { - this.distinct = distinct; - } + private ValidatingVisitor validatingVisitor = ValidatingVisitor.DEFAULT; - @Override - public void setLimit(Long limit) { - if (modifiers == null || modifiers.getOffset() == null) { - modifiers = QueryModifiers.limit(limit); - } else { - modifiers = new QueryModifiers(limit, modifiers.getOffset()); - } + private static Predicate and(Predicate lhs, Predicate rhs) { + if (lhs == null) { + return rhs; + } else { + return ExpressionUtils.and(lhs, rhs); } + } - @Override - public void setModifiers(QueryModifiers restriction) { - if (restriction == null) { - throw new NullPointerException(); - } - this.modifiers = restriction; - } + /** Create an empty DefaultQueryMetadata instance */ + public DefaultQueryMetadata() {} - @Override - public void setOffset(Long offset) { - if (modifiers == null || modifiers.getLimit() == null) { - modifiers = QueryModifiers.offset(offset); - } else { - modifiers = new QueryModifiers(modifiers.getLimit(), offset); - } - } - - @Override - public void setUnique(boolean unique) { - this.unique = unique; - } - - @Override - public void setParam(ParamExpression param, T value) { - params = put(params, param, value); - } - - @Override - public Set getFlags() { - return flags; - } - - @Override - public boolean hasFlag(QueryFlag flag) { - return flags.contains(flag); - } - - @Override - public void removeFlag(QueryFlag flag) { - flags = removeSorted(flags, flag); - } - - private void validate(Expression expr) { - if (extractParams) { - expr.accept(ParamsVisitor.DEFAULT, this); - } - if (validate) { - exprInJoins = expr.accept(validatingVisitor, exprInJoins); - } - } - - @Override - public void setValidate(boolean v) { - this.validate = v; - } + /** + * Disable validation + * + * @return the current object + */ + public DefaultQueryMetadata noValidate() { + validate = false; + return this; + } - public void setValidatingVisitor(ValidatingVisitor visitor) { - this.validatingVisitor = visitor; - } - - @Override - public boolean equals(Object o) { - if (o instanceof QueryMetadata) { - QueryMetadata q = (QueryMetadata) o; - return q.getFlags().equals(flags) - && q.getGroupBy().equals(groupBy) - && Objects.equals(q.getHaving(), having) - && q.isDistinct() == distinct - && q.isUnique() == unique - && q.getJoins().equals(getJoins()) - && q.getModifiers().equals(modifiers) - && q.getOrderBy().equals(orderBy) - && q.getParams().equals(params) - && Objects.equals(q.getProjection(), projection) - && Objects.equals(q.getWhere(), where); - - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(flags, groupBy, having, getJoins(), modifiers, - orderBy, params, projection, unique, where); - } + @Override + public void addFlag(QueryFlag flag) { + flags = addSorted(flags, flag); + } + @Override + public void addJoinFlag(JoinFlag flag) { + joinFlags.add(flag); + } + @Override + public void addGroupBy(Expression o) { + // group by elements can't be validated, since they can refer to projection elements + // that are declared later + groupBy.add(o); + } + + @Override + public void addHaving(Predicate e) { + if (e == null) { + return; + } + e = (Predicate) ExpressionUtils.extract(e); + if (e != null) { + // having elements can't be validated, since they can refer to projection elements + // that are declared later + having = and(having, e); + } + } + + private void addLastJoin() { + if (joinTarget != null) { + joins.add( + new JoinExpression( + joinType, joinTarget, joinCondition, CollectionUtils.unmodifiableSet(joinFlags))); + joinType = null; + joinTarget = null; + joinCondition = null; + joinFlags.clear(); + } + } + + @Override + public void addJoin(JoinType joinType, Expression expr) { + addLastJoin(); + if (!exprInJoins.contains(expr)) { + if (expr instanceof Path && ((Path) expr).getMetadata().isRoot()) { + exprInJoins.add(expr); + } else { + validate(expr); + } + this.joinType = joinType; + this.joinTarget = expr; + } else if (validate) { + throw new IllegalStateException(expr + " is already used"); + } + } + + @Override + public void addJoinCondition(Predicate o) { + validate(o); + joinCondition = and(joinCondition, o); + } + + @Override + public void addOrderBy(OrderSpecifier o) { + // order specifiers can't be validated, since they can refer to projection elements + // that are declared later + orderBy.add(o); + } + + @Override + public void setProjection(Expression o) { + validate(o); + projection = o; + } + + @Override + public void addWhere(Predicate e) { + if (e == null) { + return; + } + e = (Predicate) ExpressionUtils.extract(e); + if (e != null) { + validate(e); + where = and(where, e); + } + } + + @Override + public void clearOrderBy() { + orderBy.clear(); + } + + @Override + public void clearWhere() { + where = new BooleanBuilder(); + } + + @Override + public QueryMetadata clone() { + try { + DefaultQueryMetadata clone = (DefaultQueryMetadata) super.clone(); + clone.exprInJoins = copyOf(exprInJoins); + clone.groupBy = copyOf(groupBy); + clone.having = having; + clone.joins = copyOf(joins); + clone.joinTarget = joinTarget; + clone.joinCondition = joinCondition; + clone.joinFlags = copyOf(joinFlags); + clone.joinType = joinType; + clone.modifiers = modifiers; + clone.orderBy = copyOf(orderBy); + clone.projection = projection; + clone.params = copyOf(params); + clone.where = where; + clone.flags = copyOfSorted(flags); + return clone; + } catch (CloneNotSupportedException e) { + throw new QueryException(e); + } + } + + @Override + public List> getGroupBy() { + return Collections.unmodifiableList(groupBy); + } + + @Override + public Predicate getHaving() { + return having; + } + + @Override + public List getJoins() { + if (joinTarget == null) { + return Collections.unmodifiableList(joins); + } else { + List j = new ArrayList<>(joins); + j.add( + new JoinExpression( + joinType, + joinTarget, + joinCondition, + Collections.unmodifiableSet(new HashSet<>(joinFlags)))); + return j; + } + } + + @Override + public QueryModifiers getModifiers() { + return modifiers; + } + + @Override + public Map, Object> getParams() { + return Collections.unmodifiableMap(params); + } + + @Override + public List> getOrderBy() { + return Collections.unmodifiableList(orderBy); + } + + @Override + public Expression getProjection() { + return projection; + } + + @Override + public Predicate getWhere() { + return where; + } + + @Override + public boolean isDistinct() { + return distinct; + } + + @Override + public boolean isUnique() { + return unique; + } + + @Override + public void reset() { + params = new LinkedHashMap<>(); + modifiers = QueryModifiers.EMPTY; + } + + @Override + public void setDistinct(boolean distinct) { + this.distinct = distinct; + } + + @Override + public void setLimit(Long limit) { + if (modifiers == null || modifiers.getOffset() == null) { + modifiers = QueryModifiers.limit(limit); + } else { + modifiers = new QueryModifiers(limit, modifiers.getOffset()); + } + } + + @Override + public void setModifiers(QueryModifiers restriction) { + if (restriction == null) { + throw new NullPointerException(); + } + this.modifiers = restriction; + } + + @Override + public void setOffset(Long offset) { + if (modifiers == null || modifiers.getLimit() == null) { + modifiers = QueryModifiers.offset(offset); + } else { + modifiers = new QueryModifiers(modifiers.getLimit(), offset); + } + } + + @Override + public void setUnique(boolean unique) { + this.unique = unique; + } + + @Override + public void setParam(ParamExpression param, T value) { + params = put(params, param, value); + } + + @Override + public Set getFlags() { + return flags; + } + + @Override + public boolean hasFlag(QueryFlag flag) { + return flags.contains(flag); + } + + @Override + public void removeFlag(QueryFlag flag) { + flags = removeSorted(flags, flag); + } + + private void validate(Expression expr) { + if (extractParams) { + expr.accept(ParamsVisitor.DEFAULT, this); + } + if (validate) { + exprInJoins = expr.accept(validatingVisitor, exprInJoins); + } + } + + @Override + public void setValidate(boolean v) { + this.validate = v; + } + + public void setValidatingVisitor(ValidatingVisitor visitor) { + this.validatingVisitor = visitor; + } + + @Override + public boolean equals(Object o) { + if (o instanceof QueryMetadata) { + QueryMetadata q = (QueryMetadata) o; + return q.getFlags().equals(flags) + && q.getGroupBy().equals(groupBy) + && Objects.equals(q.getHaving(), having) + && q.isDistinct() == distinct + && q.isUnique() == unique + && q.getJoins().equals(getJoins()) + && q.getModifiers().equals(modifiers) + && q.getOrderBy().equals(orderBy) + && q.getParams().equals(params) + && Objects.equals(q.getProjection(), projection) + && Objects.equals(q.getWhere(), where); + + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hash( + flags, groupBy, having, getJoins(), modifiers, orderBy, params, projection, unique, where); + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/EmptyMetadata.java b/querydsl-core/src/main/java/com/querydsl/core/EmptyMetadata.java index f67a588f41..80dd643268 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/EmptyMetadata.java +++ b/querydsl-core/src/main/java/com/querydsl/core/EmptyMetadata.java @@ -13,193 +13,188 @@ */ package com.querydsl.core; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.ParamExpression; import com.querydsl.core.types.Predicate; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * {@code EmptyMetadata} provides an immutable empty {@link QueryMetadata} instance. * - *

Modification methods throw {@link UnsupportedOperationException}.

+ *

Modification methods throw {@link UnsupportedOperationException}. * * @author tiwe - * */ public final class EmptyMetadata implements QueryMetadata { - private static final long serialVersionUID = 134750105981272499L; - - public static final QueryMetadata DEFAULT = new EmptyMetadata(); - - @Override - public void addGroupBy(Expression o) { - throw new UnsupportedOperationException(); - } - - @Override - public void addHaving(Predicate o) { - throw new UnsupportedOperationException(); - } - - @Override - public void addJoin(JoinType joinType, Expression expr) { - throw new UnsupportedOperationException(); - } - - @Override - public void addJoinCondition(Predicate o) { - throw new UnsupportedOperationException(); - } - - @Override - public void addOrderBy(OrderSpecifier o) { - throw new UnsupportedOperationException(); - } - - @Override - public void setProjection(Expression o) { - throw new UnsupportedOperationException(); - } - - @Override - public void addWhere(Predicate o) { - throw new UnsupportedOperationException(); - } - - @Override - public void clearOrderBy() { - throw new UnsupportedOperationException(); - } - - @Override - public void clearWhere() { - throw new UnsupportedOperationException(); - } - - @Override - public QueryMetadata clone() { - return this; - } - - @Override - public List> getGroupBy() { - return Collections.emptyList(); - } - - @Override - public Predicate getHaving() { - return null; - } - - @Override - public List getJoins() { - return Collections.emptyList(); - } - - @Override - public QueryModifiers getModifiers() { - return null; - } - - @Override - public List> getOrderBy() { - return Collections.emptyList(); - } - - @Override - public Expression getProjection() { - return null; - } - - @Override - public Map, Object> getParams() { - return Collections.emptyMap(); - } - - @Override - public Predicate getWhere() { - return null; - } - - @Override - public boolean isDistinct() { - return false; - } - - @Override - public boolean isUnique() { - return false; - } - - @Override - public void reset() { - throw new UnsupportedOperationException(); - } - - @Override - public void setDistinct(boolean distinct) { - throw new UnsupportedOperationException(); - } - - @Override - public void setLimit(Long limit) { - throw new UnsupportedOperationException(); - } - - @Override - public void setModifiers(QueryModifiers restriction) { - throw new UnsupportedOperationException(); - } - - @Override - public void setOffset(Long offset) { - throw new UnsupportedOperationException(); - } - - @Override - public void setUnique(boolean unique) { - throw new UnsupportedOperationException(); - } - - @Override - public void setParam(ParamExpression param, T value) { - throw new UnsupportedOperationException(); - } - - @Override - public void addFlag(QueryFlag flag) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean hasFlag(QueryFlag flag) { - return false; - } - - @Override - public Set getFlags() { - return Collections.emptySet(); - } - - @Override - public void setValidate(boolean v) { - throw new UnsupportedOperationException(); - } - - @Override - public void addJoinFlag(JoinFlag flag) { - throw new UnsupportedOperationException(); - } - - @Override - public void removeFlag(QueryFlag flag) { - - } - + private static final long serialVersionUID = 134750105981272499L; + + public static final QueryMetadata DEFAULT = new EmptyMetadata(); + + @Override + public void addGroupBy(Expression o) { + throw new UnsupportedOperationException(); + } + + @Override + public void addHaving(Predicate o) { + throw new UnsupportedOperationException(); + } + + @Override + public void addJoin(JoinType joinType, Expression expr) { + throw new UnsupportedOperationException(); + } + + @Override + public void addJoinCondition(Predicate o) { + throw new UnsupportedOperationException(); + } + + @Override + public void addOrderBy(OrderSpecifier o) { + throw new UnsupportedOperationException(); + } + + @Override + public void setProjection(Expression o) { + throw new UnsupportedOperationException(); + } + + @Override + public void addWhere(Predicate o) { + throw new UnsupportedOperationException(); + } + + @Override + public void clearOrderBy() { + throw new UnsupportedOperationException(); + } + + @Override + public void clearWhere() { + throw new UnsupportedOperationException(); + } + + @Override + public QueryMetadata clone() { + return this; + } + + @Override + public List> getGroupBy() { + return Collections.emptyList(); + } + + @Override + public Predicate getHaving() { + return null; + } + + @Override + public List getJoins() { + return Collections.emptyList(); + } + + @Override + public QueryModifiers getModifiers() { + return null; + } + + @Override + public List> getOrderBy() { + return Collections.emptyList(); + } + + @Override + public Expression getProjection() { + return null; + } + + @Override + public Map, Object> getParams() { + return Collections.emptyMap(); + } + + @Override + public Predicate getWhere() { + return null; + } + + @Override + public boolean isDistinct() { + return false; + } + + @Override + public boolean isUnique() { + return false; + } + + @Override + public void reset() { + throw new UnsupportedOperationException(); + } + + @Override + public void setDistinct(boolean distinct) { + throw new UnsupportedOperationException(); + } + + @Override + public void setLimit(Long limit) { + throw new UnsupportedOperationException(); + } + + @Override + public void setModifiers(QueryModifiers restriction) { + throw new UnsupportedOperationException(); + } + + @Override + public void setOffset(Long offset) { + throw new UnsupportedOperationException(); + } + + @Override + public void setUnique(boolean unique) { + throw new UnsupportedOperationException(); + } + + @Override + public void setParam(ParamExpression param, T value) { + throw new UnsupportedOperationException(); + } + + @Override + public void addFlag(QueryFlag flag) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean hasFlag(QueryFlag flag) { + return false; + } + + @Override + public Set getFlags() { + return Collections.emptySet(); + } + + @Override + public void setValidate(boolean v) { + throw new UnsupportedOperationException(); + } + + @Override + public void addJoinFlag(JoinFlag flag) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeFlag(QueryFlag flag) {} } diff --git a/querydsl-core/src/main/java/com/querydsl/core/Fetchable.java b/querydsl-core/src/main/java/com/querydsl/core/Fetchable.java index 30ff23a32a..c703db5d7e 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/Fetchable.java +++ b/querydsl-core/src/main/java/com/querydsl/core/Fetchable.java @@ -13,91 +13,88 @@ */ package com.querydsl.core; +import com.mysema.commons.lang.CloseableIterator; import java.util.List; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; - -import com.mysema.commons.lang.CloseableIterator; import org.jetbrains.annotations.Nullable; /** - * {@code Fetchable} defines default projection methods for {@link Query} implementations. - * All Querydsl query implementations should implement this interface. + * {@code Fetchable} defines default projection methods for {@link Query} implementations. All + * Querydsl query implementations should implement this interface. * * @param result type - * * @author tiwe */ public interface Fetchable { - /** - * Get the projection as a typed List - * - * @return results in list form - */ - List fetch(); - - /** - * Get the first result of Get the projection or null if no result is found - * - * @return first result or null - */ - @Nullable - T fetchFirst(); + /** + * Get the projection as a typed List + * + * @return results in list form + */ + List fetch(); - /** - * Get the projection as a unique result or null if no result is found - * - * @throws NonUniqueResultException if there is more than one matching result - * @return first result or null - */ - @Nullable - T fetchOne() throws NonUniqueResultException; + /** + * Get the first result of Get the projection or null if no result is found + * + * @return first result or null + */ + @Nullable + T fetchFirst(); - /** - * Get the projection as a typed closeable Iterator - * - * @return closeable iterator - */ - CloseableIterator iterate(); + /** + * Get the projection as a unique result or null if no result is found + * + * @throws NonUniqueResultException if there is more than one matching result + * @return first result or null + */ + @Nullable + T fetchOne() throws NonUniqueResultException; - /** - * Get the projection as a typed closeable Stream. - * - * @return closeable stream - */ - default Stream stream() { - final CloseableIterator iterator = iterate(); - final Spliterator spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED); - return StreamSupport.stream(spliterator, false) - .onClose(iterator::close); - } + /** + * Get the projection as a typed closeable Iterator + * + * @return closeable iterator + */ + CloseableIterator iterate(); - /** - * Get the projection in {@link QueryResults} form. - * - * Make sure to use {@link #fetch()} instead if you do not rely on the {@link QueryResults#getOffset()} or - * {@link QueryResults#getLimit()}, because it will be more performant. Also, count queries cannot be - * properly generated for all dialects. For example: in JPA count queries can't be generated for queries - * that have multiple group by expressions or a having clause. - * Get the projection in {@link QueryResults} form. - * - * Use {@link #fetch()} instead if you do not need the total count of rows in the query result. - * - * @return results - * @see #fetch() - */ - QueryResults fetchResults(); + /** + * Get the projection as a typed closeable Stream. + * + * @return closeable stream + */ + default Stream stream() { + final CloseableIterator iterator = iterate(); + final Spliterator spliterator = + Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED); + return StreamSupport.stream(spliterator, false).onClose(iterator::close); + } - /** - * Get the count of matched elements - * - * Note: not all QueryDSL modules might optimize fetchCount using a count query. - * An implementation is allowed to fall back to {@code fetch().size()}. - * - * @return row count - */ - long fetchCount(); + /** + * Get the projection in {@link QueryResults} form. + * + *

Make sure to use {@link #fetch()} instead if you do not rely on the {@link + * QueryResults#getOffset()} or {@link QueryResults#getLimit()}, because it will be more + * performant. Also, count queries cannot be properly generated for all dialects. For example: in + * JPA count queries can't be generated for queries that have multiple group by expressions or a + * having clause. Get the projection in {@link QueryResults} form. + * + *

Use {@link #fetch()} instead if you do not need the total count of rows in the query result. + * + * @return results + * @see #fetch() + */ + QueryResults fetchResults(); + /** + * Get the count of matched elements + * + *

Note: not all QueryDSL modules might optimize fetchCount using a count query. An + * implementation is allowed to fall back to {@code fetch().size()}. + * + * @return row count + */ + long fetchCount(); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/FetchableQuery.java b/querydsl-core/src/main/java/com/querydsl/core/FetchableQuery.java index dcfe6d369a..58f65c39ca 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/FetchableQuery.java +++ b/querydsl-core/src/main/java/com/querydsl/core/FetchableQuery.java @@ -22,33 +22,32 @@ * @param element type * @param concrete subtype */ -public interface FetchableQuery> extends SimpleQuery, Fetchable { +public interface FetchableQuery> + extends SimpleQuery, Fetchable { - /** - * Change the projection of this query - * - * @param - * @param expr new projection - * - * @return the current object - */ - FetchableQuery select(Expression expr); + /** + * Change the projection of this query + * + * @param + * @param expr new projection + * @return the current object + */ + FetchableQuery select(Expression expr); - /** - * Change the projection of this query - * - * @param exprs new projection - * @return the current object - */ - FetchableQuery select(Expression... exprs); - - /** - * Apply the given transformer to this {@code FetchableQuery} instance and return the results - * - * @param - * @param transformer result transformer - * @return transformed result - */ - S transform(ResultTransformer transformer); + /** + * Change the projection of this query + * + * @param exprs new projection + * @return the current object + */ + FetchableQuery select(Expression... exprs); + /** + * Apply the given transformer to this {@code FetchableQuery} instance and return the results + * + * @param + * @param transformer result transformer + * @return transformed result + */ + S transform(ResultTransformer transformer); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/FilteredClause.java b/querydsl-core/src/main/java/com/querydsl/core/FilteredClause.java index 6a11a85a98..36b372dda2 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/FilteredClause.java +++ b/querydsl-core/src/main/java/com/querydsl/core/FilteredClause.java @@ -19,19 +19,17 @@ * {@code FilteredClause} is an interface for clauses with a filter condition * * @author tiwe - * * @param concrete subtype */ public interface FilteredClause> { - /** - * Adds the given filter conditions - * - *

Skips null arguments

- * - * @param o filter conditions to be added - * @return the current object - */ - C where(Predicate... o); - + /** + * Adds the given filter conditions + * + *

Skips null arguments + * + * @param o filter conditions to be added + * @return the current object + */ + C where(Predicate... o); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/JoinExpression.java b/querydsl-core/src/main/java/com/querydsl/core/JoinExpression.java index 1397da51cf..4d9d98d38c 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/JoinExpression.java +++ b/querydsl-core/src/main/java/com/querydsl/core/JoinExpression.java @@ -13,17 +13,15 @@ */ package com.querydsl.core; +import com.querydsl.core.annotations.Immutable; +import com.querydsl.core.types.Expression; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.util.CollectionUtils; import java.io.Serializable; import java.util.Collections; import java.util.Objects; import java.util.Set; - import org.jetbrains.annotations.Nullable; -import com.querydsl.core.annotations.Immutable; - -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.Predicate; -import com.querydsl.core.util.CollectionUtils; /** * {@code JoinExpression} is a join element in a {@link Query} instance. @@ -33,91 +31,88 @@ @Immutable public final class JoinExpression implements Serializable { - private static final long serialVersionUID = -1131755765747174886L; - - @Nullable - private final Predicate condition; - - private final Set flags; - - private final Expression target; - - private final JoinType type; - - /** - * Create a new JoinExpression instance - * - * @param type type of join - * @param target target of join - */ - public JoinExpression(JoinType type, Expression target) { - this(type, target, null, Collections.emptySet()); - } - - - /** - * Create a new JoinExpression instance - * - * @param type type of join - * @param target target of join - * @param condition join condition or null, if none is used - * @param flags join flags - */ - public JoinExpression(JoinType type, Expression target, @Nullable Predicate condition, - Set flags) { - this.type = type; - this.target = target; - this.condition = condition; - this.flags = CollectionUtils.unmodifiableSet(flags); + private static final long serialVersionUID = -1131755765747174886L; + + @Nullable private final Predicate condition; + + private final Set flags; + + private final Expression target; + + private final JoinType type; + + /** + * Create a new JoinExpression instance + * + * @param type type of join + * @param target target of join + */ + public JoinExpression(JoinType type, Expression target) { + this(type, target, null, Collections.emptySet()); + } + + /** + * Create a new JoinExpression instance + * + * @param type type of join + * @param target target of join + * @param condition join condition or null, if none is used + * @param flags join flags + */ + public JoinExpression( + JoinType type, Expression target, @Nullable Predicate condition, Set flags) { + this.type = type; + this.target = target; + this.condition = condition; + this.flags = CollectionUtils.unmodifiableSet(flags); + } + + @Nullable + public Predicate getCondition() { + return condition; + } + + public Expression getTarget() { + return target; + } + + public JoinType getType() { + return type; + } + + public boolean hasFlag(JoinFlag flag) { + return flags.contains(flag); + } + + public Set getFlags() { + return flags; + } + + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append(type).append(" ").append(target); + if (condition != null) { + builder.append(" on ").append(condition); } - - @Nullable - public Predicate getCondition() { - return condition; + return builder.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(condition, target, type); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof JoinExpression) { + JoinExpression j = (JoinExpression) o; + return Objects.equals(condition, j.condition) + && Objects.equals(target, j.target) + && Objects.equals(type, j.type); + } else { + return false; } - - public Expression getTarget() { - return target; - } - - public JoinType getType() { - return type; - } - - public boolean hasFlag(JoinFlag flag) { - return flags.contains(flag); - } - - public Set getFlags() { - return flags; - } - - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(type).append(" ").append(target); - if (condition != null) { - builder.append(" on ").append(condition); - } - return builder.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(condition, target, type); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof JoinExpression) { - JoinExpression j = (JoinExpression) o; - return Objects.equals(condition, j.condition) && - Objects.equals(target, j.target) && - Objects.equals(type, j.type); - } else { - return false; - } - } - + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/JoinFlag.java b/querydsl-core/src/main/java/com/querydsl/core/JoinFlag.java index d1d59cd42b..c24348edd7 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/JoinFlag.java +++ b/querydsl-core/src/main/java/com/querydsl/core/JoinFlag.java @@ -13,129 +13,116 @@ */ package com.querydsl.core; -import java.io.Serializable; - import com.querydsl.core.annotations.Immutable; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.ExpressionUtils; +import java.io.Serializable; /** * {@code JoinFlag} defines a join related flag using an Expression instance * - *

{@code JoinFlag} instances can be used in Querydsl modules which serialize queries to String form.

+ *

{@code JoinFlag} instances can be used in Querydsl modules which serialize queries to String + * form. * * @author tiwe */ @Immutable public class JoinFlag implements Serializable { - /** - * The different {@code JoinFlag} positions - */ - public enum Position { - - /** - * before the join - */ - START, - - /** - * as a replacement for the join symbol - */ - OVERRIDE, - - /** - * before the join target - */ - BEFORE_TARGET, - - /** - * before the join condition - */ - BEFORE_CONDITION, - - /** - * after the join - */ - END - + /** The different {@code JoinFlag} positions */ + public enum Position { + + /** before the join */ + START, + + /** as a replacement for the join symbol */ + OVERRIDE, + + /** before the join target */ + BEFORE_TARGET, + + /** before the join condition */ + BEFORE_CONDITION, + + /** after the join */ + END + } + + private static final long serialVersionUID = -688265393547206465L; + + private final Expression flag; + + private final Position position; + + /** + * Create a new instance using the given flag + * + *

The used position is before the target. + * + * @param flag flag in String form + */ + public JoinFlag(String flag) { + this(ExpressionUtils.template(Object.class, flag), Position.BEFORE_TARGET); + } + + /** + * Create a new instance using the given flag and position. + * + * @param flag flag in String form + * @param position position of the flag in the join + */ + public JoinFlag(String flag, Position position) { + this(ExpressionUtils.template(Object.class, flag), position); + } + + /** + * Create a new instance using the given flag + * + *

The used position is before the target. + * + * @param flag flag in Expression form + */ + public JoinFlag(Expression flag) { + this(flag, Position.BEFORE_TARGET); + } + + /** + * Create a new instance using the given flag and position + * + * @param flag flag in Expression form + * @param position position of the flag in the join + */ + public JoinFlag(Expression flag, Position position) { + this.flag = flag; + this.position = position; + } + + @Override + public int hashCode() { + return flag.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof JoinFlag) { + return ((JoinFlag) obj).flag.equals(flag); + } else { + return false; } + } - private static final long serialVersionUID = -688265393547206465L; - - private final Expression flag; - - private final Position position; + @Override + public String toString() { + return flag.toString(); + } - /** - * Create a new instance using the given flag - *

The used position is before the target.

- * - * @param flag flag in String form - */ - public JoinFlag(String flag) { - this(ExpressionUtils.template(Object.class, flag), Position.BEFORE_TARGET); - } - - /** - * Create a new instance using the given flag and position. - * - * @param flag flag in String form - * @param position position of the flag in the join - */ - public JoinFlag(String flag, Position position) { - this(ExpressionUtils.template(Object.class, flag), position); - } - - /** - * Create a new instance using the given flag - *

The used position is before the target.

- * - * @param flag flag in Expression form - */ - public JoinFlag(Expression flag) { - this(flag, Position.BEFORE_TARGET); - } - - /** - * Create a new instance using the given flag and position - * - * @param flag flag in Expression form - * @param position position of the flag in the join - */ - public JoinFlag(Expression flag, Position position) { - this.flag = flag; - this.position = position; - } - - @Override - public int hashCode() { - return flag.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } else if (obj instanceof JoinFlag) { - return ((JoinFlag) obj).flag.equals(flag); - } else { - return false; - } - } - - @Override - public String toString() { - return flag.toString(); - } - - public Expression getFlag() { - return flag; - } - - public Position getPosition() { - return position; - } + public Expression getFlag() { + return flag; + } + public Position getPosition() { + return position; + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/JoinType.java b/querydsl-core/src/main/java/com/querydsl/core/JoinType.java index dee248ecd3..955699865b 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/JoinType.java +++ b/querydsl-core/src/main/java/com/querydsl/core/JoinType.java @@ -19,44 +19,30 @@ * @author tiwe */ public enum JoinType { - /** - * cross join - */ - DEFAULT(false, false), - /** - * inner join - */ - INNERJOIN(true, false), - /** - * join - */ - JOIN(true, false), - /** - * left join - */ - LEFTJOIN(false, true), - /** - * right join - */ - RIGHTJOIN(false, true), - /** - * full join - */ - FULLJOIN(false, true); + /** cross join */ + DEFAULT(false, false), + /** inner join */ + INNERJOIN(true, false), + /** join */ + JOIN(true, false), + /** left join */ + LEFTJOIN(false, true), + /** right join */ + RIGHTJOIN(false, true), + /** full join */ + FULLJOIN(false, true); + private final boolean inner, outer; - private final boolean inner, outer; + JoinType(boolean inner, boolean outer) { + this.inner = inner; + this.outer = outer; + } - JoinType(boolean inner, boolean outer) { - this.inner = inner; - this.outer = outer; - } - - public boolean isInner() { - return inner; - } - - public boolean isOuter() { - return outer; - } + public boolean isInner() { + return inner; + } + public boolean isOuter() { + return outer; + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/NonUniqueResultException.java b/querydsl-core/src/main/java/com/querydsl/core/NonUniqueResultException.java index 39156f7142..f7969b2f78 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/NonUniqueResultException.java +++ b/querydsl-core/src/main/java/com/querydsl/core/NonUniqueResultException.java @@ -14,26 +14,24 @@ package com.querydsl.core; /** - * {@code NonUniqueResultException} is thrown for query results where one result row is expected, but multiple - * are retrieved. + * {@code NonUniqueResultException} is thrown for query results where one result row is expected, + * but multiple are retrieved. * * @author tiwe - * */ public class NonUniqueResultException extends QueryException { - private static final long serialVersionUID = -1757423191400510323L; - - public NonUniqueResultException() { - super("Only one result is allowed for fetchOne calls"); - } + private static final long serialVersionUID = -1757423191400510323L; - public NonUniqueResultException(String message) { - super(message); - } + public NonUniqueResultException() { + super("Only one result is allowed for fetchOne calls"); + } - public NonUniqueResultException(Exception e) { - super(e); - } + public NonUniqueResultException(String message) { + super(message); + } + public NonUniqueResultException(Exception e) { + super(e); + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/Query.java b/querydsl-core/src/main/java/com/querydsl/core/Query.java index b709a150e8..a0e06c96c0 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/Query.java +++ b/querydsl-core/src/main/java/com/querydsl/core/Query.java @@ -19,30 +19,28 @@ /** * {@code Query} defines the main query interface of the fluent query language. * - *

Note that the from method has been left out, since there are implementation - * specific variants of it.

+ *

Note that the from method has been left out, since there are implementation specific variants + * of it. * * @author tiwe * @see SimpleQuery - * * @param concrete subtype */ public interface Query> extends SimpleQuery { - /** - * Add grouping/aggregation expressions - * - * @param o group by expressions - * @return the current object - */ - Q groupBy(Expression... o); - - /** - * Add filters for aggregation - * - * @param o having conditions - * @return the current object - */ - Q having(Predicate... o); + /** + * Add grouping/aggregation expressions + * + * @param o group by expressions + * @return the current object + */ + Q groupBy(Expression... o); + /** + * Add filters for aggregation + * + * @param o having conditions + * @return the current object + */ + Q having(Predicate... o); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryException.java b/querydsl-core/src/main/java/com/querydsl/core/QueryException.java index 9f47b014cb..b1ffa4826b 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryException.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryException.java @@ -17,22 +17,20 @@ * {@code QueryException} is thrown for exceptional query construction issues * * @author tiwe - * */ public class QueryException extends RuntimeException { - private static final long serialVersionUID = 2345665389612058703L; - - public QueryException(String msg) { - super(msg); - } + private static final long serialVersionUID = 2345665389612058703L; - public QueryException(String msg, Throwable t) { - super(msg, t); - } + public QueryException(String msg) { + super(msg); + } - public QueryException(Throwable t) { - super(t); - } + public QueryException(String msg, Throwable t) { + super(msg, t); + } + public QueryException(Throwable t) { + super(t); + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryFactory.java b/querydsl-core/src/main/java/com/querydsl/core/QueryFactory.java index 21d56ba1e6..d53ab20ce1 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryFactory.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryFactory.java @@ -13,20 +13,17 @@ */ package com.querydsl.core; - /** * Common interface for QueryFactory implementations * * @author tiwe - * * @param Query type */ public interface QueryFactory> { - /** - * Create a new Query - * - * @return new query - */ - Q query(); - + /** + * Create a new Query + * + * @return new query + */ + Q query(); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryFlag.java b/querydsl-core/src/main/java/com/querydsl/core/QueryFlag.java index a07b1d0525..11547a5b65 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryFlag.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryFlag.java @@ -13,139 +13,106 @@ */ package com.querydsl.core; -import java.io.Serializable; -import java.util.Objects; - import com.querydsl.core.types.Expression; import com.querydsl.core.types.ExpressionUtils; +import java.io.Serializable; +import java.util.Objects; /** * Defines a positioned flag in a Query for customization of query serialization * * @author tiwe - * */ public class QueryFlag implements Serializable { - private static final long serialVersionUID = -7131081607441961628L; - - /** - * The different {@code QueryFlag} positions - */ - public enum Position { - - /** - * WITH part (used in SQL) - */ - WITH, - - /** - * Start of the query - */ - START, - - /** - * Override for the first element (e.g SELECT, INSERT) - */ - START_OVERRIDE, - - /** - * After the first element (after select) - */ - AFTER_SELECT, - - /** - * After the projection (after select ...) - */ - AFTER_PROJECTION, - - /** - * Before the filter conditions (where) - */ - BEFORE_FILTERS, - - /** - * After the filter conditions (where) - */ - AFTER_FILTERS, - - /** - * Before group by - */ - BEFORE_GROUP_BY, - - /** - * After group by - */ - AFTER_GROUP_BY, - - /** - * Before having - */ - BEFORE_HAVING, - - /** - * After having - */ - AFTER_HAVING, - - /** - * Before order (by) - */ - BEFORE_ORDER, - - /** - * After order (by) - */ - AFTER_ORDER, - - /** - * After all other tokens - */ - END + private static final long serialVersionUID = -7131081607441961628L; - } + /** The different {@code QueryFlag} positions */ + public enum Position { - private final Position position; + /** WITH part (used in SQL) */ + WITH, - private final Expression flag; + /** Start of the query */ + START, - public QueryFlag(Position position, String flag) { - this(position, ExpressionUtils.template(Object.class, flag)); - } + /** Override for the first element (e.g SELECT, INSERT) */ + START_OVERRIDE, - public QueryFlag(Position position, Expression flag) { - this.position = position; - this.flag = flag; - } + /** After the first element (after select) */ + AFTER_SELECT, - public Position getPosition() { - return position; - } + /** After the projection (after select ...) */ + AFTER_PROJECTION, - public Expression getFlag() { - return flag; - } + /** Before the filter conditions (where) */ + BEFORE_FILTERS, - @Override - public int hashCode() { - return Objects.hash(position, flag); - } + /** After the filter conditions (where) */ + AFTER_FILTERS, - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } else if (obj instanceof QueryFlag) { - QueryFlag other = (QueryFlag) obj; - return other.position.equals(position) && other.flag.equals(flag); - } else { - return false; - } - } + /** Before group by */ + BEFORE_GROUP_BY, + + /** After group by */ + AFTER_GROUP_BY, - @Override - public String toString() { - return position + " : " + flag; + /** Before having */ + BEFORE_HAVING, + + /** After having */ + AFTER_HAVING, + + /** Before order (by) */ + BEFORE_ORDER, + + /** After order (by) */ + AFTER_ORDER, + + /** After all other tokens */ + END + } + + private final Position position; + + private final Expression flag; + + public QueryFlag(Position position, String flag) { + this(position, ExpressionUtils.template(Object.class, flag)); + } + + public QueryFlag(Position position, Expression flag) { + this.position = position; + this.flag = flag; + } + + public Position getPosition() { + return position; + } + + public Expression getFlag() { + return flag; + } + + @Override + public int hashCode() { + return Objects.hash(position, flag); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof QueryFlag) { + QueryFlag other = (QueryFlag) obj; + return other.position.equals(position) && other.flag.equals(flag); + } else { + return false; } + } + + @Override + public String toString() { + return position + " : " + flag; + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryMetadata.java b/querydsl-core/src/main/java/com/querydsl/core/QueryMetadata.java index 936416f9fd..8fe1c8719c 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryMetadata.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryMetadata.java @@ -13,262 +13,253 @@ */ package com.querydsl.core; +import com.querydsl.core.types.Expression; +import com.querydsl.core.types.OrderSpecifier; +import com.querydsl.core.types.ParamExpression; +import com.querydsl.core.types.Predicate; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; - import org.jetbrains.annotations.Nullable; - -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.OrderSpecifier; -import com.querydsl.core.types.ParamExpression; -import com.querydsl.core.types.Predicate; import org.jetbrains.annotations.Unmodifiable; /** - * {@code QueryMetadata} defines query metadata such as query sources, filtering - * conditions and the projection + * {@code QueryMetadata} defines query metadata such as query sources, filtering conditions and the + * projection * * @author tiwe */ public interface QueryMetadata extends Serializable { - /** - * Add the given group by expressions - * - * @param o group by expressions - */ - void addGroupBy(Expression o); - - /** - * Add the given having expressions - * - * @param o having conditions - */ - void addHaving(Predicate o); - - /** - * Add the given query join - * - * @param joinType type of join - * @param expr join target - */ - void addJoin(JoinType joinType, Expression expr); - - /** - * Add the given join flag to the last given join - * - * @param flag join flag - */ - void addJoinFlag(JoinFlag flag); - - /** - * Add the given join condition to the last given join - * - * @param o join condition - */ - void addJoinCondition(Predicate o); - - /** - * Add the given order specifiers - * - * @param o order - */ - void addOrderBy(OrderSpecifier o); - - /** - * Add the given where expressions - * - * @param o where condition - */ - void addWhere(Predicate o); - - /** - * Clear the order expressions - */ - void clearOrderBy(); - - /** - * Clear the where expressions - */ - void clearWhere(); - - /** - * Clone this QueryMetadata instance - * - * @return new QueryMetadata instance with cloned state - */ - QueryMetadata clone(); - - /** - * Get the group by expressions - * - * @return group by - */ - @Unmodifiable - List> getGroupBy(); - - /** - * Get the having expressions - * - * @return having condition, or null if none set - */ - @Nullable - Predicate getHaving(); - - /** - * Get the query joins - * - * @return joins - */ - @Unmodifiable - List getJoins(); - - /** - * Get the QueryModifiers - * - * @return modifiers - */ - QueryModifiers getModifiers(); - - /** - * Get the OrderSpecifiers - * - * @return order by - */ - @Unmodifiable - List> getOrderBy(); - - /** - * Get the projection - * - * @return projection - */ - @Nullable - Expression getProjection(); - - /** - * Get the parameter bindings - * - * @return parameter bindings - */ - @Unmodifiable - Map,Object> getParams(); - - /** - * Get the expressions aggregated into a single boolean expression or null, - * if none where defined - * - * @return where condition or null, if none set - */ - @Nullable - Predicate getWhere(); - - /** - * Get whether the projection is distinct - * - * @return distinct - */ - boolean isDistinct(); - - /** - * Get whether the projection is unique - * - * @return unique - */ - boolean isUnique(); - - /** - * Reset the projection - */ - void reset(); - - /** - * Set the distinct flag - * - * @param distinct distinct - */ - void setDistinct(boolean distinct); - - /** - * Set the maximum number of rows - * - * @param limit limit - */ - void setLimit(@Nullable Long limit); - - /** - * Set the query modifiers limit and offset - * - * @param restriction restriction - */ - void setModifiers(QueryModifiers restriction); - - /** - * Set the number of skipped rows - * - * @param offset offset - */ - void setOffset(@Nullable Long offset); - - /** - * Set the unique flag - * - * @param unique unique - */ - void setUnique(boolean unique); - - /** - * Bind the value for the given parameter expression - * - * @param binding type - * @param param parameter - * @param value binding - */ - void setParam(ParamExpression param, T value); - - /** - * Set the projection - * - * @param o projection - */ - void setProjection(Expression o); - - /** - * Add the given query flag - * - * @param flag query flag - */ - void addFlag(QueryFlag flag); - - /** - * Return whether the given query flag is applied - * - * @param flag query flag - * @return true, if present, false, if not - */ - boolean hasFlag(QueryFlag flag); - - /** - * Remove the given query flag - * - * @param flag query flag - */ - void removeFlag(QueryFlag flag); - - /** - * Get all query flags - * - * @return all used query flags - */ - @Unmodifiable - Set getFlags(); - - /** - * Set the validate flag - * - * @param v validate - */ - void setValidate(boolean v); + /** + * Add the given group by expressions + * + * @param o group by expressions + */ + void addGroupBy(Expression o); + + /** + * Add the given having expressions + * + * @param o having conditions + */ + void addHaving(Predicate o); + + /** + * Add the given query join + * + * @param joinType type of join + * @param expr join target + */ + void addJoin(JoinType joinType, Expression expr); + + /** + * Add the given join flag to the last given join + * + * @param flag join flag + */ + void addJoinFlag(JoinFlag flag); + + /** + * Add the given join condition to the last given join + * + * @param o join condition + */ + void addJoinCondition(Predicate o); + + /** + * Add the given order specifiers + * + * @param o order + */ + void addOrderBy(OrderSpecifier o); + + /** + * Add the given where expressions + * + * @param o where condition + */ + void addWhere(Predicate o); + + /** Clear the order expressions */ + void clearOrderBy(); + + /** Clear the where expressions */ + void clearWhere(); + + /** + * Clone this QueryMetadata instance + * + * @return new QueryMetadata instance with cloned state + */ + QueryMetadata clone(); + + /** + * Get the group by expressions + * + * @return group by + */ + @Unmodifiable + List> getGroupBy(); + + /** + * Get the having expressions + * + * @return having condition, or null if none set + */ + @Nullable + Predicate getHaving(); + + /** + * Get the query joins + * + * @return joins + */ + @Unmodifiable + List getJoins(); + + /** + * Get the QueryModifiers + * + * @return modifiers + */ + QueryModifiers getModifiers(); + + /** + * Get the OrderSpecifiers + * + * @return order by + */ + @Unmodifiable + List> getOrderBy(); + + /** + * Get the projection + * + * @return projection + */ + @Nullable + Expression getProjection(); + + /** + * Get the parameter bindings + * + * @return parameter bindings + */ + @Unmodifiable + Map, Object> getParams(); + + /** + * Get the expressions aggregated into a single boolean expression or null, if none where defined + * + * @return where condition or null, if none set + */ + @Nullable + Predicate getWhere(); + + /** + * Get whether the projection is distinct + * + * @return distinct + */ + boolean isDistinct(); + + /** + * Get whether the projection is unique + * + * @return unique + */ + boolean isUnique(); + + /** Reset the projection */ + void reset(); + + /** + * Set the distinct flag + * + * @param distinct distinct + */ + void setDistinct(boolean distinct); + + /** + * Set the maximum number of rows + * + * @param limit limit + */ + void setLimit(@Nullable Long limit); + + /** + * Set the query modifiers limit and offset + * + * @param restriction restriction + */ + void setModifiers(QueryModifiers restriction); + + /** + * Set the number of skipped rows + * + * @param offset offset + */ + void setOffset(@Nullable Long offset); + + /** + * Set the unique flag + * + * @param unique unique + */ + void setUnique(boolean unique); + + /** + * Bind the value for the given parameter expression + * + * @param binding type + * @param param parameter + * @param value binding + */ + void setParam(ParamExpression param, T value); + + /** + * Set the projection + * + * @param o projection + */ + void setProjection(Expression o); + + /** + * Add the given query flag + * + * @param flag query flag + */ + void addFlag(QueryFlag flag); + + /** + * Return whether the given query flag is applied + * + * @param flag query flag + * @return true, if present, false, if not + */ + boolean hasFlag(QueryFlag flag); + + /** + * Remove the given query flag + * + * @param flag query flag + */ + void removeFlag(QueryFlag flag); + + /** + * Get all query flags + * + * @return all used query flags + */ + @Unmodifiable + Set getFlags(); + + /** + * Set the validate flag + * + * @param v validate + */ + void setValidate(boolean v); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryModifiers.java b/querydsl-core/src/main/java/com/querydsl/core/QueryModifiers.java index 1bcd54a027..312194c54c 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryModifiers.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryModifiers.java @@ -16,9 +16,8 @@ import java.io.Serializable; import java.util.List; import java.util.Objects; - -import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; /** * {@code QueryModifiers} combines limit and offset info into a single immutable value type. @@ -27,114 +26,110 @@ */ public final class QueryModifiers implements Serializable { - private static final long serialVersionUID = 2934344588433680339L; + private static final long serialVersionUID = 2934344588433680339L; - /** - * No limit and not offset restriction - */ - public static final QueryModifiers EMPTY = new QueryModifiers(); + /** No limit and not offset restriction */ + public static final QueryModifiers EMPTY = new QueryModifiers(); - private static int toInt(Long l) { - if (l <= Integer.MAX_VALUE) { - return l.intValue(); - } else { - return Integer.MAX_VALUE; - } + private static int toInt(Long l) { + if (l <= Integer.MAX_VALUE) { + return l.intValue(); + } else { + return Integer.MAX_VALUE; } + } - public static QueryModifiers limit(@Range(from = 0, to = Integer.MAX_VALUE) long limit) { - return new QueryModifiers(limit, null); - } + public static QueryModifiers limit(@Range(from = 0, to = Integer.MAX_VALUE) long limit) { + return new QueryModifiers(limit, null); + } - public static QueryModifiers offset(@Range(from = 0, to = Integer.MAX_VALUE) long offset) { - return new QueryModifiers(null, offset); - } + public static QueryModifiers offset(@Range(from = 0, to = Integer.MAX_VALUE) long offset) { + return new QueryModifiers(null, offset); + } - @Nullable - private final Long limit, offset; + @Nullable private final Long limit, offset; - private QueryModifiers() { - limit = null; - offset = null; - } + private QueryModifiers() { + limit = null; + offset = null; + } - public QueryModifiers(@Nullable Long limit, @Nullable Long offset) { - this.limit = limit; - if (limit != null && limit <= 0) { - throw new IllegalArgumentException("Limit must be greater than 0."); - } - this.offset = offset; - if (offset != null && offset < 0) { - throw new IllegalArgumentException("Offset must not be negative."); - } + public QueryModifiers(@Nullable Long limit, @Nullable Long offset) { + this.limit = limit; + if (limit != null && limit <= 0) { + throw new IllegalArgumentException("Limit must be greater than 0."); } - - public QueryModifiers(QueryModifiers modifiers) { - this.limit = modifiers.getLimit(); - this.offset = modifiers.getOffset(); + this.offset = offset; + if (offset != null && offset < 0) { + throw new IllegalArgumentException("Offset must not be negative."); } - - @Nullable - public Long getLimit() { - return limit; + } + + public QueryModifiers(QueryModifiers modifiers) { + this.limit = modifiers.getLimit(); + this.offset = modifiers.getOffset(); + } + + @Nullable + public Long getLimit() { + return limit; + } + + @Nullable + public Integer getLimitAsInteger() { + return limit != null ? toInt(limit) : null; + } + + @Nullable + public Long getOffset() { + return offset; + } + + @Nullable + public Integer getOffsetAsInteger() { + return offset != null ? toInt(offset) : null; + } + + /** + * Checks if is restricting. + * + * @return true, if is restricting + */ + public boolean isRestricting() { + return limit != null || offset != null; + } + + /** + * Get a sublist based on the restriction of limit and offset + * + * @param + * @param list list to be handled + * @return sublist with limit and offset applied + */ + public List subList(List list) { + if (!list.isEmpty()) { + int from = offset != null ? toInt(offset) : 0; + int to = limit != null ? (from + toInt(limit)) : list.size(); + return list.subList(from, Math.min(to, list.size())); + } else { + return list; } - - @Nullable - public Integer getLimitAsInteger() { - return limit != null ? toInt(limit) : null; - } - - @Nullable - public Long getOffset() { - return offset; - } - - @Nullable - public Integer getOffsetAsInteger() { - return offset != null ? toInt(offset) : null; - } - - /** - * Checks if is restricting. - * - * @return true, if is restricting - */ - public boolean isRestricting() { - return limit != null || offset != null; - } - - /** - * Get a sublist based on the restriction of limit and offset - * - * @param - * @param list list to be handled - * @return sublist with limit and offset applied - */ - public List subList(List list) { - if (!list.isEmpty()) { - int from = offset != null ? toInt(offset) : 0; - int to = limit != null ? (from + toInt(limit)) : list.size(); - return list.subList(from, Math.min(to,list.size())); - } else { - return list; - } - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (o instanceof QueryModifiers) { - QueryModifiers qm = (QueryModifiers) o; - return Objects.equals(qm.getLimit(), limit) && Objects.equals(qm.getOffset(), offset); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(limit, offset); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof QueryModifiers) { + QueryModifiers qm = (QueryModifiers) o; + return Objects.equals(qm.getLimit(), limit) && Objects.equals(qm.getOffset(), offset); + } else { + return false; } + } + @Override + public int hashCode() { + return Objects.hash(limit, offset); + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/QueryResults.java b/querydsl-core/src/main/java/com/querydsl/core/QueryResults.java index e7de11978f..f27efe5247 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/QueryResults.java +++ b/querydsl-core/src/main/java/com/querydsl/core/QueryResults.java @@ -16,103 +16,101 @@ import java.io.Serializable; import java.util.Collections; import java.util.List; - import org.jetbrains.annotations.Nullable; /** * {@code QueryResults} bundles data for paged query results * * @param type of result elements - * * @author tiwe */ public final class QueryResults implements Serializable { - private static final long serialVersionUID = -4591506147471300909L; - - private static final QueryResults EMPTY = new QueryResults( - Collections.emptyList(), Long.MAX_VALUE, 0L, 0L); - - @SuppressWarnings("unchecked") - public static QueryResults emptyResults() { - return (QueryResults) EMPTY; - }; - - private final long limit, offset, total; - - private final List results; - - /** - * Create a new {@link QueryResults} instance - * - * @param results paged results - * @param limit used limit - * @param offset used offset - * @param total total result rows count - */ - public QueryResults(List results, @Nullable Long limit, @Nullable Long offset, long total) { - this.limit = limit != null ? limit : Long.MAX_VALUE; - this.offset = offset != null ? offset : 0L; - this.total = total; - this.results = results; - } - - /** - * Create a new {@link QueryResults} instance - * - * @param results paged results - * @param mod limit and offset - * @param total total result rows count - */ - public QueryResults(List results, QueryModifiers mod, long total) { - this(results, mod.getLimit(), mod.getOffset(), total); - } - - /** - * Get the results in List form - * - * An empty list is returned for no results. - * - * @return results - */ - public List getResults() { - return results; - } - - /** - * Get the total number of results - * - * @return total rows - */ - public long getTotal() { - return total; - } - - /** - * Return whether there are results in the current query window - * - * @return true, if no results where found - */ - public boolean isEmpty() { - return results.isEmpty(); - } - - /** - * Get the limit value used for the query - * - * @return applied limit - */ - public long getLimit() { - return limit; - } - - /** - * Get the offset value used for the query - * - * @return applied offset - */ - public long getOffset() { - return offset; - } - + private static final long serialVersionUID = -4591506147471300909L; + + private static final QueryResults EMPTY = + new QueryResults(Collections.emptyList(), Long.MAX_VALUE, 0L, 0L); + + @SuppressWarnings("unchecked") + public static QueryResults emptyResults() { + return (QueryResults) EMPTY; + } + ; + + private final long limit, offset, total; + + private final List results; + + /** + * Create a new {@link QueryResults} instance + * + * @param results paged results + * @param limit used limit + * @param offset used offset + * @param total total result rows count + */ + public QueryResults(List results, @Nullable Long limit, @Nullable Long offset, long total) { + this.limit = limit != null ? limit : Long.MAX_VALUE; + this.offset = offset != null ? offset : 0L; + this.total = total; + this.results = results; + } + + /** + * Create a new {@link QueryResults} instance + * + * @param results paged results + * @param mod limit and offset + * @param total total result rows count + */ + public QueryResults(List results, QueryModifiers mod, long total) { + this(results, mod.getLimit(), mod.getOffset(), total); + } + + /** + * Get the results in List form + * + *

An empty list is returned for no results. + * + * @return results + */ + public List getResults() { + return results; + } + + /** + * Get the total number of results + * + * @return total rows + */ + public long getTotal() { + return total; + } + + /** + * Return whether there are results in the current query window + * + * @return true, if no results where found + */ + public boolean isEmpty() { + return results.isEmpty(); + } + + /** + * Get the limit value used for the query + * + * @return applied limit + */ + public long getLimit() { + return limit; + } + + /** + * Get the offset value used for the query + * + * @return applied offset + */ + public long getOffset() { + return offset; + } } diff --git a/querydsl-core/src/main/java/com/querydsl/core/ResultTransformer.java b/querydsl-core/src/main/java/com/querydsl/core/ResultTransformer.java index 6e1ac6d49d..39a59042a7 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/ResultTransformer.java +++ b/querydsl-core/src/main/java/com/querydsl/core/ResultTransformer.java @@ -13,24 +13,21 @@ */ package com.querydsl.core; - /** - * Executes query on a {@link FetchableQuery} and transforms results into T. This can be used for example - * to group projected columns or to filter out duplicate results. + * Executes query on a {@link FetchableQuery} and transforms results into T. This can be used for + * example to group projected columns or to filter out duplicate results. * * @see com.querydsl.core.group.GroupBy * @author sasa - * * @param Transformations target type */ public interface ResultTransformer { - /** - * Execute the given query and transform the results - * - * @param query query to be used for execution - * @return transformed results - */ - T transform(FetchableQuery query); - + /** + * Execute the given query and transform the results + * + * @param query query to be used for execution + * @return transformed results + */ + T transform(FetchableQuery query); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/SimpleQuery.java b/querydsl-core/src/main/java/com/querydsl/core/SimpleQuery.java index e74d14137d..5f4f58822d 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/SimpleQuery.java +++ b/querydsl-core/src/main/java/com/querydsl/core/SimpleQuery.java @@ -13,68 +13,65 @@ */ package com.querydsl.core; -import org.jetbrains.annotations.Range; - import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.ParamExpression; +import org.jetbrains.annotations.Range; /** * {@code SimpleQuery} defines a simple querying interface than {@link Query} * * @author tiwe - * * @param concrete subtype * @see Query */ public interface SimpleQuery> extends FilteredClause { - /** - * Set the limit / max results for the query results - * - * @param limit max rows - * @return the current object - */ - Q limit(@Range(from = 0, to = Integer.MAX_VALUE) long limit); - - /** - * Set the offset for the query results - * - * @param offset row offset - * @return the current object - */ - Q offset(@Range(from = 0, to = Integer.MAX_VALUE) long offset); + /** + * Set the limit / max results for the query results + * + * @param limit max rows + * @return the current object + */ + Q limit(@Range(from = 0, to = Integer.MAX_VALUE) long limit); - /** - * Set both limit and offset of the query results - * - * @param modifiers query modifiers - * @return the current object - */ - Q restrict(QueryModifiers modifiers); + /** + * Set the offset for the query results + * + * @param offset row offset + * @return the current object + */ + Q offset(@Range(from = 0, to = Integer.MAX_VALUE) long offset); - /** - * Add order expressions - * - * @param o order - * @return the current object - */ - Q orderBy(OrderSpecifier... o); + /** + * Set both limit and offset of the query results + * + * @param modifiers query modifiers + * @return the current object + */ + Q restrict(QueryModifiers modifiers); - /** - * Set the given parameter to the given value - * - * @param - * @param param param - * @param value binding - * @return the current object - */ - Q set(ParamExpression param, T value); + /** + * Add order expressions + * + * @param o order + * @return the current object + */ + Q orderBy(OrderSpecifier... o); - /** - * Set the Query to return distinct results - * - * @return the current object - */ - Q distinct(); + /** + * Set the given parameter to the given value + * + * @param + * @param param param + * @param value binding + * @return the current object + */ + Q set(ParamExpression param, T value); + /** + * Set the Query to return distinct results + * + * @return the current object + */ + Q distinct(); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/Tuple.java b/querydsl-core/src/main/java/com/querydsl/core/Tuple.java index e1afa43ae9..438d3af43b 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/Tuple.java +++ b/querydsl-core/src/main/java/com/querydsl/core/Tuple.java @@ -13,77 +13,72 @@ */ package com.querydsl.core; -import org.jetbrains.annotations.Nullable; - import com.querydsl.core.types.Expression; +import org.jetbrains.annotations.Nullable; /** * {@code Tuple} defines an interface for generic query result projection * - *

Usage example:

- *
- * {@code
+ * 

Usage example: + * + *

{@code
  * List result = query.from(employee).select(employee.firstName, employee.lastName).fetch();
  * for (Tuple row : result) {
  *     System.out.println("firstName " + row.get(employee.firstName));
  *     System.out.println("lastName " + row.get(employee.lastName));
  * }
- * }
- * 
+ * }
* * @author tiwe - * */ public interface Tuple { - /** - * Get a Tuple element by index - * - * @param type of element - * @param index zero based index - * @param type type of element - * @return element in array - */ - @Nullable - T get(int index, Class type); - - /** - * Get a tuple element by expression - * - * @param type of element - * @param expr expression key - * @return result element that matches the expression - */ - @Nullable - T get(Expression expr); - - /** - * Get the size of the Tuple - * - * @return row element count - */ - int size(); + /** + * Get a Tuple element by index + * + * @param type of element + * @param index zero based index + * @param type type of element + * @return element in array + */ + @Nullable + T get(int index, Class type); - /** - * Get the content as an Object array - * - * @return tuple in array form - */ - Object[] toArray(); + /** + * Get a tuple element by expression + * + * @param type of element + * @param expr expression key + * @return result element that matches the expression + */ + @Nullable + T get(Expression expr); - /** - * All Tuples should override equals and hashCode. For compatibility - * across different Tuple implementations, equality check should use - * {@code java.util.Arrays#equals(Object[], Object[])} with {@code #toArray()} as parameters. - */ - boolean equals(Object o); + /** + * Get the size of the Tuple + * + * @return row element count + */ + int size(); - /** - * All Tuples should override equals and hashCode. For compatibility - * across different Tuple implementations, hashCode should use - * {@code java.util.Arrays#hashCode(Object[])} with {@code #toArray()} as parameter. - */ - int hashCode(); + /** + * Get the content as an Object array + * + * @return tuple in array form + */ + Object[] toArray(); + /** + * All Tuples should override equals and hashCode. For compatibility across different Tuple + * implementations, equality check should use {@code java.util.Arrays#equals(Object[], Object[])} + * with {@code #toArray()} as parameters. + */ + boolean equals(Object o); + /** + * All Tuples should override equals and hashCode. For compatibility across different Tuple + * implementations, hashCode should use {@code java.util.Arrays#hashCode(Object[])} with {@code + * #toArray()} as parameter. + */ + int hashCode(); } diff --git a/querydsl-core/src/main/java/com/querydsl/core/alias/Alias.java b/querydsl-core/src/main/java/com/querydsl/core/alias/Alias.java index 6d12ae58d1..0f31743851 100644 --- a/querydsl-core/src/main/java/com/querydsl/core/alias/Alias.java +++ b/querydsl-core/src/main/java/com/querydsl/core/alias/Alias.java @@ -13,6 +13,11 @@ */ package com.querydsl.core.alias; +import com.querydsl.core.types.EntityPath; +import com.querydsl.core.types.Expression; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.*; +import com.querydsl.core.util.StringUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Time; @@ -21,19 +26,12 @@ import java.util.List; import java.util.Map; import java.util.Set; - import org.jetbrains.annotations.Nullable; -import com.querydsl.core.types.EntityPath; -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.Path; -import com.querydsl.core.types.dsl.*; -import com.querydsl.core.util.StringUtils; - /** * {@code Alias} provides alias factory methods * - *

Example:

+ *

Example: * *

{@code
  * Employee e = alias(Employee.class, "e");
@@ -41,9 +39,10 @@
  *     .where($(e.getDepartment().getId()).eq(1001))
  *     .list($(e.getName()))) {
  *     System.out.println(name);
- * }}
+ * } + * } * - *

using the following static imports

+ *

using the following static imports * *

{@code
  * import static com.mysema.query.alias.Alias.$;
@@ -55,423 +54,422 @@
 @SuppressWarnings("PMD")
 public final class Alias {
 
-    private static final AliasFactory aliasFactory = new AliasFactory(new DefaultPathFactory(), new DefaultTypeSystem());
-
-    private static final SimplePath it = Expressions.path(Object.class, "it");
-
-    // exclude $-methods from Checkstyle checks
-    //CHECKSTYLE:OFF
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param 
-     * @return expression
-     */
-    public static > D $() {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    public static  ArrayPath $(D[] arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(BigDecimal arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(BigInteger arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static BooleanPath $(Boolean arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Byte arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    public static > EnumPath $(T arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    @SuppressWarnings("unchecked")
-    public static  CollectionPath> $(Collection arg) {
-        final Object current = aliasFactory.getCurrentAndReset();
-        if (arg instanceof CollectionPath) {
-            return (CollectionPath>) arg; //NOSONAR
-        } else if (arg instanceof ManagedObject) {
-            return (CollectionPath>) ((ManagedObject) arg).__mappedPath();
-        } else {
-            return (CollectionPath>) current;
-        }
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    public static > ComparablePath $(D arg) {
-        return Alias.getPath(arg);
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Double arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Float arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Integer arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static DatePath $(java.sql.Date arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static DateTimePath $(java.util.Date arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    @SuppressWarnings("unchecked")
-    public static  ListPath> $(List arg) {
-        final Object current = aliasFactory.getCurrentAndReset();
-        if (arg instanceof ListPath) {
-            return (ListPath>) arg; //NOSONAR
-        } else if (arg instanceof ManagedObject) {
-            return (ListPath>) ((ManagedObject) arg).__mappedPath();
-        } else {
-            return (ListPath>) current;
-        }
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Long arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @param 
-     * @return expression
-     */
-    @SuppressWarnings("unchecked")
-    public static  MapPath> $(Map arg) {
-        final Object current = aliasFactory.getCurrentAndReset();
-        if (arg instanceof MapPath) {
-            return (MapPath>) arg; //NOSONAR
-        } else if (arg instanceof ManagedObject) {
-            return (MapPath>) ((ManagedObject) arg).__mappedPath();
-        } else {
-            return (MapPath>) current;
-        }
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @param 
-     * @return expression
-     */
-    @SuppressWarnings("unchecked")
-    public static  SetPath> $(Set arg) {
-        final Object current = aliasFactory.getCurrentAndReset();
-        if (arg instanceof SetPath) {
-            return (SetPath>) arg; //NOSONAR
-        } else if (arg instanceof ManagedObject) {
-            return (SetPath>) ((ManagedObject) arg).__mappedPath();
-        } else {
-            return (SetPath>) current;
-        }
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static NumberPath $(Short arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static StringPath $(String arg) {
-        return aliasFactory.getCurrentAndReset();
-    }
-
-    /**
-     * Convert the given alias to an expression
-     *
-     * @param arg alias
-     * @return expression
-     */
-    public static TimePath