From cfc5153efb83d9e5b50ae8506c1bb60d713d642e Mon Sep 17 00:00:00 2001 From: Andreas Igel Date: Wed, 18 Nov 2026 09:14:25 +0100 Subject: [PATCH 01/15] test: cover constructor-accessibility filtering on @SimpleBuilder (#402) --- .../processor/BuilderProcessorTest.java | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java index 226924eb..7a02826e 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java @@ -27,6 +27,7 @@ import static org.javahelpers.codegen.testing.ProcessorAsserts.contains; import static org.javahelpers.codegen.testing.ProcessorAsserts.notContains; import static org.javahelpers.simple.builders.processor.testing.BuilderAsserts.assertGenerationSucceeded; +import static org.javahelpers.simple.builders.processor.testing.BuilderAsserts.assertNoBuilderGenerated; import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.loadGeneratedSource; import com.google.testing.compile.Compilation; @@ -237,6 +238,147 @@ public abstract class AbstractAnnotated { } .hadWarningContaining("The target class for generating a builder should not be abstract"); } + @Test + void shouldWarnAndGenerateNoBuilderWhenOnlyConstructorIsPrivate() { + // Given: a DTO that is exclusively created through a hand-written builder, so its only + // constructor is private + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, "PersonDto", "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldWarnAndGenerateNoBuilderWhenNoArgConstructorIsPrivate() { + // Given: a singleton-style DTO whose only constructor is a private no-arg constructor + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class SingletonDto { + private String name; + private SingletonDto() {} + public static SingletonDto getInstance() { return new SingletonDto(); } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, + "SingletonDto", + "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldGenerateBuilderWhenAccessibleConstructorExistsNextToPrivateOne() { + // Given: a DTO with a private constructor and an accessible public constructor + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public PersonDto() {} + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: the builder is generated using the accessible constructor + String generatedCode = loadGeneratedSource(compilation, "PersonDtoBuilder"); + assertGenerationSucceeded(compilation, "PersonDtoBuilder", generatedCode); + } + + @Test + void + shouldWarnAndGenerateNoBuilderWhenPackagePrivateConstructorIsNotReachableFromGeneratedPackage() { + // Given: a DTO with a package-private constructor whose builder is generated into another + // package, so the constructor is not reachable from the generated code + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder(options = @SimpleBuilder.Options(packageName = "com.example.generated")) + public class WidgetDto { + private String name; + WidgetDto() {} + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = compile(source); + + // Then: compilation succeeds, but no builder is generated + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("No accessible constructor"); + assertNoBuilderGenerated( + compilation, "WidgetDto", "A type without accessible constructor must not get a builder"); + } + + @Test + void shouldFailInStrictModeWhenNoAccessibleConstructor() { + // Given: a DTO without an accessible constructor, compiled with strict mode enabled + JavaFileObject source = + ProcessorTestUtils.forSource( + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class PersonDto { + private String name; + private PersonDto(String name) { this.name = name; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = + ProcessorTestUtils.createCompiler() + .withOptions("-Asimplebuilder.strict=true") + .compile(source); + + // Then: compilation fails with an error + assertThat(compilation).failed(); + assertThat(compilation).hadErrorContaining("No accessible constructor"); + } + @Test void shouldGenerateBuilderForNestedPropertyTypeInSameClass() { // Given: a property whose type is a static nested class of the DTO itself From 209deae7b8521c4c3df47f5dd70b68a148dbd620 Mon Sep 17 00:00:00 2001 From: Andreas Igel Date: Wed, 18 Nov 2026 12:05:49 +0100 Subject: [PATCH 02/15] feat: derive String Javadoc example values from field names (#412) --- .../builders/example/BookDtoBuilder.java | 28 ++--- .../example/ExternalAddressBuilder.java | 30 +++--- .../example/JacksonIntegrationDtoBuilder.java | 10 +- .../example/MannschaftDtoBuilder.java | 10 +- .../example/OrderWithDefaultsBuilder.java | 20 ++-- .../builders/example/PersonDtoBuilder.java | 44 ++++---- .../example/ProductRecordBuilder.java | 20 ++-- .../example/ProductWithDefaultsBuilder.java | 20 ++-- .../builders/example/SponsorDtoBuilder.java | 10 +- .../scoping/TrustedHelperDtoBuilder.java | 10 +- .../field/AddToCollectionGenerator.java | 2 +- .../field/ArrayConversionGenerator.java | 2 +- .../field/BasicSetterGenerator.java | 5 +- .../field/ListConsumerGenerator.java | 11 +- .../field/OptionalHelperGenerator.java | 3 +- .../field/SetConsumerGenerator.java | 11 +- .../field/SupplierMethodGenerator.java | 3 +- .../field/UpdateHelperGenerator.java | 3 +- .../field/VarArgsHelperGenerator.java | 11 +- .../generators/util/JavadocExampleValues.java | 73 +++++++++---- .../generators/util/MethodGeneratorUtil.java | 87 ++++++++++++++- .../model/method/BuilderMethodDto.java | 6 +- .../processor/AnnotationCopyTest.java | 4 +- .../BuilderConfigurationReaderTest.java | 8 +- .../processor/BuilderJavadocExampleTest.java | 30 +++--- .../ComprehensiveFeatureIntegrationTest.java | 102 +++++++++--------- .../processor/FormattingModeTest.java | 10 +- .../processor/UpdateHelperGeneratorTest.java | 6 +- 28 files changed, 361 insertions(+), 218 deletions(-) diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java index 3de32abf..3332d079 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java @@ -25,23 +25,23 @@ * *
{@code
  * BookDto result = BookDtoBuilder.create()
- *     .author("example value")
+ *     .author("example author")
  *     .available(true)
  *     .category('x')
  *     .discount(3.14f)
  *     .exactPrice(BigDecimal.valueOf(3.14))
- *     .genres(Set.of("example value"))
- *     .isbn("example value")
+ *     .genres(Set.of("example genres"))
+ *     .isbn("example isbn")
  *     .lastUpdated(LocalDateTime.now())
- *     .metadata(Map.of("example value", "example value"))
+ *     .metadata(Map.of("example value", "example metadata"))
  *     .pages(42)
  *     .price(3.14)
  *     .publishDate(LocalDate.now())
  *     .publisher(PersonDtoBuilder.create().build())
  *     .salesCount(42L)
- *     .subtitle(Optional.of("example value"))
- *     .tags(List.of("example value"))
- *     .title("example value")
+ *     .subtitle(Optional.of("example subtitle"))
+ *     .tags(List.of("example tags"))
+ *     .title("example title")
  *     .build();
  * }
*/ @@ -180,7 +180,7 @@ public static BookDtoBuilder create() { *

Example:

* *
{@code
-   * builder.author("example value");
+   * builder.author("example author");
    * }
* * @param author the book author to set @@ -288,7 +288,7 @@ public BookDtoBuilder exactPrice(BigDecimal exactPrice) { *

Example:

* *
{@code
-   * builder.genres(Set.of("example value"));
+   * builder.genres(Set.of("example genres"));
    * }
* * @param genres the set of genres to set @@ -307,7 +307,7 @@ public BookDtoBuilder genres(Set genres) { *

Example:

* *
{@code
-   * builder.isbn("example value");
+   * builder.isbn("example isbn");
    * }
* * @param isbn the ISBN to set @@ -345,7 +345,7 @@ public BookDtoBuilder lastUpdated(LocalDateTime lastUpdated) { *

Example:

* *
{@code
-   * builder.metadata(Map.of("example value", "example value"));
+   * builder.metadata(Map.of("example value", "example metadata"));
    * }
* * @param metadata the metadata map to set @@ -472,7 +472,7 @@ public BookDtoBuilder salesCount(long salesCount) { *

Example:

* *
{@code
-   * builder.subtitle(Optional.of("example value"));
+   * builder.subtitle(Optional.of("example subtitle"));
    * }
* * @param subtitle an Optional containing the subtitle to set @@ -491,7 +491,7 @@ public BookDtoBuilder subtitle(Optional subtitle) { *

Example:

* *
{@code
-   * builder.tags(List.of("example value"));
+   * builder.tags(List.of("example tags"));
    * }
* * @param tags the list of tags to set @@ -510,7 +510,7 @@ public BookDtoBuilder tags(List tags) { *

Example:

* *
{@code
-   * builder.title("example value");
+   * builder.title("example title");
    * }
* * @param title the book title to set diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/ExternalAddressBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/ExternalAddressBuilder.java index 7c8de9c9..dbbaee35 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/ExternalAddressBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/ExternalAddressBuilder.java @@ -27,19 +27,19 @@ * *
{@code
  * ExternalAddress result = ExternalAddressBuilder.create()
- *     .city("example value")
+ *     .city("example city")
  *     .city("Hello %s", "World")
- *     .city(() -> "example value")
+ *     .city(() -> "example city")
  *     .city(sb -> sb.append("text"))
  *     .cityUpdate(String::trim)
- *     .street("example value")
+ *     .street("example street")
  *     .street("Hello %s", "World")
- *     .street(() -> "example value")
+ *     .street(() -> "example street")
  *     .street(sb -> sb.append("text"))
  *     .streetUpdate(String::trim)
- *     .zipCode("example value")
+ *     .zipCode("example zipCode")
  *     .zipCode("Hello %s", "World")
- *     .zipCode(() -> "example value")
+ *     .zipCode(() -> "example zipCode")
  *     .zipCode(sb -> sb.append("text"))
  *     .zipCodeUpdate(String::trim)
  *     .build();
@@ -124,7 +124,7 @@ public ExternalAddressBuilder city(Consumer cityStringBuilderCons
    * 

Example:

* *
{@code
-   * builder.city(() -> "example value");
+   * builder.city(() -> "example city");
    * }
* * @param citySupplier supplier for city @@ -164,7 +164,7 @@ public ExternalAddressBuilder city(String format, Object... args) { *

Example:

* *
{@code
-   * builder.city("example value");
+   * builder.city("example city");
    * }
* * @param city city @@ -186,7 +186,7 @@ public ExternalAddressBuilder city(String city) { *

Example:

* *
{@code
-   * builder.city("example value").cityUpdate(String::trim);
+   * builder.city("example city").cityUpdate(String::trim);
    * }
* * @param cityUpdater operator applied to the current value; its result becomes the new value @@ -230,7 +230,7 @@ public ExternalAddressBuilder street(Consumer streetStringBuilder *

Example:

* *
{@code
-   * builder.street(() -> "example value");
+   * builder.street(() -> "example street");
    * }
* * @param streetSupplier supplier for street @@ -270,7 +270,7 @@ public ExternalAddressBuilder street(String format, Object... args) { *

Example:

* *
{@code
-   * builder.street("example value");
+   * builder.street("example street");
    * }
* * @param street street @@ -292,7 +292,7 @@ public ExternalAddressBuilder street(String street) { *

Example:

* *
{@code
-   * builder.street("example value").streetUpdate(String::trim);
+   * builder.street("example street").streetUpdate(String::trim);
    * }
* * @param streetUpdater operator applied to the current value; its result becomes the new value @@ -336,7 +336,7 @@ public ExternalAddressBuilder zipCode(Consumer zipCodeStringBuild *

Example:

* *
{@code
-   * builder.zipCode(() -> "example value");
+   * builder.zipCode(() -> "example zipCode");
    * }
* * @param zipCodeSupplier supplier for zipCode @@ -376,7 +376,7 @@ public ExternalAddressBuilder zipCode(String format, Object... args) { *

Example:

* *
{@code
-   * builder.zipCode("example value");
+   * builder.zipCode("example zipCode");
    * }
* * @param zipCode zipCode @@ -398,7 +398,7 @@ public ExternalAddressBuilder zipCode(String zipCode) { *

Example:

* *
{@code
-   * builder.zipCode("example value").zipCodeUpdate(String::trim);
+   * builder.zipCode("example zipCode").zipCodeUpdate(String::trim);
    * }
* * @param zipCodeUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/JacksonIntegrationDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/JacksonIntegrationDtoBuilder.java index 7e7671f0..af8ba15f 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/JacksonIntegrationDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/JacksonIntegrationDtoBuilder.java @@ -27,9 +27,9 @@ * *
{@code
  * JacksonIntegrationDto result = JacksonIntegrationDtoBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .age(42)
@@ -181,7 +181,7 @@ public JacksonIntegrationDtoBuilder name(Consumer nameStringBuild
    * 

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -223,7 +223,7 @@ public JacksonIntegrationDtoBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -246,7 +246,7 @@ public JacksonIntegrationDtoBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/MannschaftDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/MannschaftDtoBuilder.java index 51089eb7..119bf279 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/MannschaftDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/MannschaftDtoBuilder.java @@ -28,9 +28,9 @@ * *
{@code
  * MannschaftDto result = MannschaftDtoBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .sponsoren(Set.of(SponsorDtoBuilder.create().build()))
@@ -115,7 +115,7 @@ public MannschaftDtoBuilder name(Consumer nameStringBuilderConsum
    * 

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -155,7 +155,7 @@ public MannschaftDtoBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -177,7 +177,7 @@ public MannschaftDtoBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/OrderWithDefaultsBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/OrderWithDefaultsBuilder.java index d0c1e671..1890737f 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/OrderWithDefaultsBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/OrderWithDefaultsBuilder.java @@ -26,17 +26,17 @@ * *
{@code
  * OrderWithDefaults result = OrderWithDefaultsBuilder.create()
- *     .id("example value")
+ *     .id("example id")
  *     .id("Hello %s", "World")
- *     .id(() -> "example value")
+ *     .id(() -> "example id")
  *     .id(sb -> sb.append("text"))
  *     .idUpdate(String::trim)
  *     .priority(42)
  *     .priority(() -> 42)
  *     .priorityUpdate(Math::abs)
- *     .status("example value")
+ *     .status("example status")
  *     .status("Hello %s", "World")
- *     .status(() -> "example value")
+ *     .status(() -> "example status")
  *     .status(sb -> sb.append("text"))
  *     .statusUpdate(String::trim)
  *     .build();
@@ -120,7 +120,7 @@ public OrderWithDefaultsBuilder id(Consumer idStringBuilderConsum
    * 

Example:

* *
{@code
-   * builder.id(() -> "example value");
+   * builder.id(() -> "example id");
    * }
* * @param idSupplier supplier for id @@ -160,7 +160,7 @@ public OrderWithDefaultsBuilder id(String format, Object... args) { *

Example:

* *
{@code
-   * builder.id("example value");
+   * builder.id("example id");
    * }
* * @param id id @@ -182,7 +182,7 @@ public OrderWithDefaultsBuilder id(String id) { *

Example:

* *
{@code
-   * builder.id("example value").idUpdate(String::trim);
+   * builder.id("example id").idUpdate(String::trim);
    * }
* * @param idUpdater operator applied to the current value; its result becomes the new value @@ -290,7 +290,7 @@ public OrderWithDefaultsBuilder status(Consumer statusStringBuild *

Example:

* *
{@code
-   * builder.status(() -> "example value");
+   * builder.status(() -> "example status");
    * }
* * @param statusSupplier supplier for status @@ -330,7 +330,7 @@ public OrderWithDefaultsBuilder status(String format, Object... args) { *

Example:

* *
{@code
-   * builder.status("example value");
+   * builder.status("example status");
    * }
* * @param status status @@ -352,7 +352,7 @@ public OrderWithDefaultsBuilder status(String status) { *

Example:

* *
{@code
-   * builder.status("example value").statusUpdate(String::trim);
+   * builder.status("example status").statusUpdate(String::trim);
    * }
* * @param statusUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/PersonDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/PersonDtoBuilder.java index 327027f0..7d0366f3 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/PersonDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/PersonDtoBuilder.java @@ -30,9 +30,9 @@ * *
{@code
  * PersonDto result = PersonDtoBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .birthdate(LocalDate.now())
@@ -41,15 +41,15 @@
  *     .mannschaft(new MannschaftDto())
  *     .mannschaft(MannschaftDto::new)
  *     .mannschaft(mannschaftDtoBuilder -> mannschaftDtoBuilder)
- *     .nickNames(List.of("example value"))
- *     .nickNames(() -> List.of("example value"))
- *     .nickNames(t -> t.add("example value"))
- *     .nickNames("example value", "example value")
+ *     .nickNames(List.of("example nickNames"))
+ *     .nickNames(() -> List.of("example nickNames"))
+ *     .nickNames(t -> t.add("example nickNames"))
+ *     .nickNames("example nickNames", "example nickNames")
  *     .nickNamesUpdate(list -> list.stream().sorted().toList())
- *     .add2NickNames("example value")
- *     .nickNames2(new String[]{"example value"})
- *     .nickNames2(() -> new String[]{"example value"})
- *     .nickNames2("example value")
+ *     .add2NickNames("example nickNames")
+ *     .nickNames2(new String[]{"example nickNames2"})
+ *     .nickNames2(() -> new String[]{"example nickNames2"})
+ *     .nickNames2("example nickNames2")
  *     .build();
  * }
*/ @@ -286,7 +286,7 @@ public PersonDtoBuilder name(Consumer nameStringBuilderConsumer) *

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -326,7 +326,7 @@ public PersonDtoBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -348,7 +348,7 @@ public PersonDtoBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value @@ -371,7 +371,7 @@ public PersonDtoBuilder nameUpdate(UnaryOperator nameUpdater) { *

Example:

* *
{@code
-   * builder.add2NickNames("example value");
+   * builder.add2NickNames("example nickNames");
    * }
* * @param element the element to add @@ -397,7 +397,7 @@ public PersonDtoBuilder add2NickNames(String element) { *

Example:

* *
{@code
-   * builder.nickNames("example value", "example value");
+   * builder.nickNames("example nickNames", "example nickNames");
    * }
* * @param nickNames nickNames @@ -416,7 +416,7 @@ public PersonDtoBuilder nickNames(String... nickNames) { *

Example:

* *
{@code
-   * builder.nickNames(t -> t.add("example value"));
+   * builder.nickNames(t -> t.add("example nickNames"));
    * }
* * @param nickNamesBuilderConsumer consumer providing an instance of a builder for nickNames @@ -439,7 +439,7 @@ public PersonDtoBuilder nickNames(Consumer> nickNamesBu *

Example:

* *
{@code
-   * builder.nickNames(() -> List.of("example value"));
+   * builder.nickNames(() -> List.of("example nickNames"));
    * }
* * @param nickNamesSupplier supplier for nickNames @@ -458,7 +458,7 @@ public PersonDtoBuilder nickNames(Supplier> nickNamesSupplier) { *

Example:

* *
{@code
-   * builder.nickNames(List.of("example value"));
+   * builder.nickNames(List.of("example nickNames"));
    * }
* * @param nickNames nickNames @@ -480,7 +480,7 @@ public PersonDtoBuilder nickNames(List nickNames) { *

Example:

* *
{@code
-   * builder.nickNames(List.of("example value")).nickNamesUpdate(list -> list.stream().sorted().toList());
+   * builder.nickNames(List.of("example nickNames")).nickNamesUpdate(list -> list.stream().sorted().toList());
    * }
* * @param nickNamesUpdater operator applied to the current value; its result becomes the new value @@ -503,7 +503,7 @@ public PersonDtoBuilder nickNamesUpdate(UnaryOperator> nickNamesUpd *

Example:

* *
{@code
-   * builder.nickNames2("example value");
+   * builder.nickNames2("example nickNames2");
    * }
* * @param nickNames2 nickNames2 @@ -542,7 +542,7 @@ public PersonDtoBuilder nickNames2(Consumer> nickNames2 *

Example:

* *
{@code
-   * builder.nickNames2(() -> new String[]{"example value"});
+   * builder.nickNames2(() -> new String[]{"example nickNames2"});
    * }
* * @param nickNames2Supplier supplier for nickNames2 @@ -561,7 +561,7 @@ public PersonDtoBuilder nickNames2(Supplier nickNames2Supplier) { *

Example:

* *
{@code
-   * builder.nickNames2(new String[]{"example value"});
+   * builder.nickNames2(new String[]{"example nickNames2"});
    * }
* * @param nickNames2 nickNames2 diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductRecordBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductRecordBuilder.java index 9316d7fc..eb83a499 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductRecordBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductRecordBuilder.java @@ -25,17 +25,17 @@ * *
{@code
  * ProductRecord result = ProductRecordBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .price(3.14)
  *     .price(() -> 3.14)
  *     .priceUpdate(Math::abs)
- *     .category("example value")
+ *     .category("example category")
  *     .category("Hello %s", "World")
- *     .category(() -> "example value")
+ *     .category(() -> "example category")
  *     .category(sb -> sb.append("text"))
  *     .categoryUpdate(String::trim)
  *     .build();
@@ -121,7 +121,7 @@ public ProductRecordBuilder category(Consumer categoryStringBuild
    * 

Example:

* *
{@code
-   * builder.category(() -> "example value");
+   * builder.category(() -> "example category");
    * }
* * @param categorySupplier supplier for category @@ -163,7 +163,7 @@ public ProductRecordBuilder category(String format, Object... args) { *

Example:

* *
{@code
-   * builder.category("example value");
+   * builder.category("example category");
    * }
* * @param category category @@ -186,7 +186,7 @@ public ProductRecordBuilder category(String category) { *

Example:

* *
{@code
-   * builder.category("example value").categoryUpdate(String::trim);
+   * builder.category("example category").categoryUpdate(String::trim);
    * }
* * @param categoryUpdater operator applied to the current value; its result becomes the new value @@ -232,7 +232,7 @@ public ProductRecordBuilder name(Consumer nameStringBuilderConsum *

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -274,7 +274,7 @@ public ProductRecordBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -297,7 +297,7 @@ public ProductRecordBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductWithDefaultsBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductWithDefaultsBuilder.java index 84c9f536..6d350b6c 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductWithDefaultsBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/ProductWithDefaultsBuilder.java @@ -26,17 +26,17 @@ * *
{@code
  * ProductWithDefaults result = ProductWithDefaultsBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .price(3.14)
  *     .price(() -> 3.14)
  *     .priceUpdate(Math::abs)
- *     .category("example value")
+ *     .category("example category")
  *     .category("Hello %s", "World")
- *     .category(() -> "example value")
+ *     .category(() -> "example category")
  *     .category(sb -> sb.append("text"))
  *     .categoryUpdate(String::trim)
  *     .active(true)
@@ -202,7 +202,7 @@ public ProductWithDefaultsBuilder category(Consumer categoryStrin
    * 

Example:

* *
{@code
-   * builder.category(() -> "example value");
+   * builder.category(() -> "example category");
    * }
* * @param categorySupplier supplier for category @@ -246,7 +246,7 @@ public ProductWithDefaultsBuilder category(String format, Object... args) { *

Example:

* *
{@code
-   * builder.category("example value");
+   * builder.category("example category");
    * }
* * @param category category @@ -270,7 +270,7 @@ public ProductWithDefaultsBuilder category(String category) { *

Example:

* *
{@code
-   * builder.category("example value").categoryUpdate(String::trim);
+   * builder.category("example category").categoryUpdate(String::trim);
    * }
* * @param categoryUpdater operator applied to the current value; its result becomes the new value @@ -318,7 +318,7 @@ public ProductWithDefaultsBuilder name(Consumer nameStringBuilder *

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -362,7 +362,7 @@ public ProductWithDefaultsBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -386,7 +386,7 @@ public ProductWithDefaultsBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/SponsorDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/SponsorDtoBuilder.java index 74ae41ad..8ec1f942 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/SponsorDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/SponsorDtoBuilder.java @@ -25,9 +25,9 @@ * *
{@code
  * SponsorDto result = SponsorDtoBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .build();
@@ -101,7 +101,7 @@ public SponsorDtoBuilder name(Consumer nameStringBuilderConsumer)
    * 

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -141,7 +141,7 @@ public SponsorDtoBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -163,7 +163,7 @@ public SponsorDtoBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/scoping/TrustedHelperDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/scoping/TrustedHelperDtoBuilder.java index 94fdf114..fedb2c4d 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/scoping/TrustedHelperDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/scoping/TrustedHelperDtoBuilder.java @@ -26,9 +26,9 @@ * *
{@code
  * TrustedHelperDto result = TrustedHelperDtoBuilder.create()
- *     .name("example value")
+ *     .name("example name")
  *     .name("Hello %s", "World")
- *     .name(() -> "example value")
+ *     .name(() -> "example name")
  *     .name(sb -> sb.append("text"))
  *     .nameUpdate(String::trim)
  *     .build();
@@ -103,7 +103,7 @@ public TrustedHelperDtoBuilder name(Consumer nameStringBuilderCon
    * 

Example:

* *
{@code
-   * builder.name(() -> "example value");
+   * builder.name(() -> "example name");
    * }
* * @param nameSupplier supplier for name @@ -143,7 +143,7 @@ public TrustedHelperDtoBuilder name(String format, Object... args) { *

Example:

* *
{@code
-   * builder.name("example value");
+   * builder.name("example name");
    * }
* * @param name name @@ -165,7 +165,7 @@ public TrustedHelperDtoBuilder name(String name) { *

Example:

* *
{@code
-   * builder.name("example value").nameUpdate(String::trim);
+   * builder.name("example name").nameUpdate(String::trim);
    * }
* * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java index 4bddb965..628b13f5 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java @@ -192,7 +192,7 @@ private BuilderMethodDto createAddToCollectionMethod( // Store the fluent-chain fragment so the class-level enhancer can synthesise both the // method-level example block and the class-level kitchen-sink chain from one source of truth. - addExampleChainFragment(methodDto, elementType, context::resolveBuilderType); + addExampleChainFragment(methodDto, elementType, originalFieldName, context::resolveBuilderType); return methodDto; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayConversionGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayConversionGenerator.java index 5daae4c9..801156ed 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayConversionGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ArrayConversionGenerator.java @@ -148,7 +148,7 @@ private BuilderMethodDto createFieldSetterForArrayFromList( .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); // Add example fragment for array conversion method - addExampleChainFragment(methodDto, elementType, context::resolveBuilderType); + addExampleChainFragment(methodDto, elementType, fieldName, context::resolveBuilderType); return methodDto; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/BasicSetterGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/BasicSetterGenerator.java index 98ff52e7..3414eebf 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/BasicSetterGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/BasicSetterGenerator.java @@ -94,7 +94,10 @@ public List generateMethods( // Store the fluent-chain fragment so the class-level enhancer can synthesise both the // method-level example block and the class-level kitchen-sink chain from one source of truth. MethodGeneratorUtil.addExampleChainFragment( - setterMethod, field.getFieldType(), context::resolveBuilderType); + setterMethod, + field.getFieldType(), + field.getOriginalFieldName(), + context::resolveBuilderType); return Collections.singletonList(setterMethod); } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java index 171dbf32..61a3ade8 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java @@ -158,7 +158,8 @@ public List generateMethods( context); // Add method-level example for list consumer - addExampleToListConsumerWithSimpleValue(method, elementType, context::resolveBuilderType); + addExampleToListConsumerWithSimpleValue( + method, elementType, field.getOriginalFieldName(), context::resolveBuilderType); return List.of(method); } @@ -184,12 +185,18 @@ private void addExampleToListConsumerWithBuilder( * * @param method the method to add the example to * @param elementType the element type + * @param fieldName the original field name used for String example values */ private void addExampleToListConsumerWithSimpleValue( BuilderMethodDto method, TypeName elementType, + String fieldName, Function> builderResolver) { addExampleChainFragmentTemplate( - method, "#{methodName}(t -> t.add(#{exampleValue}))", elementType, builderResolver); + method, + "#{methodName}(t -> t.add(#{exampleValue}))", + elementType, + fieldName, + builderResolver); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java index 83aa7e96..7358300c 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java @@ -111,7 +111,8 @@ public List generateMethods( method.getMethodCodeDto().addCodeBlockImport(Optional.class); // Add example fragment for Optional helper method - MethodGeneratorUtil.addExampleChainFragment(method, innerType, context::resolveBuilderType); + MethodGeneratorUtil.addExampleChainFragment( + method, innerType, field.getOriginalFieldName(), context::resolveBuilderType); return Collections.singletonList(method); } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java index afb2e6c7..9411cd04 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java @@ -149,7 +149,8 @@ public List generateMethods( Map.of(), builderType, context); - addExampleToSetConsumerWithSimpleValue(method, elementType, context::resolveBuilderType); + addExampleToSetConsumerWithSimpleValue( + method, elementType, field.getOriginalFieldName(), context::resolveBuilderType); return List.of(method); } @@ -174,12 +175,18 @@ private void addExampleToSetConsumerWithBuilder( * * @param method the method to add the example to * @param elementType the element type + * @param fieldName the original field name used for String example values */ private void addExampleToSetConsumerWithSimpleValue( BuilderMethodDto method, TypeName elementType, + String fieldName, Function> builderResolver) { addExampleChainFragmentTemplate( - method, "#{methodName}(t -> t.add(#{exampleValue}))", elementType, builderResolver); + method, + "#{methodName}(t -> t.add(#{exampleValue}))", + elementType, + fieldName, + builderResolver); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SupplierMethodGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SupplierMethodGenerator.java index 7440fc77..2296a6e6 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SupplierMethodGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SupplierMethodGenerator.java @@ -154,7 +154,8 @@ private BuilderMethodDto createFieldSupplier( .addParam(parameterName, "supplier for %s", fieldJavaDoc) .addReturn(JavadocConstants.RETURN_BUILDER_INSTANCE)); - addExampleChainFragmentWithSupplier(methodDto, fieldType, context::resolveBuilderType); + addExampleChainFragmentWithSupplier( + methodDto, fieldType, fieldName, context::resolveBuilderType); return methodDto; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/UpdateHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/UpdateHelperGenerator.java index b68a7b9e..d80ddd66 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/UpdateHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/UpdateHelperGenerator.java @@ -238,7 +238,8 @@ private static void addUpdateExample( addExampleChainFragmentTemplate(methodDto, "#{methodName}(" + updateExpression.get() + ")"); Optional initialValue = - JavadocExampleValues.getExampleValue(field.getFieldType(), context::resolveBuilderType); + JavadocExampleValues.getExampleValue( + field.getFieldType(), field.getOriginalFieldName(), context::resolveBuilderType); if (initialValue.isEmpty()) { return; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java index 2ed88da9..130930c5 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java @@ -165,11 +165,17 @@ private BuilderMethodDto createFieldSetterByVarArgs( if (fieldType instanceof TypeNameList listType) { method.getMethodCodeDto().addCodeBlockImport(List.class); MethodGeneratorUtil.addExampleChainFragmentVarArgs( - method, listType.getElementType(), context::resolveBuilderType); + method, + listType.getElementType(), + field.getOriginalFieldName(), + context::resolveBuilderType); } else if (fieldType instanceof TypeNameSet setType) { method.getMethodCodeDto().addCodeBlockImport(Set.class); MethodGeneratorUtil.addExampleChainFragmentVarArgs( - method, setType.getElementType(), context::resolveBuilderType); + method, + setType.getElementType(), + field.getOriginalFieldName(), + context::resolveBuilderType); } else if (fieldType instanceof TypeNameMap mapType) { method.getMethodCodeDto().addCodeBlockImport(Map.class); // For maps, only add example if key type is String @@ -178,6 +184,7 @@ private BuilderMethodDto createFieldSetterByVarArgs( method, "#{methodName}(Map.entry(\"key\", #{exampleValue}))", mapType.getValueType(), + field.getOriginalFieldName(), context::resolveBuilderType); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java index dec68d21..36f89fc4 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java @@ -47,6 +47,8 @@ public final class JavadocExampleValues { private static final String STRING_EXAMPLE = "\"example value\""; + private static final String STRING_EXAMPLE_PREFIX = "\"example "; + private static final String STRING_EXAMPLE_SUFFIX = "\""; private static final String INT_EXAMPLE = "42"; private static final String LONG_EXAMPLE = "42L"; private static final String DOUBLE_EXAMPLE = "3.14"; @@ -99,7 +101,8 @@ private JavadocExampleValues() { * *
    *
  • Primitive types (int, long, double, float, boolean, char) - *
  • String type (returns {@value STRING_EXAMPLE}) + *
  • String type (returns {@code "example "} when a field name is provided, + * otherwise {@value STRING_EXAMPLE}) *
  • Wrapper types (Integer, Long, Double, Float, Boolean, Character) *
  • Common JDK types (BigInteger, BigDecimal, UUID, LocalDate, LocalTime, LocalDateTime) *
  • Collection types (List, Set) of any supported element type (e.g., {@code List.of("example @@ -118,12 +121,33 @@ private JavadocExampleValues() { */ public static Optional getExampleValue( TypeName typeName, Function> builderResolver) { + return getExampleValue(typeName, null, builderResolver); + } + + /** + * Returns an example value for the given type name, if available. + * + *

    Behaves like {@link #getExampleValue(TypeName, Function)}, but derives String examples from + * the given field name (e.g. field {@code category} → {@code "example category"}). The field name + * is passed through to nested String types (List/Set elements, array elements, Optional inner + * type, Map value type). All non-String types ignore the field name. + * + * @param typeName the type name to get an example value for + * @param fieldName the original field name used for String examples, or {@code null}/blank to + * fall back to {@value STRING_EXAMPLE} + * @param builderResolver resolves a type's builder for builder-backed examples + * @return an Optional containing the example value, or empty if no example is available + */ + public static Optional getExampleValue( + TypeName typeName, + String fieldName, + Function> builderResolver) { return resolvePrimitive(typeName) - .or(() -> resolveCollection(typeName, builderResolver)) - .or(() -> resolveArray(typeName, builderResolver)) - .or(() -> resolveOptional(typeName, builderResolver)) + .or(() -> resolveCollection(typeName, fieldName, builderResolver)) + .or(() -> resolveArray(typeName, fieldName, builderResolver)) + .or(() -> resolveOptional(typeName, fieldName, builderResolver)) .or(() -> resolveCommonType(typeName)) - .or(() -> resolveString(typeName)) + .or(() -> resolveString(typeName, fieldName)) .or(() -> resolveEmptyConstructor(typeName)) .or(() -> resolveBuilderType(typeName, builderResolver)); } @@ -136,17 +160,19 @@ private static Optional resolvePrimitive(TypeName typeName) { } private static Optional resolveCollection( - TypeName typeName, Function> builderResolver) { + TypeName typeName, + String fieldName, + Function> builderResolver) { if (typeName instanceof TypeNameList listType && listType.isParameterized()) { - return getElementExample(listType, builderResolver) + return getElementExample(listType, fieldName, builderResolver) .map(elementExample -> "List.of(" + elementExample + ")"); } if (typeName instanceof TypeNameSet setType && setType.isParameterized()) { - return getElementExample(setType, builderResolver) + return getElementExample(setType, fieldName, builderResolver) .map(elementExample -> "Set.of(" + elementExample + ")"); } if (typeName instanceof TypeNameMap mapType && mapType.isParameterized()) { - return resolveMap(mapType, builderResolver); + return resolveMap(mapType, fieldName, builderResolver); } return Optional.empty(); } @@ -157,8 +183,9 @@ private static Optional resolveCollection( */ private static Optional getElementExample( TypeNameCollection collectionType, + String fieldName, Function> builderResolver) { - return getExampleValue(collectionType.getElementType(), builderResolver) + return getExampleValue(collectionType.getElementType(), fieldName, builderResolver) .or( () -> builderResolver @@ -167,10 +194,12 @@ private static Optional getElementExample( } private static Optional resolveArray( - TypeName typeName, Function> builderResolver) { + TypeName typeName, + String fieldName, + Function> builderResolver) { if (typeName instanceof TypeNameArray arrayType) { TypeName elementType = arrayType.getTypeOfArray(); - return getExampleValue(elementType, builderResolver) + return getExampleValue(elementType, fieldName, builderResolver) .map( elementExample -> "new " + elementType.getClassName() + "[] {" + elementExample + "}"); @@ -179,9 +208,12 @@ private static Optional resolveArray( } private static Optional resolveMap( - TypeNameMap mapType, Function> builderResolver) { + TypeNameMap mapType, + String fieldName, + Function> builderResolver) { Optional keyExample = getExampleValue(mapType.getKeyType(), builderResolver); - Optional valueExample = getExampleValue(mapType.getValueType(), builderResolver); + Optional valueExample = + getExampleValue(mapType.getValueType(), fieldName, builderResolver); if (keyExample.isPresent() && valueExample.isPresent()) { return Optional.of("Map.of(" + keyExample.get() + ", " + valueExample.get() + ")"); } @@ -189,11 +221,13 @@ private static Optional resolveMap( } private static Optional resolveOptional( - TypeName typeName, Function> builderResolver) { + TypeName typeName, + String fieldName, + Function> builderResolver) { if (typeName.is(Optional.class)) { return typeName .getInnerType() - .flatMap(innerType -> getExampleValue(innerType, builderResolver)) + .flatMap(innerType -> getExampleValue(innerType, fieldName, builderResolver)) .map(inner -> "Optional.of(" + inner + ")"); } return Optional.empty(); @@ -207,9 +241,12 @@ private static Optional resolveCommonType(TypeName typeName) { return Optional.empty(); } - private static Optional resolveString(TypeName typeName) { + private static Optional resolveString(TypeName typeName, String fieldName) { if (typeName.is(String.class)) { - return Optional.of(STRING_EXAMPLE); + if (fieldName == null || fieldName.isBlank()) { + return Optional.of(STRING_EXAMPLE); + } + return Optional.of(STRING_EXAMPLE_PREFIX + fieldName + STRING_EXAMPLE_SUFFIX); } return Optional.empty(); } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java index fb6f1087..063905cd 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java @@ -469,8 +469,26 @@ public static void addExampleChainFragment( BuilderMethodDto methodDto, TypeName fieldType, Function> builderResolver) { + addExampleChainFragment(methodDto, fieldType, null, builderResolver); + } + + /** + * Adds the fluent-chain fragment for Javadoc examples to a method. + * + *

    Behaves like {@link #addExampleChainFragment(BuilderMethodDto, TypeName, Function)}, but + * derives String example values from the given field name (e.g. {@code "example "}). + * + * @param methodDto the method DTO to add the fragment to + * @param fieldType the field type to get an example value for + * @param fieldName the original field name used for String example values (may be {@code null}) + */ + public static void addExampleChainFragment( + BuilderMethodDto methodDto, + TypeName fieldType, + String fieldName, + Function> builderResolver) { addExampleChainFragmentTemplate( - methodDto, "#{methodName}(#{exampleValue})", fieldType, builderResolver); + methodDto, "#{methodName}(#{exampleValue})", fieldType, fieldName, builderResolver); } /** @@ -491,8 +509,30 @@ public static void addExampleChainFragmentVarArgs( BuilderMethodDto methodDto, TypeName elementType, Function> builderResolver) { + addExampleChainFragmentVarArgs(methodDto, elementType, null, builderResolver); + } + + /** + * Adds the fluent-chain fragment for Javadoc examples to a varargs method. + * + *

    Behaves like {@link #addExampleChainFragmentVarArgs(BuilderMethodDto, TypeName, Function)}, + * but derives String example values from the given field name. + * + * @param methodDto the method DTO to add the fragment to + * @param elementType the element type to get an example value for + * @param fieldName the original field name used for String example values (may be {@code null}) + */ + public static void addExampleChainFragmentVarArgs( + BuilderMethodDto methodDto, + TypeName elementType, + String fieldName, + Function> builderResolver) { addExampleChainFragmentTemplate( - methodDto, "#{methodName}(#{exampleValue}, #{exampleValue})", elementType, builderResolver); + methodDto, + "#{methodName}(#{exampleValue}, #{exampleValue})", + elementType, + fieldName, + builderResolver); } /** @@ -513,12 +553,30 @@ public static void addExampleChainFragmentWithSupplier( BuilderMethodDto methodDto, TypeName fieldType, Function> builderResolver) { + addExampleChainFragmentWithSupplier(methodDto, fieldType, null, builderResolver); + } + + /** + * Adds the fluent-chain fragment for Javadoc examples to a method using a supplier pattern. + * + *

    Behaves like {@link #addExampleChainFragmentWithSupplier(BuilderMethodDto, TypeName, + * Function)}, but derives String example values from the given field name. + * + * @param methodDto the method DTO to add the fragment to + * @param fieldType the field type to get an example value for + * @param fieldName the original field name used for String example values (may be {@code null}) + */ + public static void addExampleChainFragmentWithSupplier( + BuilderMethodDto methodDto, + TypeName fieldType, + String fieldName, + Function> builderResolver) { if (fieldType.hasEmptyConstructor()) { addExampleChainFragmentTemplate( methodDto, "#{methodName}(" + fieldType.getClassName() + "::new)"); } else { addExampleChainFragmentTemplate( - methodDto, "#{methodName}(() -> #{exampleValue})", fieldType, builderResolver); + methodDto, "#{methodName}(() -> #{exampleValue})", fieldType, fieldName, builderResolver); } } @@ -546,11 +604,32 @@ public static void addExampleChainFragmentTemplate( String template, TypeName fieldType, Function> builderResolver) { + addExampleChainFragmentTemplate(methodDto, template, fieldType, null, builderResolver); + } + + /** + * Adds the fluent-chain fragment for Javadoc examples to a method using a template string. + * + *

    Behaves like {@link #addExampleChainFragmentTemplate(BuilderMethodDto, String, TypeName, + * Function)}, but derives String example values from the given field name. + * + * @param methodDto the method DTO to add the fragment to + * @param template the template string with placeholders (e.g., {@code + * #{methodName}(#{exampleValue})}) + * @param fieldType the field type to get an example value for (can be {@code null}) + * @param fieldName the original field name used for String example values (may be {@code null}) + */ + public static void addExampleChainFragmentTemplate( + BuilderMethodDto methodDto, + String template, + TypeName fieldType, + String fieldName, + Function> builderResolver) { String fragment = template.replace("#{methodName}", methodDto.getMethodName()); if (fieldType != null) { Optional exampleValue = - JavadocExampleValues.getExampleValue(fieldType, builderResolver); + JavadocExampleValues.getExampleValue(fieldType, fieldName, builderResolver); if (exampleValue.isEmpty()) { return; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDto.java index d6daa246..cea81976 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/method/BuilderMethodDto.java @@ -91,7 +91,7 @@ public class BuilderMethodDto { /** * Fluent-chain fragment describing how this method is invoked in Javadoc examples (e.g., {@code - * .title("example value")}). When present, downstream enhancers use it to synthesise the + * .title("example title")}). When present, downstream enhancers use it to synthesise the * method-level example block (as {@code builder;}) and to aggregate the class-level * kitchen-sink chain. A {@code null} value means the method should not appear in either example. */ @@ -218,7 +218,7 @@ public MethodCodeDto getMethodCodeDto() { } /** - * Returns the fluent-chain fragment for Javadoc examples (e.g. {@code .title("example value")}) + * Returns the fluent-chain fragment for Javadoc examples (e.g. {@code .title("example title")}) * or {@code null} if this method should not participate in example generation. * * @return the fragment or {@code null} @@ -230,7 +230,7 @@ public String getExampleChainFragment() { /** * Stores the fluent-chain fragment describing how this method is invoked in examples. * - *

    The fragment contains just the method invocation, e.g. {@code title("example value")}. + *

    The fragment contains just the method invocation, e.g. {@code title("example title")}. * Downstream enhancers synthesise the method-level example block (as {@code builder.;}) * and the class-level kitchen-sink chain from it. * diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/AnnotationCopyTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/AnnotationCopyTest.java index 045ad200..1ecab1ba 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/AnnotationCopyTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/AnnotationCopyTest.java @@ -552,7 +552,7 @@ public static MyDtoBuilder create() { *

    Example:

    * *
    {@code
    -           * builder.name("example value");
    +           * builder.name("example name");
                * }
    * * @param name name @@ -574,7 +574,7 @@ public MyDtoBuilder name(String name) { *

    Example:

    * *
    {@code
    -           * builder.name("example value").nameUpdate(String::trim);
    +           * builder.name("example name").nameUpdate(String::trim);
                * }
    * * @param nameUpdater operator applied to the current value; its result becomes the new value diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderConfigurationReaderTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderConfigurationReaderTest.java index c093d3ec..1c862528 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderConfigurationReaderTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderConfigurationReaderTest.java @@ -487,8 +487,8 @@ public class PersonDto { * *
    {@code
             * PersonDto result = PersonDtoMinimalBuilder.create()
    -        *     .withName("example value")
    -        *     .withTags(List.of("example value"))
    +        *     .withName("example name")
    +        *     .withTags(List.of("example tags"))
             *     .build();
             * }
    */ @@ -542,7 +542,7 @@ public static PersonDtoMinimalBuilder create() { *

    Example:

    * *
    {@code
    -           * builder.withName("example value");
    +           * builder.withName("example name");
                * }
    * * @param name name @@ -561,7 +561,7 @@ public PersonDtoMinimalBuilder withName(String name) { *

    Example:

    * *
    {@code
    -           * builder.withTags(List.of("example value"));
    +           * builder.withTags(List.of("example tags"));
                * }
    * * @param tags tags diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java index c6488781..0785882e 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java @@ -102,15 +102,15 @@ void shouldGenerateClassJavadocExampleWithKitchenSinkChain() { * .pages(42) * .pages(() -> 42) * .pagesUpdate(Math::abs) - * .tags(List.of("example value")) - * .tags(() -> List.of("example value")) - * .tags(t -> t.add("example value")) - * .tags("example value", "example value") + * .tags(List.of("example tags")) + * .tags(() -> List.of("example tags")) + * .tags(t -> t.add("example tags")) + * .tags("example tags", "example tags") * .tagsUpdate(list -> list.stream().sorted().toList()) - * .add2Tags("example value") - * .title("example value") + * .add2Tags("example tags") + * .title("example title") * .title("Hello %s", "World") - * .title(() -> "example value") + * .title(() -> "example title") * .title(sb -> sb.append("text")) * .titleUpdate(String::trim) * .build(); @@ -147,7 +147,7 @@ private static Stream methodJavadocExampleCases() { *

    Example:

    * *
    {@code
    -            * builder.teamname("example value");
    +            * builder.teamname("example teamname");
                 * }
    * * @param teamname teamname @@ -189,7 +189,7 @@ public CounterBuilder amount(int amount) *

    Example:

    * *
    {@code
    -            * builder.title(() -> "example value");
    +            * builder.title(() -> "example title");
                 * }
    """), Arguments.of( @@ -207,7 +207,7 @@ public CounterBuilder amount(int amount) *

    Example:

    * *
    {@code
    -            * builder.add2Tags("example value");
    +            * builder.add2Tags("example tags");
                 * }
    * * @param element the element to add @@ -226,7 +226,7 @@ public TagsDtoBuilder add2Tags(String element) *

    Example:

    * *
    {@code
    -            * builder.tags(t -> t.add("example value"));
    +            * builder.tags(t -> t.add("example tags"));
                 * }
    """), Arguments.of( @@ -282,7 +282,7 @@ public TagsDtoBuilder add2Tags(String element) *

    Example:

    * *
    {@code
    -            * builder.values(Map.of(42, "example value"));
    +            * builder.values(Map.of(42, "example values"));
                 * }
    """), Arguments.of( @@ -296,7 +296,7 @@ public TagsDtoBuilder add2Tags(String element) *

    Example:

    * *
    {@code
    -            * builder.subtitle(Optional.of("example value"));
    +            * builder.subtitle(Optional.of("example subtitle"));
                 * }
    """)); } @@ -392,9 +392,9 @@ public class HelperPlain { public HelperPlain(String arg) {} } """ *
    {@code
             * MixedDto result = MixedDtoBuilder.create()
    -        *     .title("example value")
    +        *     .title("example title")
             *     .title("Hello %s", "World")
    -        *     .title(() -> "example value")
    +        *     .title(() -> "example title")
             *     .title(sb -> sb.append("text"))
             *     .titleUpdate(String::trim)
             *     .build();
    diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java
    index a055d489..4757ab40 100644
    --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java
    +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java
    @@ -114,34 +114,34 @@ void allFeatures_generatedCorrectly() {
              *
              * 
    {@code
              * PersonDto result = PersonDtoBuilder.create()
    -         *     .name("example value")
    +         *     .name("example name")
              *     .name("Hello %s", "World")
    -         *     .name(() -> "example value")
    +         *     .name(() -> "example name")
              *     .name(sb -> sb.append("text"))
              *     .nameUpdate(String::trim)
              *     .age(42)
              *     .age(() -> 42)
              *     .ageUpdate(Math::abs)
    -         *     .email(Optional.of("example value"))
    +         *     .email(Optional.of("example email"))
              *     .email("Hello %s", "World")
    -         *     .email("example value")
    -         *     .email(() -> Optional.of("example value"))
    +         *     .email("example email")
    +         *     .email(() -> Optional.of("example email"))
              *     .email(sb -> sb.append("text"))
    -         *     .nicknames(List.of("example value"))
    -         *     .nicknames(() -> List.of("example value"))
    -         *     .nicknames(t -> t.add("example value"))
    -         *     .nicknames("example value", "example value")
    +         *     .nicknames(List.of("example nicknames"))
    +         *     .nicknames(() -> List.of("example nicknames"))
    +         *     .nicknames(t -> t.add("example nicknames"))
    +         *     .nicknames("example nicknames", "example nicknames")
              *     .nicknamesUpdate(list -> list.stream().sorted().toList())
    -         *     .add2Nicknames("example value")
    -         *     .tags(Set.of("example value"))
    -         *     .tags(() -> Set.of("example value"))
    -         *     .tags(t -> t.add("example value"))
    -         *     .tags("example value", "example value")
    +         *     .add2Nicknames("example nicknames")
    +         *     .tags(Set.of("example tags"))
    +         *     .tags(() -> Set.of("example tags"))
    +         *     .tags(t -> t.add("example tags"))
    +         *     .tags("example tags", "example tags")
              *     .tagsUpdate(TreeSet::new)
    -         *     .add2Tags("example value")
    -         *     .metadata(Map.of("example value", "example value"))
    -         *     .metadata(() -> Map.of("example value", "example value"))
    -         *     .metadata(Map.entry("key", "example value"))
    +         *     .add2Tags("example tags")
    +         *     .metadata(Map.of("example value", "example metadata"))
    +         *     .metadata(() -> Map.of("example value", "example metadata"))
    +         *     .metadata(Map.entry("key", "example metadata"))
              *     .metadataUpdate(Map::copyOf)
              *     .address(AddressDtoBuilder.create().build())
              *     .address(() -> AddressDtoBuilder.create().build())
    @@ -152,12 +152,12 @@ void allFeatures_generatedCorrectly() {
              *     .previousAddresses(AddressDtoBuilder.create().build(), AddressDtoBuilder.create().build())
              *     .previousAddressesUpdate(list -> list.stream().sorted().toList())
              *     .add2PreviousAddresses(AddressDtoBuilder.create().build())
    -         *     .phoneNumbers(List.of("example value"))
    -         *     .phoneNumbers(() -> List.of("example value"))
    -         *     .phoneNumbers(t -> t.add("example value"))
    -         *     .phoneNumbers("example value", "example value")
    +         *     .phoneNumbers(List.of("example phoneNumbers"))
    +         *     .phoneNumbers(() -> List.of("example phoneNumbers"))
    +         *     .phoneNumbers(t -> t.add("example phoneNumbers"))
    +         *     .phoneNumbers("example phoneNumbers", "example phoneNumbers")
              *     .phoneNumbersUpdate(list -> new LinkedList<>(list.stream().sorted().toList()))
    -         *     .add2PhoneNumbers("example value")
    +         *     .add2PhoneNumbers("example phoneNumbers")
              *     .build();
              * }
    */ @@ -418,7 +418,7 @@ public PersonDtoBuilder ageUpdate(UnaryOperator ageUpdater) { *

    Example:

    * *
    {@code
    -           * builder.email("example value");
    +           * builder.email("example email");
                * }
    * * @param email email @@ -464,7 +464,7 @@ public PersonDtoBuilder email(Consumer emailStringBuilderConsumer *

    Example:

    * *
    {@code
    -           * builder.email(() -> Optional.of("example value"));
    +           * builder.email(() -> Optional.of("example email"));
                * }
    * * @param emailSupplier supplier for email @@ -510,7 +510,7 @@ public PersonDtoBuilder email(String format, Object... args) { *

    Example:

    * *
    {@code
    -           * builder.email(Optional.of("example value"));
    +           * builder.email(Optional.of("example email"));
                * }
    * * @param email email @@ -555,7 +555,7 @@ public PersonDtoBuilder emailUpdate(UnaryOperator> emailUpdater *

    Example:

    * *
    {@code
    -           * builder.metadata(Map.entry("key", "example value"));
    +           * builder.metadata(Map.entry("key", "example metadata"));
                * }
    * * @param metadata metadata @@ -597,7 +597,7 @@ public PersonDtoBuilder metadata(Consumer> metada *

    Example:

    * *
    {@code
    -           * builder.metadata(() -> Map.of("example value", "example value"));
    +           * builder.metadata(() -> Map.of("example value", "example metadata"));
                * }
    * * @param metadataSupplier supplier for metadata @@ -619,7 +619,7 @@ public PersonDtoBuilder metadata(Supplier> metadataSupplier) *

    Example:

    * *
    {@code
    -           * builder.metadata(Map.of("example value", "example value"));
    +           * builder.metadata(Map.of("example value", "example metadata"));
                * }
    * * @param metadata metadata @@ -644,7 +644,7 @@ public PersonDtoBuilder metadata(Map metadata) { *

    Example:

    * *
    {@code
    -           * builder.metadata(Map.of("example value", "example value")).metadataUpdate(Map::copyOf);
    +           * builder.metadata(Map.of("example value", "example metadata")).metadataUpdate(Map::copyOf);
                * }
    * * @param metadataUpdater operator applied to the current value; its result becomes the new value @@ -694,7 +694,7 @@ public PersonDtoBuilder name(Consumer nameStringBuilderConsumer) *

    Example:

    * *
    {@code
    -           * builder.name(() -> "example value");
    +           * builder.name(() -> "example name");
                * }
    * * @param nameSupplier supplier for name @@ -740,7 +740,7 @@ public PersonDtoBuilder name(String format, Object... args) { *

    Example:

    * *
    {@code
    -           * builder.name("example value");
    +           * builder.name("example name");
                * }
    * * @param name name @@ -765,7 +765,7 @@ public PersonDtoBuilder name(String name) { *

    Example:

    * *
    {@code
    -           * builder.name("example value").nameUpdate(String::trim);
    +           * builder.name("example name").nameUpdate(String::trim);
                * }
    * * @param nameUpdater operator applied to the current value; its result becomes the new value @@ -791,7 +791,7 @@ public PersonDtoBuilder nameUpdate(UnaryOperator nameUpdater) { *

    Example:

    * *
    {@code
    -           * builder.add2Nicknames("example value");
    +           * builder.add2Nicknames("example nicknames");
                * }
    * * @param element the element to add @@ -820,7 +820,7 @@ public PersonDtoBuilder add2Nicknames(String element) { *

    Example:

    * *
    {@code
    -           * builder.nicknames("example value", "example value");
    +           * builder.nicknames("example nicknames", "example nicknames");
                * }
    * * @param nicknames nicknames @@ -842,7 +842,7 @@ public PersonDtoBuilder nicknames(String... nicknames) { *

    Example:

    * *
    {@code
    -           * builder.nicknames(t -> t.add("example value"));
    +           * builder.nicknames(t -> t.add("example nicknames"));
                * }
    * * @param nicknamesBuilderConsumer consumer providing an instance of a builder for nicknames @@ -868,7 +868,7 @@ public PersonDtoBuilder nicknames(Consumer> nicknamesBu *

    Example:

    * *
    {@code
    -           * builder.nicknames(() -> List.of("example value"));
    +           * builder.nicknames(() -> List.of("example nicknames"));
                * }
    * * @param nicknamesSupplier supplier for nicknames @@ -890,7 +890,7 @@ public PersonDtoBuilder nicknames(Supplier> nicknamesSupplier) { *

    Example:

    * *
    {@code
    -           * builder.nicknames(List.of("example value"));
    +           * builder.nicknames(List.of("example nicknames"));
                * }
    * * @param nicknames nicknames @@ -915,7 +915,7 @@ public PersonDtoBuilder nicknames(List nicknames) { *

    Example:

    * *
    {@code
    -           * builder.nicknames(List.of("example value")).nicknamesUpdate(list -> list.stream().sorted().toList());
    +           * builder.nicknames(List.of("example nicknames")).nicknamesUpdate(list -> list.stream().sorted().toList());
                * }
    * * @param nicknamesUpdater operator applied to the current value; its result becomes the new value @@ -941,7 +941,7 @@ public PersonDtoBuilder nicknamesUpdate(UnaryOperator> nicknamesUpd *

    Example:

    * *
    {@code
    -           * builder.add2PhoneNumbers("example value");
    +           * builder.add2PhoneNumbers("example phoneNumbers");
                * }
    * * @param element the element to add @@ -970,7 +970,7 @@ public PersonDtoBuilder add2PhoneNumbers(String element) { *

    Example:

    * *
    {@code
    -           * builder.phoneNumbers("example value", "example value");
    +           * builder.phoneNumbers("example phoneNumbers", "example phoneNumbers");
                * }
    * * @param phoneNumbers phoneNumbers @@ -992,7 +992,7 @@ public PersonDtoBuilder phoneNumbers(String... phoneNumbers) { *

    Example:

    * *
    {@code
    -           * builder.phoneNumbers(t -> t.add("example value"));
    +           * builder.phoneNumbers(t -> t.add("example phoneNumbers"));
                * }
    * * @param phoneNumbersBuilderConsumer consumer providing an instance of a builder for phoneNumbers @@ -1018,7 +1018,7 @@ public PersonDtoBuilder phoneNumbers(Consumer> phoneNum *

    Example:

    * *
    {@code
    -           * builder.phoneNumbers(() -> List.of("example value"));
    +           * builder.phoneNumbers(() -> List.of("example phoneNumbers"));
                * }
    * * @param phoneNumbersSupplier supplier for phoneNumbers @@ -1040,7 +1040,7 @@ public PersonDtoBuilder phoneNumbers(Supplier> phoneNumbersSu *

    Example:

    * *
    {@code
    -           * builder.phoneNumbers(List.of("example value"));
    +           * builder.phoneNumbers(List.of("example phoneNumbers"));
                * }
    * * @param phoneNumbers phoneNumbers @@ -1065,7 +1065,7 @@ public PersonDtoBuilder phoneNumbers(LinkedList phoneNumbers) { *

    Example:

    * *
    {@code
    -           * builder.phoneNumbers(List.of("example value"))
    +           * builder.phoneNumbers(List.of("example phoneNumbers"))
                *     .phoneNumbersUpdate(list -> new LinkedList<>(list.stream().sorted().toList()));
                * }
    * @@ -1246,7 +1246,7 @@ public PersonDtoBuilder previousAddressesUpdate(UnaryOperator> *

    Example:

    * *
    {@code
    -           * builder.add2Tags("example value");
    +           * builder.add2Tags("example tags");
                * }
    * * @param element the element to add @@ -1275,7 +1275,7 @@ public PersonDtoBuilder add2Tags(String element) { *

    Example:

    * *
    {@code
    -           * builder.tags("example value", "example value");
    +           * builder.tags("example tags", "example tags");
                * }
    * * @param tags tags @@ -1297,7 +1297,7 @@ public PersonDtoBuilder tags(String... tags) { *

    Example:

    * *
    {@code
    -           * builder.tags(t -> t.add("example value"));
    +           * builder.tags(t -> t.add("example tags"));
                * }
    * * @param tagsBuilderConsumer consumer providing an instance of a builder for tags @@ -1323,7 +1323,7 @@ public PersonDtoBuilder tags(Consumer> tagsBuilderConsume *

    Example:

    * *
    {@code
    -           * builder.tags(() -> Set.of("example value"));
    +           * builder.tags(() -> Set.of("example tags"));
                * }
    * * @param tagsSupplier supplier for tags @@ -1345,7 +1345,7 @@ public PersonDtoBuilder tags(Supplier> tagsSupplier) { *

    Example:

    * *
    {@code
    -           * builder.tags(Set.of("example value"));
    +           * builder.tags(Set.of("example tags"));
                * }
    * * @param tags tags @@ -1370,7 +1370,7 @@ public PersonDtoBuilder tags(Set tags) { *

    Example:

    * *
    {@code
    -           * builder.tags(Set.of("example value")).tagsUpdate(TreeSet::new);
    +           * builder.tags(Set.of("example tags")).tagsUpdate(TreeSet::new);
                * }
    * * @param tagsUpdater operator applied to the current value; its result becomes the new value diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/FormattingModeTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/FormattingModeTest.java index beb42e36..b44f08c0 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/FormattingModeTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/FormattingModeTest.java @@ -122,9 +122,9 @@ public int getCount() { * *

    Example:

    {@code
              * FormatTestDto result = FormatTestDtoBuilder.create()
    -         *     .name("example value")
    +         *     .name("example name")
              *     .name("Hello %s", "World")
    -         *     .name(() -> "example value")
    +         *     .name(() -> "example name")
              *     .name(sb -> sb.append("text"))
              *     .nameUpdate(String::trim)
              *     .count(42)
    @@ -246,7 +246,7 @@ public FormatTestDtoBuilder name(Consumer nameStringBuilderConsum
                * 

    Generated from parameter in constructor {@link FormatTestDto#FormatTestDto(String, int) FormatTestDto(String name, int count)} * *

    Example:

    {@code
    -           * builder.name(() -> "example value");
    +           * builder.name(() -> "example name");
                * }
    * @param nameSupplier supplier for name * @return current instance of builder @@ -278,7 +278,7 @@ public FormatTestDtoBuilder name(String format, Object... args) { *

    Generated from parameter in constructor {@link FormatTestDto#FormatTestDto(String, int) FormatTestDto(String name, int count)} * *

    Example:

    {@code
    -           * builder.name("example value");
    +           * builder.name("example name");
                * }
    * @param name name * @return current instance of builder @@ -295,7 +295,7 @@ public FormatTestDtoBuilder name(String name) { *

    Generated from parameter in constructor {@link FormatTestDto#FormatTestDto(String, int) FormatTestDto(String name, int count)} * *

    Example:

    {@code
    -           * builder.name("example value").nameUpdate(String::trim);
    +           * builder.name("example name").nameUpdate(String::trim);
                * }
    * @param nameUpdater operator applied to the current value; its result becomes the new value * @return current instance of builder diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/UpdateHelperGeneratorTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/UpdateHelperGeneratorTest.java index c35909d7..e63000e9 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/UpdateHelperGeneratorTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/UpdateHelperGeneratorTest.java @@ -61,7 +61,7 @@ void updateHelpers_DefaultEnabled_GeneratesMethodsWithSignaturesGuardAndExamples // Method-level Javadoc examples initialize the field, then update it ProcessorAsserts.assertContaining( - generated, "builder.name(\"example value\").nameUpdate(String::trim);"); + generated, "builder.name(\"example name\").nameUpdate(String::trim);"); ProcessorAsserts.assertContaining(generated, "builder.quantity(42).quantityUpdate(Math::abs);"); // Class-level example chain contains the updater as a separate fragment line @@ -267,9 +267,9 @@ public HelperPlain(String arg) {} ProcessorAsserts.assertContaining(generated, "builder.flag(true).flagUpdate(value -> !value);"); ProcessorAsserts.assertContaining( generated, - "builder.tags(List.of(\"example value\")).tagsUpdate(list -> list.stream().sorted().toList());"); + "builder.tags(List.of(\"example tags\")).tagsUpdate(list -> list.stream().sorted().toList());"); ProcessorAsserts.assertContaining( - generated, "builder.title(\"example value\").titleUpdate(String::trim);"); + generated, "builder.title(\"example title\").titleUpdate(String::trim);"); // No artificial identity fallback anywhere ProcessorAsserts.assertNotContaining(generated, "UnaryOperator.identity()"); From 112fa4a09766638ebe6159f21fda3191df5c9ba3 Mon Sep 17 00:00:00 2001 From: Andreas Igel Date: Wed, 18 Nov 2026 12:13:05 +0100 Subject: [PATCH 03/15] feat: generate fluent builders for codegen model DTOs (#415) --- codegen-core/pom.xml | 9 +- .../annotation/AnnotationDtoBuilder.java | 232 ++++++ .../model/core/ClassFieldDtoBuilder.java | 643 ++++++++++++++++ .../core/GenerationTargetClassDtoBuilder.java | 522 +++++++++++++ .../javadoc/JavadocCodeBlockDtoBuilder.java | 306 ++++++++ .../model/javadoc/JavadocDtoBuilder.java | 499 ++++++++++++ .../model/method/CodeTemplateDtoBuilder.java | 305 ++++++++ .../model/method/ConstructorDtoBuilder.java | 438 +++++++++++ .../model/method/MethodCodeDtoBuilder.java | 304 ++++++++ .../model/method/MethodDtoBuilder.java | 711 ++++++++++++++++++ .../method/MethodParameterDtoBuilder.java | 365 +++++++++ .../type/GenericParameterDtoBuilder.java | 300 ++++++++ .../model/type/NestedTypeDtoBuilder.java | 513 +++++++++++++ .../GenerationTargetClassDtoBuilderTest.java | 112 +++ .../codegen/util/ImportCollectorTest.java | 27 +- .../RoasterCodeGeneratorResilienceTest.java | 51 +- .../roaster/RoasterCodeGeneratorTest.java | 246 +++--- .../codegen/roaster/RoasterMapperTest.java | 54 +- .../MinimalCodegenProcessorTest.java | 53 +- 19 files changed, 5524 insertions(+), 166 deletions(-) create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index 910bba1c..f5389e8e 100644 --- a/codegen-core/pom.xml +++ b/codegen-core/pom.xml @@ -101,7 +101,14 @@ commons-collections4 ${commons-collections.version} - + + + io.github.java-helpers + simple-builders-core + ${project.version} + + org.junit.jupiter diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java new file mode 100644 index 00000000..8d6fde37 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java @@ -0,0 +1,232 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.annotation; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.annotation.AnnotationDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.annotation.AnnotationDto with method chaining and validation. Use + * the static {@code create()} method to obtain a new builder instance, configure the desired + * properties using the setter methods, and then call {@code build()} to create the final DTO. + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class AnnotationDtoBuilder { + + /** Tracked value for annotationType: the type of the annotation. */ + private TrackedValue annotationType = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.codegen.model.annotation.AnnotationDto}. + */ + public AnnotationDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.annotation.AnnotationDto} by + * a instance. + * + * @param instance object instance for initialisiation + */ + public AnnotationDtoBuilder(AnnotationDto instance) { + this.annotationType = initialValue(instance.getAnnotationType()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.annotation.AnnotationDto}. + * + *

    Example:

    + * + *
    {@code
    +   * AnnotationDtoBuilder builder = AnnotationDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.annotation.AnnotationDto} + */ + public static AnnotationDtoBuilder create() { + return new AnnotationDtoBuilder(); + } + + /** + * Sets the value for annotationType by invoking the provided supplier. + * + *

    Generated from setter {@link AnnotationDto#setAnnotationType(TypeName) + * setAnnotationType(TypeName annotationType)} + * + * @param annotationTypeSupplier supplier for the type of the annotation + * @return current instance of builder + */ + public AnnotationDtoBuilder annotationType(Supplier annotationTypeSupplier) { + this.annotationType = changedValue(annotationTypeSupplier.get()); + return this; + } + + /** + * Sets the value for annotationType. + * + *

    Generated from setter {@link AnnotationDto#setAnnotationType(TypeName) + * setAnnotationType(TypeName annotationType)} + * + * @param annotationType the type of the annotation + * @return current instance of builder + */ + public AnnotationDtoBuilder annotationType(TypeName annotationType) { + this.annotationType = changedValue(annotationType); + return this; + } + + /** + * Updates the current value of annotationType in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link AnnotationDto#setAnnotationType(TypeName) + * setAnnotationType(TypeName annotationType)} + * + * @param annotationTypeUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if annotationType has not been set yet + */ + public AnnotationDtoBuilder annotationTypeUpdate(UnaryOperator annotationTypeUpdater) { + if (!this.annotationType.isSet()) { + throw new IllegalStateException("Cannot update 'annotationType' before it is set"); + } + this.annotationType = changedValue(annotationTypeUpdater.apply(this.annotationType.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public AnnotationDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public AnnotationDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * AnnotationDto result = builder.build();
    +   * }
    + */ + public AnnotationDto build() { + AnnotationDto result = new AnnotationDto(); + this.annotationType.ifSet(result::setAnnotationType); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("annotationType", this.annotationType) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default AnnotationDto with(Consumer b) { + AnnotationDtoBuilder builder; + try { + builder = new AnnotationDtoBuilder(AnnotationDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'AnnotationDtoBuilder.With' should only be implemented by classes, which could be casted to 'AnnotationDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default AnnotationDtoBuilder with() { + try { + return new AnnotationDtoBuilder(AnnotationDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'AnnotationDtoBuilder.With' should only be implemented by classes, which could be casted to 'AnnotationDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java new file mode 100644 index 00000000..794f5030 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java @@ -0,0 +1,643 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.core; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.core.ClassFieldDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.core.ClassFieldDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * ClassFieldDto result = ClassFieldDtoBuilder.create()
    + *     .fieldName("example value")
    + *     .fieldName("Hello %s", "World")
    + *     .fieldName(() -> "example value")
    + *     .fieldName(sb -> sb.append("text"))
    + *     .fieldNameUpdate(String::trim)
    + *     .javadoc(new JavadocDto())
    + *     .javadoc(JavadocDto::new)
    + *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
    + *     .literalInitializer("example value")
    + *     .literalInitializer("Hello %s", "World")
    + *     .literalInitializer(() -> "example value")
    + *     .literalInitializer(sb -> sb.append("text"))
    + *     .literalInitializerUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class ClassFieldDtoBuilder { + + /** Tracked value for fieldName: fieldName. */ + private TrackedValue fieldName = unsetValue(); + + /** Tracked value for fieldType: fieldType. */ + private TrackedValue fieldType = unsetValue(); + + /** Tracked value for javadoc: javadoc. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for literalInitializer: literalInitializer. */ + private TrackedValue literalInitializer = unsetValue(); + + /** Tracked value for visibility: visibility. */ + private TrackedValue visibility = unsetValue(); + + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.core.ClassFieldDto}. */ + public ClassFieldDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.core.ClassFieldDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public ClassFieldDtoBuilder(ClassFieldDto instance) { + this.fieldName = initialValue(instance.getFieldName()); + this.fieldType = initialValue(instance.getFieldType()); + this.javadoc = initialValue(instance.getJavadoc()); + this.literalInitializer = initialValue(instance.getLiteralInitializer()); + this.visibility = initialValue(instance.getVisibility()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.core.ClassFieldDto}. + * + *

    Example:

    + * + *
    {@code
    +   * ClassFieldDtoBuilder builder = ClassFieldDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.core.ClassFieldDto} + */ + public static ClassFieldDtoBuilder create() { + return new ClassFieldDtoBuilder(); + } + + /** + * Sets the value for fieldName by executing the provided consumer. + * + *

    Generated from setter {@link ClassFieldDto#setFieldName(String) setFieldName(String + * fieldName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.fieldName(sb -> sb.append("text"));
    +   * }
    + * + * @param fieldNameStringBuilderConsumer consumer providing an instance of fieldName + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldName(Consumer fieldNameStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + fieldNameStringBuilderConsumer.accept(builder); + this.fieldName = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for fieldName by invoking the provided supplier. + * + *

    Generated from setter {@link ClassFieldDto#setFieldName(String) setFieldName(String + * fieldName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.fieldName(() -> "example value");
    +   * }
    + * + * @param fieldNameSupplier supplier for fieldName + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldName(Supplier fieldNameSupplier) { + this.fieldName = changedValue(fieldNameSupplier.get()); + return this; + } + + /** + * Sets the String value for fieldName by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link ClassFieldDto#setFieldName(String) setFieldName(String + * fieldName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.fieldName("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldName(String format, Object... args) { + this.fieldName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for fieldName. + * + *

    Generated from setter {@link ClassFieldDto#setFieldName(String) setFieldName(String + * fieldName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.fieldName("example value");
    +   * }
    + * + * @param fieldName fieldName + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldName(String fieldName) { + this.fieldName = changedValue(fieldName); + return this; + } + + /** + * Updates the current value of fieldName in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link ClassFieldDto#setFieldName(String) setFieldName(String + * fieldName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.fieldName("example value").fieldNameUpdate(String::trim);
    +   * }
    + * + * @param fieldNameUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if fieldName has not been set yet + */ + public ClassFieldDtoBuilder fieldNameUpdate(UnaryOperator fieldNameUpdater) { + if (!this.fieldName.isSet()) { + throw new IllegalStateException("Cannot update 'fieldName' before it is set"); + } + this.fieldName = changedValue(fieldNameUpdater.apply(this.fieldName.value())); + return this; + } + + /** + * Sets the value for fieldType by invoking the provided supplier. + * + *

    Generated from setter {@link ClassFieldDto#setFieldType(TypeName) setFieldType(TypeName + * fieldType)} + * + * @param fieldTypeSupplier supplier for fieldType + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldType(Supplier fieldTypeSupplier) { + this.fieldType = changedValue(fieldTypeSupplier.get()); + return this; + } + + /** + * Sets the value for fieldType. + * + *

    Generated from setter {@link ClassFieldDto#setFieldType(TypeName) setFieldType(TypeName + * fieldType)} + * + * @param fieldType fieldType + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldType(TypeName fieldType) { + this.fieldType = changedValue(fieldType); + return this; + } + + /** + * Updates the current value of fieldType in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link ClassFieldDto#setFieldType(TypeName) setFieldType(TypeName + * fieldType)} + * + * @param fieldTypeUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if fieldType has not been set yet + */ + public ClassFieldDtoBuilder fieldTypeUpdate(UnaryOperator fieldTypeUpdater) { + if (!this.fieldType.isSet()) { + throw new IllegalStateException("Cannot update 'fieldType' before it is set"); + } + this.fieldType = changedValue(fieldTypeUpdater.apply(this.fieldType.value())); + return this; + } + + /** + * Sets the value for javadoc using a builder consumer that produces the value. + * + *

    Generated from setter {@link ClassFieldDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(javadocDtoBuilder -> javadocDtoBuilder);
    +   * }
    + * + * @param javadocBuilderConsumer consumer providing an instance of a builder for javadoc + * @return current instance of builder + */ + public ClassFieldDtoBuilder javadoc(Consumer javadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.javadoc.isSet() + ? new JavadocDtoBuilder(this.javadoc.value()) + : JavadocDtoBuilder.create(); + javadocBuilderConsumer.accept(builder); + this.javadoc = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for javadoc by invoking the provided supplier. + * + *

    Generated from setter {@link ClassFieldDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(JavadocDto::new);
    +   * }
    + * + * @param javadocSupplier supplier for javadoc + * @return current instance of builder + */ + public ClassFieldDtoBuilder javadoc(Supplier javadocSupplier) { + this.javadoc = changedValue(javadocSupplier.get()); + return this; + } + + /** + * Sets the value for javadoc. + * + *

    Generated from setter {@link ClassFieldDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(new JavadocDto());
    +   * }
    + * + * @param javadoc javadoc + * @return current instance of builder + */ + public ClassFieldDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Updates the current value of javadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #javadoc(Consumer)}. + * + *

    Generated from setter {@link ClassFieldDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + * @param javadocUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if javadoc has not been set yet + */ + public ClassFieldDtoBuilder javadocUpdate(UnaryOperator javadocUpdater) { + if (!this.javadoc.isSet()) { + throw new IllegalStateException("Cannot update 'javadoc' before it is set"); + } + this.javadoc = changedValue(javadocUpdater.apply(this.javadoc.value())); + return this; + } + + /** + * Sets the value for literalInitializer by executing the provided consumer. + * + *

    Generated from setter {@link ClassFieldDto#setLiteralInitializer(String) + * setLiteralInitializer(String literalInitializer)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.literalInitializer(sb -> sb.append("text"));
    +   * }
    + * + * @param literalInitializerStringBuilderConsumer consumer providing an instance of + * literalInitializer + * @return current instance of builder + */ + public ClassFieldDtoBuilder literalInitializer( + Consumer literalInitializerStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + literalInitializerStringBuilderConsumer.accept(builder); + this.literalInitializer = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for literalInitializer by invoking the provided supplier. + * + *

    Generated from setter {@link ClassFieldDto#setLiteralInitializer(String) + * setLiteralInitializer(String literalInitializer)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.literalInitializer(() -> "example value");
    +   * }
    + * + * @param literalInitializerSupplier supplier for literalInitializer + * @return current instance of builder + */ + public ClassFieldDtoBuilder literalInitializer(Supplier literalInitializerSupplier) { + this.literalInitializer = changedValue(literalInitializerSupplier.get()); + return this; + } + + /** + * Sets the String value for literalInitializer by using String.format(format, args). + * See {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link ClassFieldDto#setLiteralInitializer(String) + * setLiteralInitializer(String literalInitializer)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.literalInitializer("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public ClassFieldDtoBuilder literalInitializer(String format, Object... args) { + this.literalInitializer = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for literalInitializer. + * + *

    Generated from setter {@link ClassFieldDto#setLiteralInitializer(String) + * setLiteralInitializer(String literalInitializer)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.literalInitializer("example value");
    +   * }
    + * + * @param literalInitializer literalInitializer + * @return current instance of builder + */ + public ClassFieldDtoBuilder literalInitializer(String literalInitializer) { + this.literalInitializer = changedValue(literalInitializer); + return this; + } + + /** + * Updates the current value of literalInitializer in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link ClassFieldDto#setLiteralInitializer(String) + * setLiteralInitializer(String literalInitializer)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.literalInitializer("example value").literalInitializerUpdate(String::trim);
    +   * }
    + * + * @param literalInitializerUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if literalInitializer has not been set yet + */ + public ClassFieldDtoBuilder literalInitializerUpdate( + UnaryOperator literalInitializerUpdater) { + if (!this.literalInitializer.isSet()) { + throw new IllegalStateException("Cannot update 'literalInitializer' before it is set"); + } + this.literalInitializer = + changedValue(literalInitializerUpdater.apply(this.literalInitializer.value())); + return this; + } + + /** + * Sets the value for visibility by invoking the provided supplier. + * + *

    Generated from setter {@link ClassFieldDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilitySupplier supplier for visibility + * @return current instance of builder + */ + public ClassFieldDtoBuilder visibility(Supplier visibilitySupplier) { + this.visibility = changedValue(visibilitySupplier.get()); + return this; + } + + /** + * Sets the value for visibility. + * + *

    Generated from setter {@link ClassFieldDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibility visibility + * @return current instance of builder + */ + public ClassFieldDtoBuilder visibility(AccessModifier visibility) { + this.visibility = changedValue(visibility); + return this; + } + + /** + * Updates the current value of visibility in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link ClassFieldDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilityUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if visibility has not been set yet + */ + public ClassFieldDtoBuilder visibilityUpdate(UnaryOperator visibilityUpdater) { + if (!this.visibility.isSet()) { + throw new IllegalStateException("Cannot update 'visibility' before it is set"); + } + this.visibility = changedValue(visibilityUpdater.apply(this.visibility.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public ClassFieldDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public ClassFieldDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * ClassFieldDto result = builder.build();
    +   * }
    + */ + public ClassFieldDto build() { + ClassFieldDto result = new ClassFieldDto(); + this.fieldName.ifSet(result::setFieldName); + this.fieldType.ifSet(result::setFieldType); + this.javadoc.ifSet(result::setJavadoc); + this.literalInitializer.ifSet(result::setLiteralInitializer); + this.visibility.ifSet(result::setVisibility); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("fieldName", this.fieldName) + .append("fieldType", this.fieldType) + .append("javadoc", this.javadoc) + .append("literalInitializer", this.literalInitializer) + .append("visibility", this.visibility) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default ClassFieldDto with(Consumer b) { + ClassFieldDtoBuilder builder; + try { + builder = new ClassFieldDtoBuilder(ClassFieldDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'ClassFieldDtoBuilder.With' should only be implemented by classes, which could be casted to 'ClassFieldDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default ClassFieldDtoBuilder with() { + try { + return new ClassFieldDtoBuilder(ClassFieldDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'ClassFieldDtoBuilder.With' should only be implemented by classes, which could be casted to 'ClassFieldDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java new file mode 100644 index 00000000..e2700bea --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java @@ -0,0 +1,522 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.core; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.core.GenerationTargetClassDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.core.GenerationTargetClassDto with method chaining and validation. + * Use the static {@code create()} method to obtain a new builder instance, configure the desired + * properties using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * GenerationTargetClassDto result = GenerationTargetClassDtoBuilder.create()
    + *     .classJavadoc(new JavadocDto())
    + *     .classJavadoc(JavadocDto::new)
    + *     .classJavadoc(javadocDtoBuilder -> javadocDtoBuilder)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class GenerationTargetClassDtoBuilder { + + /** Tracked value for classAccessModifier: classAccessModifier. */ + private TrackedValue classAccessModifier = unsetValue(); + + /** Tracked value for classJavadoc: the class JavaDoc to set. */ + private TrackedValue classJavadoc = unsetValue(); + + /** + * Tracked value for formattingMode: the formatting mode, or null to use the global + * default. + */ + private TrackedValue formattingMode = unsetValue(); + + /** Tracked value for superType: superType. */ + private TrackedValue superType = unsetValue(); + + /** Tracked value for typeName: typeName. */ + private TrackedValue typeName = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.codegen.model.core.GenerationTargetClassDto}. + */ + public GenerationTargetClassDtoBuilder() {} + + /** + * Initialisation of builder for {@code + * org.javahelpers.codegen.model.core.GenerationTargetClassDto} by a instance. + * + * @param instance object instance for initialisiation + */ + public GenerationTargetClassDtoBuilder(GenerationTargetClassDto instance) { + this.classAccessModifier = initialValue(instance.getClassAccessModifier()); + this.classJavadoc = initialValue(instance.getClassJavadoc()); + this.formattingMode = initialValue(instance.getFormattingMode()); + this.superType = initialValue(instance.getSuperType()); + this.typeName = initialValue(instance.getTypeName()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.core.GenerationTargetClassDto}. + * + *

    Example:

    + * + *
    {@code
    +   * GenerationTargetClassDtoBuilder builder = GenerationTargetClassDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.core.GenerationTargetClassDto} + */ + public static GenerationTargetClassDtoBuilder create() { + return new GenerationTargetClassDtoBuilder(); + } + + /** + * Sets the value for classAccessModifier by invoking the provided supplier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassAccessModifier(AccessModifier) + * setClassAccessModifier(AccessModifier classAccessModifier)} + * + * @param classAccessModifierSupplier supplier for classAccessModifier + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classAccessModifier( + Supplier classAccessModifierSupplier) { + this.classAccessModifier = changedValue(classAccessModifierSupplier.get()); + return this; + } + + /** + * Sets the value for classAccessModifier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassAccessModifier(AccessModifier) + * setClassAccessModifier(AccessModifier classAccessModifier)} + * + * @param classAccessModifier classAccessModifier + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classAccessModifier(AccessModifier classAccessModifier) { + this.classAccessModifier = changedValue(classAccessModifier); + return this; + } + + /** + * Updates the current value of classAccessModifier in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassAccessModifier(AccessModifier) + * setClassAccessModifier(AccessModifier classAccessModifier)} + * + * @param classAccessModifierUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if classAccessModifier has not been set yet + */ + public GenerationTargetClassDtoBuilder classAccessModifierUpdate( + UnaryOperator classAccessModifierUpdater) { + if (!this.classAccessModifier.isSet()) { + throw new IllegalStateException("Cannot update 'classAccessModifier' before it is set"); + } + this.classAccessModifier = + changedValue(classAccessModifierUpdater.apply(this.classAccessModifier.value())); + return this; + } + + /** + * Sets the value for classJavadoc using a builder consumer that produces the value. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.classJavadoc(javadocDtoBuilder -> javadocDtoBuilder);
    +   * }
    + * + * @param classJavadocBuilderConsumer consumer providing an instance of a builder for the class + * JavaDoc to set + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classJavadoc( + Consumer classJavadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.classJavadoc.isSet() + ? new JavadocDtoBuilder(this.classJavadoc.value()) + : JavadocDtoBuilder.create(); + classJavadocBuilderConsumer.accept(builder); + this.classJavadoc = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for classJavadoc by invoking the provided supplier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.classJavadoc(JavadocDto::new);
    +   * }
    + * + * @param classJavadocSupplier supplier for the class JavaDoc to set + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classJavadoc(Supplier classJavadocSupplier) { + this.classJavadoc = changedValue(classJavadocSupplier.get()); + return this; + } + + /** + * Sets the value for classJavadoc. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.classJavadoc(new JavadocDto());
    +   * }
    + * + * @param classJavadoc the class JavaDoc to set + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classJavadoc(JavadocDto classJavadoc) { + this.classJavadoc = changedValue(classJavadoc); + return this; + } + + /** + * Updates the current value of classJavadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #classJavadoc(Consumer)}. + * + *

    Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + * @param classJavadocUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if classJavadoc has not been set yet + */ + public GenerationTargetClassDtoBuilder classJavadocUpdate( + UnaryOperator classJavadocUpdater) { + if (!this.classJavadoc.isSet()) { + throw new IllegalStateException("Cannot update 'classJavadoc' before it is set"); + } + this.classJavadoc = changedValue(classJavadocUpdater.apply(this.classJavadoc.value())); + return this; + } + + /** + * Sets the value for formattingMode by invoking the provided supplier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingModeSupplier supplier for the formatting mode, or null to use the global + * default + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder formattingMode( + Supplier formattingModeSupplier) { + this.formattingMode = changedValue(formattingModeSupplier.get()); + return this; + } + + /** + * Sets the value for formattingMode. + * + *

    Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingMode the formatting mode, or null to use the global default + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder formattingMode(FormattingMode formattingMode) { + this.formattingMode = changedValue(formattingMode); + return this; + } + + /** + * Updates the current value of formattingMode in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingModeUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if formattingMode has not been set yet + */ + public GenerationTargetClassDtoBuilder formattingModeUpdate( + UnaryOperator formattingModeUpdater) { + if (!this.formattingMode.isSet()) { + throw new IllegalStateException("Cannot update 'formattingMode' before it is set"); + } + this.formattingMode = changedValue(formattingModeUpdater.apply(this.formattingMode.value())); + return this; + } + + /** + * Sets the value for superType by invoking the provided supplier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superTypeSupplier supplier for superType + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder superType(Supplier superTypeSupplier) { + this.superType = changedValue(superTypeSupplier.get()); + return this; + } + + /** + * Sets the value for superType. + * + *

    Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superType superType + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder superType(TypeName superType) { + this.superType = changedValue(superType); + return this; + } + + /** + * Updates the current value of superType in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superTypeUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if superType has not been set yet + */ + public GenerationTargetClassDtoBuilder superTypeUpdate(UnaryOperator superTypeUpdater) { + if (!this.superType.isSet()) { + throw new IllegalStateException("Cannot update 'superType' before it is set"); + } + this.superType = changedValue(superTypeUpdater.apply(this.superType.value())); + return this; + } + + /** + * Sets the value for typeName by invoking the provided supplier. + * + *

    Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeNameSupplier supplier for typeName + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder typeName(Supplier typeNameSupplier) { + this.typeName = changedValue(typeNameSupplier.get()); + return this; + } + + /** + * Sets the value for typeName. + * + *

    Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeName typeName + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder typeName(TypeName typeName) { + this.typeName = changedValue(typeName); + return this; + } + + /** + * Updates the current value of typeName in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeNameUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if typeName has not been set yet + */ + public GenerationTargetClassDtoBuilder typeNameUpdate(UnaryOperator typeNameUpdater) { + if (!this.typeName.isSet()) { + throw new IllegalStateException("Cannot update 'typeName' before it is set"); + } + this.typeName = changedValue(typeNameUpdater.apply(this.typeName.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public GenerationTargetClassDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public GenerationTargetClassDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * GenerationTargetClassDto result = builder.build();
    +   * }
    + */ + public GenerationTargetClassDto build() { + GenerationTargetClassDto result = new GenerationTargetClassDto(); + this.classAccessModifier.ifSet(result::setClassAccessModifier); + this.classJavadoc.ifSet(result::setClassJavadoc); + this.formattingMode.ifSet(result::setFormattingMode); + this.superType.ifSet(result::setSuperType); + this.typeName.ifSet(result::setTypeName); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("classAccessModifier", this.classAccessModifier) + .append("classJavadoc", this.classJavadoc) + .append("formattingMode", this.formattingMode) + .append("superType", this.superType) + .append("typeName", this.typeName) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default GenerationTargetClassDto with(Consumer b) { + GenerationTargetClassDtoBuilder builder; + try { + builder = new GenerationTargetClassDtoBuilder(GenerationTargetClassDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GenerationTargetClassDtoBuilder.With' should only be implemented by classes, which could be casted to 'GenerationTargetClassDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default GenerationTargetClassDtoBuilder with() { + try { + return new GenerationTargetClassDtoBuilder(GenerationTargetClassDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GenerationTargetClassDtoBuilder.With' should only be implemented by classes, which could be casted to 'GenerationTargetClassDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java new file mode 100644 index 00000000..26df3c15 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java @@ -0,0 +1,306 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.javadoc; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto with method chaining and validation. + * Use the static {@code create()} method to obtain a new builder instance, configure the desired + * properties using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * JavadocCodeBlockDto result = JavadocCodeBlockDtoBuilder.create()
    + *     .codeFormat("example value")
    + *     .codeFormat("Hello %s", "World")
    + *     .codeFormat(() -> "example value")
    + *     .codeFormat(sb -> sb.append("text"))
    + *     .codeFormatUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class JavadocCodeBlockDtoBuilder { + + /** Tracked value for codeFormat: Codeformat. */ + private TrackedValue codeFormat = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto}. + */ + public JavadocCodeBlockDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto} + * by a instance. + * + * @param instance object instance for initialisiation + */ + public JavadocCodeBlockDtoBuilder(JavadocCodeBlockDto instance) { + this.codeFormat = initialValue(instance.getCodeFormat()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto}. + * + *

    Example:

    + * + *
    {@code
    +   * JavadocCodeBlockDtoBuilder builder = JavadocCodeBlockDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto} + */ + public static JavadocCodeBlockDtoBuilder create() { + return new JavadocCodeBlockDtoBuilder(); + } + + /** + * Sets the value for codeFormat by executing the provided consumer. + * + *

    Generated from setter {@link JavadocCodeBlockDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(sb -> sb.append("text"));
    +   * }
    + * + * @param codeFormatStringBuilderConsumer consumer providing an instance of Codeformat + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeFormat( + Consumer codeFormatStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + codeFormatStringBuilderConsumer.accept(builder); + this.codeFormat = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for codeFormat by invoking the provided supplier. + * + *

    Generated from setter {@link JavadocCodeBlockDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(() -> "example value");
    +   * }
    + * + * @param codeFormatSupplier supplier for Codeformat + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeFormat(Supplier codeFormatSupplier) { + this.codeFormat = changedValue(codeFormatSupplier.get()); + return this; + } + + /** + * Sets the String value for codeFormat by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link JavadocCodeBlockDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeFormat(String format, Object... args) { + this.codeFormat = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for codeFormat. + * + *

    Generated from setter {@link JavadocCodeBlockDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value");
    +   * }
    + * + * @param codeFormat Codeformat + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeFormat(String codeFormat) { + this.codeFormat = changedValue(codeFormat); + return this; + } + + /** + * Updates the current value of codeFormat in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link JavadocCodeBlockDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
    +   * }
    + * + * @param codeFormatUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeFormat has not been set yet + */ + public JavadocCodeBlockDtoBuilder codeFormatUpdate(UnaryOperator codeFormatUpdater) { + if (!this.codeFormat.isSet()) { + throw new IllegalStateException("Cannot update 'codeFormat' before it is set"); + } + this.codeFormat = changedValue(codeFormatUpdater.apply(this.codeFormat.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public JavadocCodeBlockDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public JavadocCodeBlockDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * JavadocCodeBlockDto result = builder.build();
    +   * }
    + */ + public JavadocCodeBlockDto build() { + JavadocCodeBlockDto result = new JavadocCodeBlockDto(); + this.codeFormat.ifSet(result::setCodeFormat); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeFormat", this.codeFormat) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default JavadocCodeBlockDto with(Consumer b) { + JavadocCodeBlockDtoBuilder builder; + try { + builder = new JavadocCodeBlockDtoBuilder(JavadocCodeBlockDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'JavadocCodeBlockDtoBuilder.With' should only be implemented by classes, which could be casted to 'JavadocCodeBlockDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default JavadocCodeBlockDtoBuilder with() { + try { + return new JavadocCodeBlockDtoBuilder(JavadocCodeBlockDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'JavadocCodeBlockDtoBuilder.With' should only be implemented by classes, which could be casted to 'JavadocCodeBlockDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java new file mode 100644 index 00000000..7853d6a3 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java @@ -0,0 +1,499 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.javadoc; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.Arrays; +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.javadoc.JavadocDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * JavadocDto result = JavadocDtoBuilder.create()
    + *     .format("example value")
    + *     .format("Hello %s", "World")
    + *     .format(() -> "example value")
    + *     .format(sb -> sb.append("text"))
    + *     .formatUpdate(String::trim)
    + *     .exampleUsageCodeBlock(new JavadocCodeBlockDto())
    + *     .exampleUsageCodeBlock(JavadocCodeBlockDto::new)
    + *     .exampleUsageCodeBlock(javadocCodeBlockDtoBuilder -> javadocCodeBlockDtoBuilder)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class JavadocDtoBuilder { + + /** Tracked value for format: format. */ + private TrackedValue format = unsetValue(); + + /** Tracked value for args: args. */ + private TrackedValue args = unsetValue(); + + /** + * Tracked value for exampleUsageCodeBlock: the usage-example code block, or {@code + * null} to clear it. + */ + private TrackedValue exampleUsageCodeBlock = unsetValue(); + + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto}. */ + public JavadocDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public JavadocDtoBuilder(JavadocDto instance) { + this.exampleUsageCodeBlock = initialValue(instance.getExampleUsageCodeBlock()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto}. + * + *

    Example:

    + * + *
    {@code
    +   * JavadocDtoBuilder builder = JavadocDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto} + */ + public static JavadocDtoBuilder create() { + return new JavadocDtoBuilder(); + } + + /** + * Sets the value for args. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + * @param args args + * @return current instance of builder + */ + public JavadocDtoBuilder args(List args) { + this.args = changedValue(args.toArray(new Object[0])); + return this; + } + + /** + * Sets the value for args using the fluent builder consumer. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + * @param argsBuilderConsumer consumer for args + * @return current instance of builder + */ + public JavadocDtoBuilder args(Consumer> argsBuilderConsumer) { + ArrayListBuilder builder; + if (this.args.isSet()) { + builder = new ArrayListBuilder(Arrays.asList(this.args.value())); + } else { + builder = new ArrayListBuilder(Arrays.asList()); + } + argsBuilderConsumer.accept(builder); + this.args = changedValue(builder.build().toArray(new Object[0])); + return this; + } + + /** + * Sets the value for args by invoking the provided supplier. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + * @param argsSupplier supplier for args + * @return current instance of builder + */ + public JavadocDtoBuilder args(Supplier argsSupplier) { + this.args = changedValue(argsSupplier.get()); + return this; + } + + /** + * Sets the value for args. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + * @param args args + * @return current instance of builder + */ + public JavadocDtoBuilder args(Object... args) { + this.args = changedValue(args); + return this; + } + + /** + * Updates the current value of args in place by applying the given operator, instead + * of reading it out, changing it and setting it again. Useful for adjustments relative to the + * current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination with + * the With copy-and-modify flow. The value must have been set before (directly or + * via an existing instance). + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + * @param argsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if args has not been set yet + */ + public JavadocDtoBuilder argsUpdate(UnaryOperator argsUpdater) { + if (!this.args.isSet()) { + throw new IllegalStateException("Cannot update 'args' before it is set"); + } + this.args = changedValue(argsUpdater.apply(this.args.value())); + return this; + } + + /** + * Sets the value for exampleUsageCodeBlock using a builder consumer that produces + * the value. + * + *

    Generated from setter {@link JavadocDto#setExampleUsageCodeBlock(JavadocCodeBlockDto) + * setExampleUsageCodeBlock(JavadocCodeBlockDto exampleUsageCodeBlock)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.exampleUsageCodeBlock(javadocCodeBlockDtoBuilder -> javadocCodeBlockDtoBuilder);
    +   * }
    + * + * @param exampleUsageCodeBlockBuilderConsumer consumer providing an instance of a builder for the + * usage-example code block, or {@code null} to clear it + * @return current instance of builder + */ + public JavadocDtoBuilder exampleUsageCodeBlock( + Consumer exampleUsageCodeBlockBuilderConsumer) { + JavadocCodeBlockDtoBuilder builder = + this.exampleUsageCodeBlock.isSet() + ? new JavadocCodeBlockDtoBuilder(this.exampleUsageCodeBlock.value()) + : JavadocCodeBlockDtoBuilder.create(); + exampleUsageCodeBlockBuilderConsumer.accept(builder); + this.exampleUsageCodeBlock = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for exampleUsageCodeBlock by invoking the provided supplier. + * + *

    Generated from setter {@link JavadocDto#setExampleUsageCodeBlock(JavadocCodeBlockDto) + * setExampleUsageCodeBlock(JavadocCodeBlockDto exampleUsageCodeBlock)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.exampleUsageCodeBlock(JavadocCodeBlockDto::new);
    +   * }
    + * + * @param exampleUsageCodeBlockSupplier supplier for the usage-example code block, or {@code null} + * to clear it + * @return current instance of builder + */ + public JavadocDtoBuilder exampleUsageCodeBlock( + Supplier exampleUsageCodeBlockSupplier) { + this.exampleUsageCodeBlock = changedValue(exampleUsageCodeBlockSupplier.get()); + return this; + } + + /** + * Sets the value for exampleUsageCodeBlock. + * + *

    Generated from setter {@link JavadocDto#setExampleUsageCodeBlock(JavadocCodeBlockDto) + * setExampleUsageCodeBlock(JavadocCodeBlockDto exampleUsageCodeBlock)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.exampleUsageCodeBlock(new JavadocCodeBlockDto());
    +   * }
    + * + * @param exampleUsageCodeBlock the usage-example code block, or {@code null} to clear it + * @return current instance of builder + */ + public JavadocDtoBuilder exampleUsageCodeBlock(JavadocCodeBlockDto exampleUsageCodeBlock) { + this.exampleUsageCodeBlock = changedValue(exampleUsageCodeBlock); + return this; + } + + /** + * Updates the current value of exampleUsageCodeBlock in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). For changing multiple values of a nested DTO, + * prefer the builder-consumer helper {@link #exampleUsageCodeBlock(Consumer)}. + * + *

    Generated from setter {@link JavadocDto#setExampleUsageCodeBlock(JavadocCodeBlockDto) + * setExampleUsageCodeBlock(JavadocCodeBlockDto exampleUsageCodeBlock)} + * + * @param exampleUsageCodeBlockUpdater operator applied to the current value; its result becomes + * the new value + * @return current instance of builder + * @throws IllegalStateException if exampleUsageCodeBlock has not been set yet + */ + public JavadocDtoBuilder exampleUsageCodeBlockUpdate( + UnaryOperator exampleUsageCodeBlockUpdater) { + if (!this.exampleUsageCodeBlock.isSet()) { + throw new IllegalStateException("Cannot update 'exampleUsageCodeBlock' before it is set"); + } + this.exampleUsageCodeBlock = + changedValue(exampleUsageCodeBlockUpdater.apply(this.exampleUsageCodeBlock.value())); + return this; + } + + /** + * Sets the value for format by executing the provided consumer. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.format(sb -> sb.append("text"));
    +   * }
    + * + * @param formatStringBuilderConsumer consumer providing an instance of format + * @return current instance of builder + */ + public JavadocDtoBuilder format(Consumer formatStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + formatStringBuilderConsumer.accept(builder); + this.format = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for format by invoking the provided supplier. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.format(() -> "example value");
    +   * }
    + * + * @param formatSupplier supplier for format + * @return current instance of builder + */ + public JavadocDtoBuilder format(Supplier formatSupplier) { + this.format = changedValue(formatSupplier.get()); + return this; + } + + /** + * Sets the String value for format by using String.format(format, args). See {@link + * String#format(String, Object...)} for details. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.format("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public JavadocDtoBuilder format(String format, Object... args) { + this.format = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for format. + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.format("example value");
    +   * }
    + * + * @param format format + * @return current instance of builder + */ + public JavadocDtoBuilder format(String format) { + this.format = changedValue(format); + return this; + } + + /** + * Updates the current value of format in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from parameter in constructor {@link JavadocDto#JavadocDto(String, Object) + * JavadocDto(String format, Object args)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.format("example value").formatUpdate(String::trim);
    +   * }
    + * + * @param formatUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if format has not been set yet + */ + public JavadocDtoBuilder formatUpdate(UnaryOperator formatUpdater) { + if (!this.format.isSet()) { + throw new IllegalStateException("Cannot update 'format' before it is set"); + } + this.format = changedValue(formatUpdater.apply(this.format.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public JavadocDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public JavadocDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * JavadocDto result = builder.build();
    +   * }
    + */ + public JavadocDto build() { + JavadocDto result = new JavadocDto(this.format.value(), this.args.value()); + this.exampleUsageCodeBlock.ifSet(result::setExampleUsageCodeBlock); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("format", this.format) + .append("args", this.args) + .append("exampleUsageCodeBlock", this.exampleUsageCodeBlock) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default JavadocDto with(Consumer b) { + JavadocDtoBuilder builder; + try { + builder = new JavadocDtoBuilder(JavadocDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'JavadocDtoBuilder.With' should only be implemented by classes, which could be casted to 'JavadocDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default JavadocDtoBuilder with() { + try { + return new JavadocDtoBuilder(JavadocDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'JavadocDtoBuilder.With' should only be implemented by classes, which could be casted to 'JavadocDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java new file mode 100644 index 00000000..28b17ee8 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java @@ -0,0 +1,305 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.method; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.method.CodeTemplateDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * CodeTemplateDto result = CodeTemplateDtoBuilder.create()
    + *     .codeFormat("example value")
    + *     .codeFormat("Hello %s", "World")
    + *     .codeFormat(() -> "example value")
    + *     .codeFormat(sb -> sb.append("text"))
    + *     .codeFormatUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class CodeTemplateDtoBuilder { + + /** Tracked value for codeFormat: Codeformat. */ + private TrackedValue codeFormat = unsetValue(); + + /** + * Empty constructor of builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto}. + */ + public CodeTemplateDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public CodeTemplateDtoBuilder(CodeTemplateDto instance) { + this.codeFormat = initialValue(instance.getCodeFormat()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto}. + * + *

    Example:

    + * + *
    {@code
    +   * CodeTemplateDtoBuilder builder = CodeTemplateDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.method.CodeTemplateDto} + */ + public static CodeTemplateDtoBuilder create() { + return new CodeTemplateDtoBuilder(); + } + + /** + * Sets the value for codeFormat by executing the provided consumer. + * + *

    Generated from setter {@link CodeTemplateDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(sb -> sb.append("text"));
    +   * }
    + * + * @param codeFormatStringBuilderConsumer consumer providing an instance of Codeformat + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeFormat( + Consumer codeFormatStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + codeFormatStringBuilderConsumer.accept(builder); + this.codeFormat = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for codeFormat by invoking the provided supplier. + * + *

    Generated from setter {@link CodeTemplateDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(() -> "example value");
    +   * }
    + * + * @param codeFormatSupplier supplier for Codeformat + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeFormat(Supplier codeFormatSupplier) { + this.codeFormat = changedValue(codeFormatSupplier.get()); + return this; + } + + /** + * Sets the String value for codeFormat by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link CodeTemplateDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeFormat(String format, Object... args) { + this.codeFormat = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for codeFormat. + * + *

    Generated from setter {@link CodeTemplateDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value");
    +   * }
    + * + * @param codeFormat Codeformat + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeFormat(String codeFormat) { + this.codeFormat = changedValue(codeFormat); + return this; + } + + /** + * Updates the current value of codeFormat in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link CodeTemplateDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
    +   * }
    + * + * @param codeFormatUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeFormat has not been set yet + */ + public CodeTemplateDtoBuilder codeFormatUpdate(UnaryOperator codeFormatUpdater) { + if (!this.codeFormat.isSet()) { + throw new IllegalStateException("Cannot update 'codeFormat' before it is set"); + } + this.codeFormat = changedValue(codeFormatUpdater.apply(this.codeFormat.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public CodeTemplateDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public CodeTemplateDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * CodeTemplateDto result = builder.build();
    +   * }
    + */ + public CodeTemplateDto build() { + CodeTemplateDto result = new CodeTemplateDto(); + this.codeFormat.ifSet(result::setCodeFormat); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeFormat", this.codeFormat) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default CodeTemplateDto with(Consumer b) { + CodeTemplateDtoBuilder builder; + try { + builder = new CodeTemplateDtoBuilder(CodeTemplateDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'CodeTemplateDtoBuilder.With' should only be implemented by classes, which could be casted to 'CodeTemplateDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default CodeTemplateDtoBuilder with() { + try { + return new CodeTemplateDtoBuilder(CodeTemplateDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'CodeTemplateDtoBuilder.With' should only be implemented by classes, which could be casted to 'CodeTemplateDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java new file mode 100644 index 00000000..fbb34a67 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java @@ -0,0 +1,438 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.method; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.ConstructorDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.method.ConstructorDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * ConstructorDto result = ConstructorDtoBuilder.create()
    + *     .javadoc(new JavadocDto())
    + *     .javadoc(JavadocDto::new)
    + *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
    + *     .methodCodeDto(new MethodCodeDto())
    + *     .methodCodeDto(MethodCodeDto::new)
    + *     .methodCodeDto(methodCodeDtoBuilder -> methodCodeDtoBuilder)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class ConstructorDtoBuilder { + + /** Tracked value for javadoc: javadoc. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for methodCodeDto: the method code DTO. */ + private TrackedValue methodCodeDto = unsetValue(); + + /** Tracked value for visibility: visibility. */ + private TrackedValue visibility = unsetValue(); + + /** + * Empty constructor of builder for {@code org.javahelpers.codegen.model.method.ConstructorDto}. + */ + public ConstructorDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.method.ConstructorDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public ConstructorDtoBuilder(ConstructorDto instance) { + this.javadoc = initialValue(instance.getJavadoc()); + this.methodCodeDto = initialValue(instance.getMethodCodeDto()); + this.visibility = initialValue(instance.getVisibility()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.method.ConstructorDto}. + * + *

    Example:

    + * + *
    {@code
    +   * ConstructorDtoBuilder builder = ConstructorDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.method.ConstructorDto} + */ + public static ConstructorDtoBuilder create() { + return new ConstructorDtoBuilder(); + } + + /** + * Sets the value for javadoc using a builder consumer that produces the value. + * + *

    Generated from setter {@link ConstructorDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(javadocDtoBuilder -> javadocDtoBuilder);
    +   * }
    + * + * @param javadocBuilderConsumer consumer providing an instance of a builder for javadoc + * @return current instance of builder + */ + public ConstructorDtoBuilder javadoc(Consumer javadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.javadoc.isSet() + ? new JavadocDtoBuilder(this.javadoc.value()) + : JavadocDtoBuilder.create(); + javadocBuilderConsumer.accept(builder); + this.javadoc = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for javadoc by invoking the provided supplier. + * + *

    Generated from setter {@link ConstructorDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(JavadocDto::new);
    +   * }
    + * + * @param javadocSupplier supplier for javadoc + * @return current instance of builder + */ + public ConstructorDtoBuilder javadoc(Supplier javadocSupplier) { + this.javadoc = changedValue(javadocSupplier.get()); + return this; + } + + /** + * Sets the value for javadoc. + * + *

    Generated from setter {@link ConstructorDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(new JavadocDto());
    +   * }
    + * + * @param javadoc javadoc + * @return current instance of builder + */ + public ConstructorDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Updates the current value of javadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #javadoc(Consumer)}. + * + *

    Generated from setter {@link ConstructorDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + * @param javadocUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if javadoc has not been set yet + */ + public ConstructorDtoBuilder javadocUpdate(UnaryOperator javadocUpdater) { + if (!this.javadoc.isSet()) { + throw new IllegalStateException("Cannot update 'javadoc' before it is set"); + } + this.javadoc = changedValue(javadocUpdater.apply(this.javadoc.value())); + return this; + } + + /** + * Sets the value for methodCodeDto using a builder consumer that produces the value. + * + *

    Generated from setter {@link ConstructorDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodCodeDto(methodCodeDtoBuilder -> methodCodeDtoBuilder);
    +   * }
    + * + * @param methodCodeDtoBuilderConsumer consumer providing an instance of a builder for the method + * code DTO + * @return current instance of builder + */ + public ConstructorDtoBuilder methodCodeDto( + Consumer methodCodeDtoBuilderConsumer) { + MethodCodeDtoBuilder builder = + this.methodCodeDto.isSet() + ? new MethodCodeDtoBuilder(this.methodCodeDto.value()) + : MethodCodeDtoBuilder.create(); + methodCodeDtoBuilderConsumer.accept(builder); + this.methodCodeDto = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for methodCodeDto by invoking the provided supplier. + * + *

    Generated from setter {@link ConstructorDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodCodeDto(MethodCodeDto::new);
    +   * }
    + * + * @param methodCodeDtoSupplier supplier for the method code DTO + * @return current instance of builder + */ + public ConstructorDtoBuilder methodCodeDto(Supplier methodCodeDtoSupplier) { + this.methodCodeDto = changedValue(methodCodeDtoSupplier.get()); + return this; + } + + /** + * Sets the value for methodCodeDto. + * + *

    Generated from setter {@link ConstructorDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodCodeDto(new MethodCodeDto());
    +   * }
    + * + * @param methodCodeDto the method code DTO + * @return current instance of builder + */ + public ConstructorDtoBuilder methodCodeDto(MethodCodeDto methodCodeDto) { + this.methodCodeDto = changedValue(methodCodeDto); + return this; + } + + /** + * Updates the current value of methodCodeDto in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). For changing multiple values of a nested DTO, + * prefer the builder-consumer helper {@link #methodCodeDto(Consumer)}. + * + *

    Generated from setter {@link ConstructorDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + * @param methodCodeDtoUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if methodCodeDto has not been set yet + */ + public ConstructorDtoBuilder methodCodeDtoUpdate( + UnaryOperator methodCodeDtoUpdater) { + if (!this.methodCodeDto.isSet()) { + throw new IllegalStateException("Cannot update 'methodCodeDto' before it is set"); + } + this.methodCodeDto = changedValue(methodCodeDtoUpdater.apply(this.methodCodeDto.value())); + return this; + } + + /** + * Sets the value for visibility by invoking the provided supplier. + * + *

    Generated from setter {@link ConstructorDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilitySupplier supplier for visibility + * @return current instance of builder + */ + public ConstructorDtoBuilder visibility(Supplier visibilitySupplier) { + this.visibility = changedValue(visibilitySupplier.get()); + return this; + } + + /** + * Sets the value for visibility. + * + *

    Generated from setter {@link ConstructorDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibility visibility + * @return current instance of builder + */ + public ConstructorDtoBuilder visibility(AccessModifier visibility) { + this.visibility = changedValue(visibility); + return this; + } + + /** + * Updates the current value of visibility in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link ConstructorDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilityUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if visibility has not been set yet + */ + public ConstructorDtoBuilder visibilityUpdate(UnaryOperator visibilityUpdater) { + if (!this.visibility.isSet()) { + throw new IllegalStateException("Cannot update 'visibility' before it is set"); + } + this.visibility = changedValue(visibilityUpdater.apply(this.visibility.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public ConstructorDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public ConstructorDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * ConstructorDto result = builder.build();
    +   * }
    + */ + public ConstructorDto build() { + ConstructorDto result = new ConstructorDto(); + this.javadoc.ifSet(result::setJavadoc); + this.methodCodeDto.ifSet(result::setMethodCodeDto); + this.visibility.ifSet(result::setVisibility); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("javadoc", this.javadoc) + .append("methodCodeDto", this.methodCodeDto) + .append("visibility", this.visibility) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default ConstructorDto with(Consumer b) { + ConstructorDtoBuilder builder; + try { + builder = new ConstructorDtoBuilder(ConstructorDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'ConstructorDtoBuilder.With' should only be implemented by classes, which could be casted to 'ConstructorDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default ConstructorDtoBuilder with() { + try { + return new ConstructorDtoBuilder(ConstructorDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'ConstructorDtoBuilder.With' should only be implemented by classes, which could be casted to 'ConstructorDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java new file mode 100644 index 00000000..d1e08613 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java @@ -0,0 +1,304 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.method; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.method.MethodCodeDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * MethodCodeDto result = MethodCodeDtoBuilder.create()
    + *     .codeFormat("example value")
    + *     .codeFormat("Hello %s", "World")
    + *     .codeFormat(() -> "example value")
    + *     .codeFormat(sb -> sb.append("text"))
    + *     .codeFormatUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class MethodCodeDtoBuilder { + + /** Tracked value for codeFormat: Codeformat. */ + private TrackedValue codeFormat = unsetValue(); + + /** + * Empty constructor of builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto}. + */ + public MethodCodeDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public MethodCodeDtoBuilder(MethodCodeDto instance) { + this.codeFormat = initialValue(instance.getCodeFormat()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto}. + * + *

    Example:

    + * + *
    {@code
    +   * MethodCodeDtoBuilder builder = MethodCodeDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.method.MethodCodeDto} + */ + public static MethodCodeDtoBuilder create() { + return new MethodCodeDtoBuilder(); + } + + /** + * Sets the value for codeFormat by executing the provided consumer. + * + *

    Generated from setter {@link MethodCodeDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(sb -> sb.append("text"));
    +   * }
    + * + * @param codeFormatStringBuilderConsumer consumer providing an instance of Codeformat + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeFormat(Consumer codeFormatStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + codeFormatStringBuilderConsumer.accept(builder); + this.codeFormat = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for codeFormat by invoking the provided supplier. + * + *

    Generated from setter {@link MethodCodeDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat(() -> "example value");
    +   * }
    + * + * @param codeFormatSupplier supplier for Codeformat + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeFormat(Supplier codeFormatSupplier) { + this.codeFormat = changedValue(codeFormatSupplier.get()); + return this; + } + + /** + * Sets the String value for codeFormat by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link MethodCodeDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeFormat(String format, Object... args) { + this.codeFormat = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for codeFormat. + * + *

    Generated from setter {@link MethodCodeDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value");
    +   * }
    + * + * @param codeFormat Codeformat + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeFormat(String codeFormat) { + this.codeFormat = changedValue(codeFormat); + return this; + } + + /** + * Updates the current value of codeFormat in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link MethodCodeDto#setCodeFormat(String) setCodeFormat(String + * codeFormat)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
    +   * }
    + * + * @param codeFormatUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeFormat has not been set yet + */ + public MethodCodeDtoBuilder codeFormatUpdate(UnaryOperator codeFormatUpdater) { + if (!this.codeFormat.isSet()) { + throw new IllegalStateException("Cannot update 'codeFormat' before it is set"); + } + this.codeFormat = changedValue(codeFormatUpdater.apply(this.codeFormat.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public MethodCodeDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public MethodCodeDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * MethodCodeDto result = builder.build();
    +   * }
    + */ + public MethodCodeDto build() { + MethodCodeDto result = new MethodCodeDto(); + this.codeFormat.ifSet(result::setCodeFormat); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeFormat", this.codeFormat) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default MethodCodeDto with(Consumer b) { + MethodCodeDtoBuilder builder; + try { + builder = new MethodCodeDtoBuilder(MethodCodeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodCodeDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodCodeDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default MethodCodeDtoBuilder with() { + try { + return new MethodCodeDtoBuilder(MethodCodeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodCodeDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodCodeDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java new file mode 100644 index 00000000..73833953 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java @@ -0,0 +1,711 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.method; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.MethodDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.method.MethodDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * MethodDto result = MethodDtoBuilder.create()
    + *     .methodName("example value")
    + *     .methodName("Hello %s", "World")
    + *     .methodName(() -> "example value")
    + *     .methodName(sb -> sb.append("text"))
    + *     .methodNameUpdate(String::trim)
    + *     .code("example value")
    + *     .code("Hello %s", "World")
    + *     .code(() -> "example value")
    + *     .code(sb -> sb.append("text"))
    + *     .codeUpdate(String::trim)
    + *     .isStatic(true)
    + *     .isStatic(() -> true)
    + *     .isStaticUpdate(value -> !value)
    + *     .javadoc(new JavadocDto())
    + *     .javadoc(JavadocDto::new)
    + *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class MethodDtoBuilder { + + /** Tracked value for methodName: methodName. */ + private TrackedValue methodName = unsetValue(); + + /** Tracked value for returnType: returnType. */ + private TrackedValue returnType = unsetValue(); + + /** Tracked value for code: Codeformat with placeholders. */ + private TrackedValue code = unsetValue(); + + /** + * Tracked value for isStatic: true if the method should be static, false otherwise. + */ + private TrackedValue isStatic = unsetValue(); + + /** Tracked value for javadoc: the Javadoc comment. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for modifier: access modifier of type {@code AccessModifier}. */ + private TrackedValue modifier = unsetValue(); + + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.method.MethodDto}. */ + public MethodDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.method.MethodDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public MethodDtoBuilder(MethodDto instance) { + this.methodName = initialValue(instance.getMethodName()); + this.returnType = initialValue(instance.getReturnType()); + this.isStatic = initialValue(instance.isStatic()); + this.javadoc = initialValue(instance.getJavadoc()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.method.MethodDto}. + * + *

    Example:

    + * + *
    {@code
    +   * MethodDtoBuilder builder = MethodDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.method.MethodDto} + */ + public static MethodDtoBuilder create() { + return new MethodDtoBuilder(); + } + + /** + * Sets the value for code by executing the provided consumer. + * + *

    Generated from setter {@link MethodDto#setCode(String) setCode(String code)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.code(sb -> sb.append("text"));
    +   * }
    + * + * @param codeStringBuilderConsumer consumer providing an instance of Codeformat with placeholders + * @return current instance of builder + */ + public MethodDtoBuilder code(Consumer codeStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + codeStringBuilderConsumer.accept(builder); + this.code = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for code by invoking the provided supplier. + * + *

    Generated from setter {@link MethodDto#setCode(String) setCode(String code)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.code(() -> "example value");
    +   * }
    + * + * @param codeSupplier supplier for Codeformat with placeholders + * @return current instance of builder + */ + public MethodDtoBuilder code(Supplier codeSupplier) { + this.code = changedValue(codeSupplier.get()); + return this; + } + + /** + * Sets the String value for code by using String.format(format, args). See {@link + * String#format(String, Object...)} for details. + * + *

    Generated from setter {@link MethodDto#setCode(String) setCode(String code)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.code("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public MethodDtoBuilder code(String format, Object... args) { + this.code = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for code. + * + *

    Generated from setter {@link MethodDto#setCode(String) setCode(String code)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.code("example value");
    +   * }
    + * + * @param code Codeformat with placeholders + * @return current instance of builder + */ + public MethodDtoBuilder code(String code) { + this.code = changedValue(code); + return this; + } + + /** + * Updates the current value of code in place by applying the given operator, instead + * of reading it out, changing it and setting it again. Useful for adjustments relative to the + * current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination with + * the With copy-and-modify flow. The value must have been set before (directly or + * via an existing instance). + * + *

    Generated from setter {@link MethodDto#setCode(String) setCode(String code)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.code("example value").codeUpdate(String::trim);
    +   * }
    + * + * @param codeUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if code has not been set yet + */ + public MethodDtoBuilder codeUpdate(UnaryOperator codeUpdater) { + if (!this.code.isSet()) { + throw new IllegalStateException("Cannot update 'code' before it is set"); + } + this.code = changedValue(codeUpdater.apply(this.code.value())); + return this; + } + + /** + * Sets the value for isStatic by invoking the provided supplier. + * + *

    Generated from setter {@link MethodDto#setStatic(boolean) setStatic(boolean isStatic)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.isStatic(() -> true);
    +   * }
    + * + * @param isStaticSupplier supplier for true if the method should be static, false otherwise + * @return current instance of builder + */ + public MethodDtoBuilder isStatic(Supplier isStaticSupplier) { + this.isStatic = changedValue(isStaticSupplier.get()); + return this; + } + + /** + * Sets the value for isStatic. + * + *

    Generated from setter {@link MethodDto#setStatic(boolean) setStatic(boolean isStatic)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.isStatic(true);
    +   * }
    + * + * @param isStatic true if the method should be static, false otherwise + * @return current instance of builder + */ + public MethodDtoBuilder isStatic(boolean isStatic) { + this.isStatic = changedValue(isStatic); + return this; + } + + /** + * Updates the current value of isStatic in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link MethodDto#setStatic(boolean) setStatic(boolean isStatic)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.isStatic(true).isStaticUpdate(value -> !value);
    +   * }
    + * + * @param isStaticUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if isStatic has not been set yet + */ + public MethodDtoBuilder isStaticUpdate(UnaryOperator isStaticUpdater) { + if (!this.isStatic.isSet()) { + throw new IllegalStateException("Cannot update 'isStatic' before it is set"); + } + this.isStatic = changedValue(isStaticUpdater.apply(this.isStatic.value())); + return this; + } + + /** + * Sets the value for javadoc using a builder consumer that produces the value. + * + *

    Generated from setter {@link MethodDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(javadocDtoBuilder -> javadocDtoBuilder);
    +   * }
    + * + * @param javadocBuilderConsumer consumer providing an instance of a builder for the Javadoc + * comment + * @return current instance of builder + */ + public MethodDtoBuilder javadoc(Consumer javadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.javadoc.isSet() + ? new JavadocDtoBuilder(this.javadoc.value()) + : JavadocDtoBuilder.create(); + javadocBuilderConsumer.accept(builder); + this.javadoc = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for javadoc by invoking the provided supplier. + * + *

    Generated from setter {@link MethodDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(JavadocDto::new);
    +   * }
    + * + * @param javadocSupplier supplier for the Javadoc comment + * @return current instance of builder + */ + public MethodDtoBuilder javadoc(Supplier javadocSupplier) { + this.javadoc = changedValue(javadocSupplier.get()); + return this; + } + + /** + * Sets the value for javadoc. + * + *

    Generated from setter {@link MethodDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(new JavadocDto());
    +   * }
    + * + * @param javadoc the Javadoc comment + * @return current instance of builder + */ + public MethodDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Updates the current value of javadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #javadoc(Consumer)}. + * + *

    Generated from setter {@link MethodDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + * @param javadocUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if javadoc has not been set yet + */ + public MethodDtoBuilder javadocUpdate(UnaryOperator javadocUpdater) { + if (!this.javadoc.isSet()) { + throw new IllegalStateException("Cannot update 'javadoc' before it is set"); + } + this.javadoc = changedValue(javadocUpdater.apply(this.javadoc.value())); + return this; + } + + /** + * Sets the value for methodName by executing the provided consumer. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodName(sb -> sb.append("text"));
    +   * }
    + * + * @param methodNameStringBuilderConsumer consumer providing an instance of methodName + * @return current instance of builder + */ + public MethodDtoBuilder methodName(Consumer methodNameStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + methodNameStringBuilderConsumer.accept(builder); + this.methodName = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for methodName by invoking the provided supplier. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodName(() -> "example value");
    +   * }
    + * + * @param methodNameSupplier supplier for methodName + * @return current instance of builder + */ + public MethodDtoBuilder methodName(Supplier methodNameSupplier) { + this.methodName = changedValue(methodNameSupplier.get()); + return this; + } + + /** + * Sets the String value for methodName by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodName("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public MethodDtoBuilder methodName(String format, Object... args) { + this.methodName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for methodName. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodName("example value");
    +   * }
    + * + * @param methodName methodName + * @return current instance of builder + */ + public MethodDtoBuilder methodName(String methodName) { + this.methodName = changedValue(methodName); + return this; + } + + /** + * Updates the current value of methodName in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.methodName("example value").methodNameUpdate(String::trim);
    +   * }
    + * + * @param methodNameUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if methodName has not been set yet + */ + public MethodDtoBuilder methodNameUpdate(UnaryOperator methodNameUpdater) { + if (!this.methodName.isSet()) { + throw new IllegalStateException("Cannot update 'methodName' before it is set"); + } + this.methodName = changedValue(methodNameUpdater.apply(this.methodName.value())); + return this; + } + + /** + * Sets the value for modifier by invoking the provided supplier. + * + *

    Generated from setter {@link MethodDto#setModifier(AccessModifier) + * setModifier(AccessModifier modifier)} + * + * @param modifierSupplier supplier for access modifier of type {@code AccessModifier} + * @return current instance of builder + */ + public MethodDtoBuilder modifier(Supplier modifierSupplier) { + this.modifier = changedValue(modifierSupplier.get()); + return this; + } + + /** + * Sets the value for modifier. + * + *

    Generated from setter {@link MethodDto#setModifier(AccessModifier) + * setModifier(AccessModifier modifier)} + * + * @param modifier access modifier of type {@code AccessModifier} + * @return current instance of builder + */ + public MethodDtoBuilder modifier(AccessModifier modifier) { + this.modifier = changedValue(modifier); + return this; + } + + /** + * Updates the current value of modifier in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link MethodDto#setModifier(AccessModifier) + * setModifier(AccessModifier modifier)} + * + * @param modifierUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if modifier has not been set yet + */ + public MethodDtoBuilder modifierUpdate(UnaryOperator modifierUpdater) { + if (!this.modifier.isSet()) { + throw new IllegalStateException("Cannot update 'modifier' before it is set"); + } + this.modifier = changedValue(modifierUpdater.apply(this.modifier.value())); + return this; + } + + /** + * Sets the value for returnType by invoking the provided supplier. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + * @param returnTypeSupplier supplier for returnType + * @return current instance of builder + */ + public MethodDtoBuilder returnType(Supplier returnTypeSupplier) { + this.returnType = changedValue(returnTypeSupplier.get()); + return this; + } + + /** + * Sets the value for returnType. + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + * @param returnType returnType + * @return current instance of builder + */ + public MethodDtoBuilder returnType(TypeName returnType) { + this.returnType = changedValue(returnType); + return this; + } + + /** + * Updates the current value of returnType in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from parameter in constructor {@link MethodDto#MethodDto(String, TypeName) + * MethodDto(String methodName, TypeName returnType)} + * + * @param returnTypeUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if returnType has not been set yet + */ + public MethodDtoBuilder returnTypeUpdate(UnaryOperator returnTypeUpdater) { + if (!this.returnType.isSet()) { + throw new IllegalStateException("Cannot update 'returnType' before it is set"); + } + this.returnType = changedValue(returnTypeUpdater.apply(this.returnType.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public MethodDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public MethodDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * MethodDto result = builder.build();
    +   * }
    + */ + public MethodDto build() { + if (this.isStatic.isSet() && this.isStatic.value() == null) { + throw new IllegalStateException( + "Field 'isStatic' is marked as non-null but null value was provided"); + } + MethodDto result = new MethodDto(this.methodName.value(), this.returnType.value()); + this.code.ifSet(result::setCode); + this.isStatic.ifSet(result::setStatic); + this.javadoc.ifSet(result::setJavadoc); + this.modifier.ifSet(result::setModifier); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("methodName", this.methodName) + .append("returnType", this.returnType) + .append("code", this.code) + .append("isStatic", this.isStatic) + .append("javadoc", this.javadoc) + .append("modifier", this.modifier) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default MethodDto with(Consumer b) { + MethodDtoBuilder builder; + try { + builder = new MethodDtoBuilder(MethodDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default MethodDtoBuilder with() { + try { + return new MethodDtoBuilder(MethodDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java new file mode 100644 index 00000000..3f079d0e --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java @@ -0,0 +1,365 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.method; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.method.MethodParameterDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.method.MethodParameterDto with method chaining and validation. Use + * the static {@code create()} method to obtain a new builder instance, configure the desired + * properties using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * MethodParameterDto result = MethodParameterDtoBuilder.create()
    + *     .parameterName("example value")
    + *     .parameterName("Hello %s", "World")
    + *     .parameterName(() -> "example value")
    + *     .parameterName(sb -> sb.append("text"))
    + *     .parameterNameUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class MethodParameterDtoBuilder { + + /** Tracked value for parameterName: parameter name. */ + private TrackedValue parameterName = unsetValue(); + + /** Tracked value for parameterTypeName: type of parameter. */ + private TrackedValue parameterTypeName = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.codegen.model.method.MethodParameterDto}. + */ + public MethodParameterDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.method.MethodParameterDto} + * by a instance. + * + * @param instance object instance for initialisiation + */ + public MethodParameterDtoBuilder(MethodParameterDto instance) { + this.parameterName = initialValue(instance.getParameterName()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.method.MethodParameterDto}. + * + *

    Example:

    + * + *
    {@code
    +   * MethodParameterDtoBuilder builder = MethodParameterDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.method.MethodParameterDto} + */ + public static MethodParameterDtoBuilder create() { + return new MethodParameterDtoBuilder(); + } + + /** + * Sets the value for parameterName by executing the provided consumer. + * + *

    Generated from setter {@link MethodParameterDto#setParameterName(String) + * setParameterName(String parameterName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.parameterName(sb -> sb.append("text"));
    +   * }
    + * + * @param parameterNameStringBuilderConsumer consumer providing an instance of parameter name + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterName( + Consumer parameterNameStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + parameterNameStringBuilderConsumer.accept(builder); + this.parameterName = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for parameterName by invoking the provided supplier. + * + *

    Generated from setter {@link MethodParameterDto#setParameterName(String) + * setParameterName(String parameterName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.parameterName(() -> "example value");
    +   * }
    + * + * @param parameterNameSupplier supplier for parameter name + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterName(Supplier parameterNameSupplier) { + this.parameterName = changedValue(parameterNameSupplier.get()); + return this; + } + + /** + * Sets the String value for parameterName by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link MethodParameterDto#setParameterName(String) + * setParameterName(String parameterName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.parameterName("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterName(String format, Object... args) { + this.parameterName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for parameterName. + * + *

    Generated from setter {@link MethodParameterDto#setParameterName(String) + * setParameterName(String parameterName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.parameterName("example value");
    +   * }
    + * + * @param parameterName parameter name + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterName(String parameterName) { + this.parameterName = changedValue(parameterName); + return this; + } + + /** + * Updates the current value of parameterName in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link MethodParameterDto#setParameterName(String) + * setParameterName(String parameterName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.parameterName("example value").parameterNameUpdate(String::trim);
    +   * }
    + * + * @param parameterNameUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if parameterName has not been set yet + */ + public MethodParameterDtoBuilder parameterNameUpdate(UnaryOperator parameterNameUpdater) { + if (!this.parameterName.isSet()) { + throw new IllegalStateException("Cannot update 'parameterName' before it is set"); + } + this.parameterName = changedValue(parameterNameUpdater.apply(this.parameterName.value())); + return this; + } + + /** + * Sets the value for parameterTypeName by invoking the provided supplier. + * + *

    Generated from setter {@link MethodParameterDto#setParameterTypeName(TypeName) + * setParameterTypeName(TypeName parameterTypeName)} + * + * @param parameterTypeNameSupplier supplier for type of parameter + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterTypeName(Supplier parameterTypeNameSupplier) { + this.parameterTypeName = changedValue(parameterTypeNameSupplier.get()); + return this; + } + + /** + * Sets the value for parameterTypeName. + * + *

    Generated from setter {@link MethodParameterDto#setParameterTypeName(TypeName) + * setParameterTypeName(TypeName parameterTypeName)} + * + * @param parameterTypeName type of parameter + * @return current instance of builder + */ + public MethodParameterDtoBuilder parameterTypeName(TypeName parameterTypeName) { + this.parameterTypeName = changedValue(parameterTypeName); + return this; + } + + /** + * Updates the current value of parameterTypeName in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

    Generated from setter {@link MethodParameterDto#setParameterTypeName(TypeName) + * setParameterTypeName(TypeName parameterTypeName)} + * + * @param parameterTypeNameUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if parameterTypeName has not been set yet + */ + public MethodParameterDtoBuilder parameterTypeNameUpdate( + UnaryOperator parameterTypeNameUpdater) { + if (!this.parameterTypeName.isSet()) { + throw new IllegalStateException("Cannot update 'parameterTypeName' before it is set"); + } + this.parameterTypeName = + changedValue(parameterTypeNameUpdater.apply(this.parameterTypeName.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public MethodParameterDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public MethodParameterDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * MethodParameterDto result = builder.build();
    +   * }
    + */ + public MethodParameterDto build() { + MethodParameterDto result = new MethodParameterDto(); + this.parameterName.ifSet(result::setParameterName); + this.parameterTypeName.ifSet(result::setParameterTypeName); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("parameterName", this.parameterName) + .append("parameterTypeName", this.parameterTypeName) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default MethodParameterDto with(Consumer b) { + MethodParameterDtoBuilder builder; + try { + builder = new MethodParameterDtoBuilder(MethodParameterDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodParameterDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodParameterDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default MethodParameterDtoBuilder with() { + try { + return new MethodParameterDtoBuilder(MethodParameterDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'MethodParameterDtoBuilder.With' should only be implemented by classes, which could be casted to 'MethodParameterDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java new file mode 100644 index 00000000..82d0a1b1 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java @@ -0,0 +1,300 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.type; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.type.GenericParameterDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.type.GenericParameterDto with method chaining and validation. Use + * the static {@code create()} method to obtain a new builder instance, configure the desired + * properties using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * GenericParameterDto result = GenericParameterDtoBuilder.create()
    + *     .name("example value")
    + *     .name("Hello %s", "World")
    + *     .name(() -> "example value")
    + *     .name(sb -> sb.append("text"))
    + *     .nameUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class GenericParameterDtoBuilder { + + /** Tracked value for name: the name to set (e.g., "T", "K", "V"). */ + private TrackedValue name = unsetValue(); + + /** + * Empty constructor of builder for {@code + * org.javahelpers.codegen.model.type.GenericParameterDto}. + */ + public GenericParameterDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.type.GenericParameterDto} by + * a instance. + * + * @param instance object instance for initialisiation + */ + public GenericParameterDtoBuilder(GenericParameterDto instance) { + this.name = initialValue(instance.getName()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.type.GenericParameterDto}. + * + *

    Example:

    + * + *
    {@code
    +   * GenericParameterDtoBuilder builder = GenericParameterDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.type.GenericParameterDto} + */ + public static GenericParameterDtoBuilder create() { + return new GenericParameterDtoBuilder(); + } + + /** + * Sets the value for name by executing the provided consumer. + * + *

    Generated from setter {@link GenericParameterDto#setName(String) setName(String name)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.name(sb -> sb.append("text"));
    +   * }
    + * + * @param nameStringBuilderConsumer consumer providing an instance of the name to set (e.g., "T", + * "K", "V") + * @return current instance of builder + */ + public GenericParameterDtoBuilder name(Consumer nameStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + nameStringBuilderConsumer.accept(builder); + this.name = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for name by invoking the provided supplier. + * + *

    Generated from setter {@link GenericParameterDto#setName(String) setName(String name)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.name(() -> "example value");
    +   * }
    + * + * @param nameSupplier supplier for the name to set (e.g., "T", "K", "V") + * @return current instance of builder + */ + public GenericParameterDtoBuilder name(Supplier nameSupplier) { + this.name = changedValue(nameSupplier.get()); + return this; + } + + /** + * Sets the String value for name by using String.format(format, args). See {@link + * String#format(String, Object...)} for details. + * + *

    Generated from setter {@link GenericParameterDto#setName(String) setName(String name)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.name("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public GenericParameterDtoBuilder name(String format, Object... args) { + this.name = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for name. + * + *

    Generated from setter {@link GenericParameterDto#setName(String) setName(String name)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.name("example value");
    +   * }
    + * + * @param name the name to set (e.g., "T", "K", "V") + * @return current instance of builder + */ + public GenericParameterDtoBuilder name(String name) { + this.name = changedValue(name); + return this; + } + + /** + * Updates the current value of name in place by applying the given operator, instead + * of reading it out, changing it and setting it again. Useful for adjustments relative to the + * current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination with + * the With copy-and-modify flow. The value must have been set before (directly or + * via an existing instance). + * + *

    Generated from setter {@link GenericParameterDto#setName(String) setName(String name)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.name("example value").nameUpdate(String::trim);
    +   * }
    + * + * @param nameUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if name has not been set yet + */ + public GenericParameterDtoBuilder nameUpdate(UnaryOperator nameUpdater) { + if (!this.name.isSet()) { + throw new IllegalStateException("Cannot update 'name' before it is set"); + } + this.name = changedValue(nameUpdater.apply(this.name.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public GenericParameterDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public GenericParameterDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * GenericParameterDto result = builder.build();
    +   * }
    + */ + public GenericParameterDto build() { + GenericParameterDto result = new GenericParameterDto(); + this.name.ifSet(result::setName); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("name", this.name) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default GenericParameterDto with(Consumer b) { + GenericParameterDtoBuilder builder; + try { + builder = new GenericParameterDtoBuilder(GenericParameterDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GenericParameterDtoBuilder.With' should only be implemented by classes, which could be casted to 'GenericParameterDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default GenericParameterDtoBuilder with() { + try { + return new GenericParameterDtoBuilder(GenericParameterDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'GenericParameterDtoBuilder.With' should only be implemented by classes, which could be casted to 'GenericParameterDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java new file mode 100644 index 00000000..d809286e --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java @@ -0,0 +1,513 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.javahelpers.codegen.model.type; + +import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; +import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import javax.annotation.processing.Generated; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; +import org.javahelpers.simple.builders.core.util.TrackedValue; + +/** + * Builder for {@code org.javahelpers.codegen.model.type.NestedTypeDto}. + * + *

    This builder provides a fluent API for creating instances of + * org.javahelpers.codegen.model.type.NestedTypeDto with method chaining and validation. Use the + * static {@code create()} method to obtain a new builder instance, configure the desired properties + * using the setter methods, and then call {@code build()} to create the final DTO. + * + *

    Example:

    + * + *
    {@code
    + * NestedTypeDto result = NestedTypeDtoBuilder.create()
    + *     .javadoc(new JavadocDto())
    + *     .javadoc(JavadocDto::new)
    + *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
    + *     .typeName("example value")
    + *     .typeName("Hello %s", "World")
    + *     .typeName(() -> "example value")
    + *     .typeName(sb -> sb.append("text"))
    + *     .typeNameUpdate(String::trim)
    + *     .build();
    + * }
    + */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +public class NestedTypeDtoBuilder { + + /** Tracked value for javadoc: javadoc. */ + private TrackedValue javadoc = unsetValue(); + + /** Tracked value for kind: kind. */ + private TrackedValue kind = + unsetValue(); + + /** Tracked value for typeName: typeName. */ + private TrackedValue typeName = unsetValue(); + + /** Tracked value for visibility: visibility. */ + private TrackedValue visibility = unsetValue(); + + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.type.NestedTypeDto}. */ + public NestedTypeDtoBuilder() {} + + /** + * Initialisation of builder for {@code org.javahelpers.codegen.model.type.NestedTypeDto} by a + * instance. + * + * @param instance object instance for initialisiation + */ + public NestedTypeDtoBuilder(NestedTypeDto instance) { + this.javadoc = initialValue(instance.getJavadoc()); + this.kind = initialValue(instance.getKind()); + this.typeName = initialValue(instance.getTypeName()); + this.visibility = initialValue(instance.getVisibility()); + } + + /** + * Creating a new builder for {@code org.javahelpers.codegen.model.type.NestedTypeDto}. + * + *

    Example:

    + * + *
    {@code
    +   * NestedTypeDtoBuilder builder = NestedTypeDtoBuilder.create();
    +   * }
    + * + * @return builder for {@code org.javahelpers.codegen.model.type.NestedTypeDto} + */ + public static NestedTypeDtoBuilder create() { + return new NestedTypeDtoBuilder(); + } + + /** + * Sets the value for javadoc using a builder consumer that produces the value. + * + *

    Generated from setter {@link NestedTypeDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(javadocDtoBuilder -> javadocDtoBuilder);
    +   * }
    + * + * @param javadocBuilderConsumer consumer providing an instance of a builder for javadoc + * @return current instance of builder + */ + public NestedTypeDtoBuilder javadoc(Consumer javadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.javadoc.isSet() + ? new JavadocDtoBuilder(this.javadoc.value()) + : JavadocDtoBuilder.create(); + javadocBuilderConsumer.accept(builder); + this.javadoc = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for javadoc by invoking the provided supplier. + * + *

    Generated from setter {@link NestedTypeDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(JavadocDto::new);
    +   * }
    + * + * @param javadocSupplier supplier for javadoc + * @return current instance of builder + */ + public NestedTypeDtoBuilder javadoc(Supplier javadocSupplier) { + this.javadoc = changedValue(javadocSupplier.get()); + return this; + } + + /** + * Sets the value for javadoc. + * + *

    Generated from setter {@link NestedTypeDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.javadoc(new JavadocDto());
    +   * }
    + * + * @param javadoc javadoc + * @return current instance of builder + */ + public NestedTypeDtoBuilder javadoc(JavadocDto javadoc) { + this.javadoc = changedValue(javadoc); + return this; + } + + /** + * Updates the current value of javadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #javadoc(Consumer)}. + * + *

    Generated from setter {@link NestedTypeDto#setJavadoc(JavadocDto) setJavadoc(JavadocDto + * javadoc)} + * + * @param javadocUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if javadoc has not been set yet + */ + public NestedTypeDtoBuilder javadocUpdate(UnaryOperator javadocUpdater) { + if (!this.javadoc.isSet()) { + throw new IllegalStateException("Cannot update 'javadoc' before it is set"); + } + this.javadoc = changedValue(javadocUpdater.apply(this.javadoc.value())); + return this; + } + + /** + * Sets the value for kind by invoking the provided supplier. + * + *

    Generated from setter {@link NestedTypeDto#setKind(NestedTypeDto.NestedTypeKind) + * setKind(NestedTypeDto.NestedTypeKind kind)} + * + * @param kindSupplier supplier for kind + * @return current instance of builder + */ + public NestedTypeDtoBuilder kind( + Supplier kindSupplier) { + this.kind = changedValue(kindSupplier.get()); + return this; + } + + /** + * Sets the value for kind. + * + *

    Generated from setter {@link NestedTypeDto#setKind(NestedTypeDto.NestedTypeKind) + * setKind(NestedTypeDto.NestedTypeKind kind)} + * + * @param kind kind + * @return current instance of builder + */ + public NestedTypeDtoBuilder kind( + org.javahelpers.codegen.model.type.NestedTypeDto.NestedTypeKind kind) { + this.kind = changedValue(kind); + return this; + } + + /** + * Updates the current value of kind in place by applying the given operator, instead + * of reading it out, changing it and setting it again. Useful for adjustments relative to the + * current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination with + * the With copy-and-modify flow. The value must have been set before (directly or + * via an existing instance). + * + *

    Generated from setter {@link NestedTypeDto#setKind(NestedTypeDto.NestedTypeKind) + * setKind(NestedTypeDto.NestedTypeKind kind)} + * + * @param kindUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if kind has not been set yet + */ + public NestedTypeDtoBuilder kindUpdate( + UnaryOperator kindUpdater) { + if (!this.kind.isSet()) { + throw new IllegalStateException("Cannot update 'kind' before it is set"); + } + this.kind = changedValue(kindUpdater.apply(this.kind.value())); + return this; + } + + /** + * Sets the value for typeName by executing the provided consumer. + * + *

    Generated from setter {@link NestedTypeDto#setTypeName(String) setTypeName(String typeName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.typeName(sb -> sb.append("text"));
    +   * }
    + * + * @param typeNameStringBuilderConsumer consumer providing an instance of typeName + * @return current instance of builder + */ + public NestedTypeDtoBuilder typeName(Consumer typeNameStringBuilderConsumer) { + StringBuilder builder = new StringBuilder(); + typeNameStringBuilderConsumer.accept(builder); + this.typeName = changedValue(builder.toString()); + return this; + } + + /** + * Sets the value for typeName by invoking the provided supplier. + * + *

    Generated from setter {@link NestedTypeDto#setTypeName(String) setTypeName(String typeName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.typeName(() -> "example value");
    +   * }
    + * + * @param typeNameSupplier supplier for typeName + * @return current instance of builder + */ + public NestedTypeDtoBuilder typeName(Supplier typeNameSupplier) { + this.typeName = changedValue(typeNameSupplier.get()); + return this; + } + + /** + * Sets the String value for typeName by using String.format(format, args). See + * {@link String#format(String, Object...)} for details. + * + *

    Generated from setter {@link NestedTypeDto#setTypeName(String) setTypeName(String typeName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.typeName("Hello %s", "World");
    +   * }
    + * + * @param format A format string + * @param args Arguments referenced by the format specifiers in the format string. + * @return current instance of builder + */ + public NestedTypeDtoBuilder typeName(String format, Object... args) { + this.typeName = changedValue(String.format(format, args)); + return this; + } + + /** + * Sets the value for typeName. + * + *

    Generated from setter {@link NestedTypeDto#setTypeName(String) setTypeName(String typeName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.typeName("example value");
    +   * }
    + * + * @param typeName typeName + * @return current instance of builder + */ + public NestedTypeDtoBuilder typeName(String typeName) { + this.typeName = changedValue(typeName); + return this; + } + + /** + * Updates the current value of typeName in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link NestedTypeDto#setTypeName(String) setTypeName(String typeName)} + * + *

    Example:

    + * + *
    {@code
    +   * builder.typeName("example value").typeNameUpdate(String::trim);
    +   * }
    + * + * @param typeNameUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if typeName has not been set yet + */ + public NestedTypeDtoBuilder typeNameUpdate(UnaryOperator typeNameUpdater) { + if (!this.typeName.isSet()) { + throw new IllegalStateException("Cannot update 'typeName' before it is set"); + } + this.typeName = changedValue(typeNameUpdater.apply(this.typeName.value())); + return this; + } + + /** + * Sets the value for visibility by invoking the provided supplier. + * + *

    Generated from setter {@link NestedTypeDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilitySupplier supplier for visibility + * @return current instance of builder + */ + public NestedTypeDtoBuilder visibility(Supplier visibilitySupplier) { + this.visibility = changedValue(visibilitySupplier.get()); + return this; + } + + /** + * Sets the value for visibility. + * + *

    Generated from setter {@link NestedTypeDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibility visibility + * @return current instance of builder + */ + public NestedTypeDtoBuilder visibility(AccessModifier visibility) { + this.visibility = changedValue(visibility); + return this; + } + + /** + * Updates the current value of visibility in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

    Generated from setter {@link NestedTypeDto#setVisibility(AccessModifier) + * setVisibility(AccessModifier visibility)} + * + * @param visibilityUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if visibility has not been set yet + */ + public NestedTypeDtoBuilder visibilityUpdate(UnaryOperator visibilityUpdater) { + if (!this.visibility.isSet()) { + throw new IllegalStateException("Cannot update 'visibility' before it is set"); + } + this.visibility = changedValue(visibilityUpdater.apply(this.visibility.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public NestedTypeDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public NestedTypeDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

    Example:

    + * + *
    {@code
    +   * NestedTypeDto result = builder.build();
    +   * }
    + */ + public NestedTypeDto build() { + NestedTypeDto result = new NestedTypeDto(); + this.javadoc.ifSet(result::setJavadoc); + this.kind.ifSet(result::setKind); + this.typeName.ifSet(result::setTypeName); + this.visibility.ifSet(result::setVisibility); + return result; + } + + /** + * Returns a string representation of this builder, including only fields that have been set. + * + * @return string representation of the builder + */ + @Override + public String toString() { + return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("javadoc", this.javadoc) + .append("kind", this.kind) + .append("typeName", this.typeName) + .append("visibility", this.visibility) + .toString(); + } + + /** Interface that can be implemented by the DTO to provide fluent modification methods. */ + public interface With { + /** + * Initializes a builder from an instance of this class, using methods of this builder to change + * values and returns the new built object. + * + * @param b the consumer to apply modifications + * @return the modified instance + */ + default NestedTypeDto with(Consumer b) { + NestedTypeDtoBuilder builder; + try { + builder = new NestedTypeDtoBuilder(NestedTypeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'NestedTypeDtoBuilder.With' should only be implemented by classes, which could be casted to 'NestedTypeDto'", + ex); + } + b.accept(builder); + return builder.build(); + } + + /** + * Creates a builder initialized from this instance. + * + * @return a builder initialized with this instance's values + */ + default NestedTypeDtoBuilder with() { + try { + return new NestedTypeDtoBuilder(NestedTypeDto.class.cast(this)); + } catch (ClassCastException ex) { + throw new IllegalArgumentException( + "The interface 'NestedTypeDtoBuilder.With' should only be implemented by classes, which could be casted to 'NestedTypeDto'", + ex); + } + } + } +} diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java new file mode 100644 index 00000000..539cf80f --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java @@ -0,0 +1,112 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.model.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.junit.jupiter.api.Test; + +/** Tests for the generated {@link GenerationTargetClassDtoBuilder}. */ +class GenerationTargetClassDtoBuilderTest { + + @Test + void buildsEquivalentDtoAsSetterSequence() { + // Same DTO as assembled field-by-field in RoasterCodeGeneratorTest + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "AnnotatedBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classJavadoc(new JavadocDto("Builder for {@link Person}.")) + .superType(new TypeName("test", "AbstractBuilder")) + .build(); + + assertEquals(new TypeName("test", "AnnotatedBuilder"), dto.getTypeName()); + assertEquals(AccessModifier.PUBLIC, dto.getClassAccessModifier()); + assertEquals(FormattingMode.NONE, dto.getFormattingMode()); + assertEquals("Builder for {@link Person}.", dto.getClassJavadoc().getDescription()); + assertEquals(new TypeName("test", "AbstractBuilder"), dto.getSuperType()); + } + + @Test + void buildsNestedDtoViaBuilderConsumer() { + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "EmptyBuilder")) + .classJavadoc(javadoc -> javadoc.format("Builder for {@link %s}.", "Person")) + .build(); + + assertEquals("Builder for {@link Person}.", dto.getClassJavadoc().getDescription()); + } + + @Test + void unsetPropertiesRemainNull() { + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "EmptyBuilder")) + .build(); + + assertNull(dto.getClassAccessModifier()); + assertNull(dto.getClassJavadoc()); + assertNull(dto.getSuperType()); + assertNull(dto.getFormattingMode()); + } + + @Test + void builderInitializedFromInstanceAppliesChanges() { + GenerationTargetClassDto original = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "Builder")) + .classAccessModifier(AccessModifier.PUBLIC) + .build(); + + GenerationTargetClassDto modified = + new GenerationTargetClassDtoBuilder(original) + .classAccessModifier(AccessModifier.PRIVATE) + .build(); + + assertEquals(original.getTypeName(), modified.getTypeName()); + assertEquals(AccessModifier.PRIVATE, modified.getClassAccessModifier()); + assertEquals(AccessModifier.PUBLIC, original.getClassAccessModifier()); + } + + @Test + void methodDtoBuilderCoversIsStaticFlag() { + // MethodDto.setStatic resolves to property "static" (a Java keyword) and is ignored; the + // setIsStatic alias exposes the flag to the generated builder instead. + MethodDto method = MethodDtoBuilder.create().methodName("m").isStatic(true).build(); + + assertEquals("m", method.getMethodName()); + assertTrue(method.isStatic()); + } +} diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java index 56e628fe..425c92c3 100644 --- a/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java @@ -29,10 +29,14 @@ import java.util.List; import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.imports.ImportStatement; import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.junit.jupiter.api.Test; @@ -46,16 +50,11 @@ private static List fqns(GenerationTargetClassDto classDef) { } private static GenerationTargetClassDto classDef(String pkg, String name) { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName(pkg, name)); - return classDef; + return GenerationTargetClassDtoBuilder.create().typeName(new TypeName(pkg, name)).build(); } private static ClassFieldDto field(String name, String pkg, String type) { - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName(name); - field.setFieldType(new TypeName(pkg, type)); - return field; + return ClassFieldDtoBuilder.create().fieldName(name).fieldType(new TypeName(pkg, type)).build(); } @Test @@ -84,10 +83,16 @@ void genericTypeImportsRawTypeAndArguments() { GenerationTargetClassDto classDef = classDef("com.example", "Dto"); classDef.addClassField(field("mapping", "com.example", "StringIntegerMap")); - MethodDto method = new MethodDto("values", new TypeName("java.util", "Collection")); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("key"); - param.setParameterTypeName(new TypeName("com.other", "KeyDto")); + MethodDto method = + MethodDtoBuilder.create() + .methodName("values") + .returnType(new TypeName("java.util", "Collection")) + .build(); + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("key") + .parameterTypeName(new TypeName("com.other", "KeyDto")) + .build(); method.addParameter(param); classDef.addMethod(method); diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index 10d42bb7..36a104ec 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java @@ -33,11 +33,16 @@ import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.method.ConstructorDto; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; import org.javahelpers.codegen.model.method.MethodCodeDto; +import org.javahelpers.codegen.model.method.MethodCodeDtoBuilder; import org.javahelpers.codegen.model.method.MethodCodePlaceholder; import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; import org.javahelpers.codegen.testing.CapturingProcessingLogger; @@ -64,17 +69,20 @@ private UnsupportedPlaceholder(String label, String value) { @Test void shouldWrapRenderingRuntimeExceptionInCodeGenerationException() { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("com.example", "FailingBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("com.example", "FailingBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .build(); - MethodCodeDto code = new MethodCodeDto(); - code.setCodeFormat("return $value:X;"); + MethodCodeDto code = MethodCodeDtoBuilder.create().codeFormat("return $value:X;").build(); code.addCodeArgument(new UnsupportedPlaceholder("value", "irrelevant")); - ConstructorDto constructor = new ConstructorDto(); - constructor.setVisibility(AccessModifier.PUBLIC); - constructor.setMethodCodeDto(code); + ConstructorDto constructor = + ConstructorDtoBuilder.create() + .visibility(AccessModifier.PUBLIC) + .methodCodeDto(code) + .build(); classDef.addConstructor(constructor); ProcessingLogger logger = CapturingProcessingLogger.create().logger(); @@ -97,10 +105,12 @@ void shouldWrapRenderingRuntimeExceptionInCodeGenerationException() { */ @Test void shouldKeepFirstMethodAndWarnOnDuplicateSignature() { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("com.example", "DuplicateSignatureBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("com.example", "DuplicateSignatureBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); classDef.addMethod(duplicateSignatureMethod("first")); classDef.addMethod(duplicateSignatureMethod("second")); @@ -118,13 +128,18 @@ void shouldKeepFirstMethodAndWarnOnDuplicateSignature() { private static MethodDto duplicateSignatureMethod(String marker) { MethodDto method = - new MethodDto("name", new TypeName("com.example", "DuplicateSignatureBuilder")); - method.setModifier(AccessModifier.PUBLIC); - MethodParameterDto parameter = new MethodParameterDto(); - parameter.setParameterName("value"); - parameter.setParameterTypeName(TypeName.of(String.class)); + MethodDtoBuilder.create() + .methodName("name") + .returnType(new TypeName("com.example", "DuplicateSignatureBuilder")) + .modifier(AccessModifier.PUBLIC) + .code("return this; // " + marker) + .build(); + MethodParameterDto parameter = + MethodParameterDtoBuilder.create() + .parameterName("value") + .parameterTypeName(TypeName.of(String.class)) + .build(); method.addParameter(parameter); - method.setCode("return this; // " + marker); return method; } } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index ed02a2d7..bc777963 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -31,15 +31,24 @@ import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.annotation.InterfaceName; import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; import org.javahelpers.codegen.model.method.ConstructorDto; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; import org.javahelpers.codegen.model.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; @@ -77,26 +86,33 @@ public Person build() { @Test void writesFileUnderQualifiedName() throws Exception { - GenerationTargetClassDto empty = new GenerationTargetClassDto(); - empty.setTypeName(new TypeName("com.example", "EmptyBuilder")); - empty.setClassAccessModifier(AccessModifier.PUBLIC); - empty.setFormattingMode(FormattingMode.NONE); + GenerationTargetClassDto empty = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("com.example", "EmptyBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); assertEquals("mem:///com/example/EmptyBuilder.java", generate(empty).writtenUri().toString()); } @Test void generatesClassMetadataJavadocAndAnnotations() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "AnnotatedBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - classDef.setClassJavadoc(new JavadocDto("Builder for {@link Person}.")); - AnnotationDto generated = new AnnotationDto(); - generated.setAnnotationType(new TypeName("javax.annotation", "Generated")); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "AnnotatedBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .classJavadoc( + JavadocDtoBuilder.create().format("Builder for {@link Person}.").args().build()) + .superType(new TypeName("test", "AbstractBuilder")) + .build(); + AnnotationDto generated = + AnnotationDtoBuilder.create() + .annotationType(new TypeName("javax.annotation", "Generated")) + .build(); generated.addMember("value", "\"simple-builders\""); classDef.addClassAnnotation(generated); - classDef.setSuperType(new TypeName("test", "AbstractBuilder")); InterfaceName iface = new InterfaceName("java.io", "Serializable"); classDef.addInterface(iface); @@ -116,26 +132,32 @@ public class AnnotatedBuilder extends AbstractBuilder implements Serializable { @Test void generatesGenericClassAndMethods() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "GenericBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - GenericParameterDto generic = new GenericParameterDto(); - generic.setName("T"); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "GenericBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + GenericParameterDto generic = GenericParameterDtoBuilder.create().name("T").build(); classDef.addGeneric(generic); - MethodDto genericMethod = new MethodDto("of", new TypeNameVariable("T")); - genericMethod.setModifier(AccessModifier.PUBLIC); - genericMethod.setStatic(true); - GenericParameterDto methodGeneric = new GenericParameterDto(); - methodGeneric.setName("R"); + MethodDto genericMethod = + MethodDtoBuilder.create() + .methodName("of") + .returnType(new TypeNameVariable("T")) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return null;") + .build(); + GenericParameterDto methodGeneric = GenericParameterDtoBuilder.create().name("R").build(); methodGeneric.addUpperBound(TypeName.of(Number.class)); genericMethod.addGenericParameter(methodGeneric); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("input"); - param.setParameterTypeName(new TypeNameVariable("R")); + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("input") + .parameterTypeName(new TypeNameVariable("R")) + .build(); genericMethod.addParameter(param); - genericMethod.setCode("return null;"); classDef.addMethod(genericMethod); assertGeneratedSource( @@ -151,25 +173,31 @@ public static T of(R input) { @Test void generatesConstructorAndFieldVariants() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "CtorBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto constant = new ClassFieldDto(); - constant.setFieldName("DEFAULT_SIZE"); - constant.setFieldType(TypeNamePrimitive.INT); - constant.setVisibility(AccessModifier.PRIVATE); - constant.setLiteralInitializer("42"); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "CtorBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + ClassFieldDto constant = + ClassFieldDtoBuilder.create() + .fieldName("DEFAULT_SIZE") + .fieldType(TypeNamePrimitive.INT) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("42") + .build(); classDef.addClassField(constant); - ConstructorDto ctor = new ConstructorDto(); - ctor.setVisibility(AccessModifier.PROTECTED); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("capacity"); - param.setParameterTypeName(TypeNamePrimitive.INT); - AnnotationDto paramAnnotation = new AnnotationDto(); - paramAnnotation.setAnnotationType(new TypeName("test.anno", "NonNull")); + ConstructorDto ctor = + ConstructorDtoBuilder.create().visibility(AccessModifier.PROTECTED).build(); + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("capacity") + .parameterTypeName(TypeNamePrimitive.INT) + .build(); + AnnotationDto paramAnnotation = + AnnotationDtoBuilder.create().annotationType(new TypeName("test.anno", "NonNull")).build(); param.addAnnotation(paramAnnotation); ctor.addParameter(param); classDef.addConstructor(ctor); @@ -188,19 +216,27 @@ protected CtorBuilder(int capacity) { @Test void generatesNestedTypesWithMembers() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "OuterBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - NestedTypeDto nested = new NestedTypeDto(); - nested.setTypeName("Helper"); - nested.setKind(NestedTypeDto.NestedTypeKind.CLASS); - nested.setVisibility(AccessModifier.PUBLIC); - nested.setJavadoc(new JavadocDto("Nested helper.")); - MethodDto nestedMethod = new MethodDto("assist", TypeNamePrimitive.VOID); - nestedMethod.setModifier(AccessModifier.PRIVATE); - nestedMethod.setCode("// nothing"); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "OuterBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + NestedTypeDto nested = + NestedTypeDtoBuilder.create() + .typeName("Helper") + .kind(NestedTypeDto.NestedTypeKind.CLASS) + .visibility(AccessModifier.PUBLIC) + .javadoc(JavadocDtoBuilder.create().format("Nested helper.").args().build()) + .build(); + MethodDto nestedMethod = + MethodDtoBuilder.create() + .methodName("assist") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PRIVATE) + .code("// nothing") + .build(); nested.addMethod(nestedMethod); classDef.addNestedType(nested); @@ -221,25 +257,33 @@ public void assist() { @Test void generatesMethodWithJavadocAnnotationsAndTypedParameters() throws Exception { - GenerationTargetClassDto classDef = new GenerationTargetClassDto(); - classDef.setTypeName(new TypeName("test", "RichBuilder")); - classDef.setClassAccessModifier(AccessModifier.PUBLIC); - classDef.setFormattingMode(FormattingMode.NONE); - - MethodDto method = new MethodDto("items", new TypeNameGeneric(List.class, String.class)); - method.setModifier(AccessModifier.PUBLIC); - JavadocDto javadoc = new JavadocDto("Adds items."); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "RichBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + JavadocDto javadoc = JavadocDtoBuilder.create().format("Adds items.").args().build(); javadoc.addParam("values", "items to add"); javadoc.addReturn("this builder"); - method.setJavadoc(javadoc); - AnnotationDto override_ = new AnnotationDto(); - override_.setAnnotationType(TypeName.of(Override.class)); + MethodDto method = + MethodDtoBuilder.create() + .methodName("items") + .returnType(new TypeNameGeneric(List.class, String.class)) + .modifier(AccessModifier.PUBLIC) + .javadoc(javadoc) + .code("return null;") + .build(); + AnnotationDto override_ = + AnnotationDtoBuilder.create().annotationType(TypeName.of(Override.class)).build(); method.addAnnotation(override_); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("values"); - param.setParameterTypeName(new TypeNameGeneric(List.class, String.class)); + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("values") + .parameterTypeName(new TypeNameGeneric(List.class, String.class)) + .build(); method.addParameter(param); - method.setCode("return null;"); classDef.addMethod(method); assertGeneratedSource( @@ -285,33 +329,47 @@ private static GenerationTargetClassDto personBuilderDefinition() { TypeName builderType = new TypeName("test", "PersonBuilder"); TypeName personType = new TypeName("test", "Person"); - GenerationTargetClassDto target = new GenerationTargetClassDto(); - target.setTypeName(builderType); - target.setClassAccessModifier(AccessModifier.PUBLIC); - target.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("target"); - field.setFieldType(personType); - field.setVisibility(AccessModifier.PRIVATE); - field.setLiteralInitializer("new Person()"); + GenerationTargetClassDto target = + GenerationTargetClassDtoBuilder.create() + .typeName(builderType) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("target") + .fieldType(personType) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("new Person()") + .build(); target.addClassField(field); - MethodDto name = new MethodDto("name", builderType); - name.setModifier(AccessModifier.PUBLIC); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("name"); - param.setParameterTypeName(TypeName.of(String.class)); + MethodDto name = + MethodDtoBuilder.create() + .methodName("name") + .returnType(builderType) + .modifier(AccessModifier.PUBLIC) + .code( + """ + target.setName(name); + return this;""") + .build(); + MethodParameterDto param = + MethodParameterDtoBuilder.create() + .parameterName("name") + .parameterTypeName(TypeName.of(String.class)) + .build(); name.addParameter(param); - name.setCode( - """ - target.setName(name); - return this;"""); target.addMethod(name); - MethodDto build = new MethodDto("build", personType); - build.setModifier(AccessModifier.PUBLIC); - build.setCode("return target;"); + MethodDto build = + MethodDtoBuilder.create() + .methodName("build") + .returnType(personType) + .modifier(AccessModifier.PUBLIC) + .code("return target;") + .build(); target.addMethod(build); return target; } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java index bee5f6e9..65c300d9 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -29,8 +29,10 @@ import java.util.List; import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.annotation.InterfaceName; import org.javahelpers.codegen.model.method.CodeTemplateDto; +import org.javahelpers.codegen.model.method.CodeTemplateDtoBuilder; import org.javahelpers.codegen.model.method.MethodCodePlaceholder; import org.javahelpers.codegen.model.method.MethodCodeStringPlaceholder; import org.javahelpers.codegen.model.method.MethodCodeTypePlaceholder; @@ -80,8 +82,8 @@ void mapType_rendersRawGenericWithoutArguments() { @Test void mapType_prependsTypeUseAnnotations() { TypeName annotated = TypeName.of(String.class); - AnnotationDto nonNull = new AnnotationDto(); - nonNull.setAnnotationType(new TypeName("test.anno", "NonNull")); + AnnotationDto nonNull = + AnnotationDtoBuilder.create().annotationType(new TypeName("test.anno", "NonNull")).build(); annotated.addAnnotation(nonNull); assertEquals("@NonNull String", RoasterMapper.mapType(annotated)); } @@ -106,15 +108,15 @@ void mapBoxedType_passesThroughNonPrimitives() { @Test void mapAnnotation_rendersMarkerWithoutMembers() { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType(new TypeName("test.anno", "Marker")); + AnnotationDto annotation = + AnnotationDtoBuilder.create().annotationType(new TypeName("test.anno", "Marker")).build(); assertEquals("@Marker", RoasterMapper.mapAnnotation(annotation)); } @Test void mapAnnotation_rendersValueMemberBareAndOthersNamed() { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType(new TypeName("test.anno", "Meta")); + AnnotationDto annotation = + AnnotationDtoBuilder.create().annotationType(new TypeName("test.anno", "Meta")).build(); annotation.addMember("value", "\"x\""); annotation.addMember("order", "3"); assertEquals("@Meta(\"x\", order = 3)", RoasterMapper.mapAnnotation(annotation)); @@ -122,14 +124,16 @@ void mapAnnotation_rendersValueMemberBareAndOthersNamed() { @Test void mapAnnotation_wrapsFailuresInMapperException() { - AnnotationDto annotation = new AnnotationDto(); - annotation.setAnnotationType( - new TypeName("test.anno", "Broken") { - @Override - public List getAnnotations() { - throw new IllegalStateException("boom"); - } - }); + AnnotationDto annotation = + AnnotationDtoBuilder.create() + .annotationType( + new TypeName("test.anno", "Broken") { + @Override + public List getAnnotations() { + throw new IllegalStateException("boom"); + } + }) + .build(); assertThrows(RoasterMapperException.class, () -> RoasterMapper.mapAnnotation(annotation)); } @@ -146,8 +150,8 @@ void mapInterfaceToTypeName_rendersSimpleAndParameterized() { @Test void mapInterfaceToTypeName_prependsTypeUseAnnotations() { InterfaceName iface = new InterfaceName("java.io", "Serializable"); - AnnotationDto marker = new AnnotationDto(); - marker.setAnnotationType(new TypeName("test.anno", "Tag")); + AnnotationDto marker = + AnnotationDtoBuilder.create().annotationType(new TypeName("test.anno", "Tag")).build(); iface.addAnnotation(marker); assertEquals("@Tag Serializable", RoasterMapper.mapInterfaceToTypeName(iface)); } @@ -168,8 +172,10 @@ public List getTypeParameters() { @Test void resolveCodeTemplate_replacesStringAndTypePlaceholders() { - CodeTemplateDto code = new CodeTemplateDto(); - code.setCodeFormat("return $name:S, $type:T, $boxed:B, $raw:N;"); + CodeTemplateDto code = + CodeTemplateDtoBuilder.create() + .codeFormat("return $name:S, $type:T, $boxed:B, $raw:N;") + .build(); code.addCodeArgument(new MethodCodeStringPlaceholder("name", "val")); code.addCodeArgument(new MethodCodeTypePlaceholder("type", TypeNamePrimitive.INT)); code.addCodeArgument(new MethodCodeTypePlaceholder("boxed", TypeNamePrimitive.INT)); @@ -180,17 +186,19 @@ void resolveCodeTemplate_replacesStringAndTypePlaceholders() { @Test void resolveCodeTemplate_rewritesTrackedValueFactoryNames() { - CodeTemplateDto code = new CodeTemplateDto(); - code.setCodeFormat( - "TrackedValue.initialValue(x); TrackedValue.changedValue(y); TrackedValue.unsetValue();"); + CodeTemplateDto code = + CodeTemplateDtoBuilder.create() + .codeFormat( + "TrackedValue.initialValue(x); TrackedValue.changedValue(y);" + + " TrackedValue.unsetValue();") + .build(); assertEquals( "initialValue(x); changedValue(y); unsetValue();", RoasterMapper.resolveCodeTemplate(code)); } @Test void resolveCodeTemplate_rejectsUnknownPlaceholderKinds() { - CodeTemplateDto code = new CodeTemplateDto(); - code.setCodeFormat("return $x:X;"); + CodeTemplateDto code = CodeTemplateDtoBuilder.create().codeFormat("return $x:X;").build(); code.addCodeArgument(new MethodCodePlaceholder("x", "v") {}); assertThrows(RoasterMapperException.class, () -> RoasterMapper.resolveCodeTemplate(code)); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index a2345289..ef7be6da 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -54,8 +54,11 @@ import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; @@ -147,36 +150,48 @@ protected GenerationTargetClassDto mapToTargetSpecification( MinimalTargetDefinition definition, CodegenConfiguration configuration, AnnotationProcessingContext ctx) { - GenerationTargetClassDto target = new GenerationTargetClassDto(); - target.setTypeName(definition.builderTypeName()); - target.setClassAccessModifier(AccessModifier.PUBLIC); - target.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("target"); - field.setFieldType(definition.sourceTypeName()); - field.setVisibility(AccessModifier.PRIVATE); - field.setLiteralInitializer("new " + definition.sourceTypeName().getClassName() + "()"); + GenerationTargetClassDto target = + GenerationTargetClassDtoBuilder.create() + .typeName(definition.builderTypeName()) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("target") + .fieldType(definition.sourceTypeName()) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("new " + definition.sourceTypeName().getClassName() + "()") + .build(); target.addClassField(field); for (ExecutableElement setter : definition.setters()) { String setterName = setter.getSimpleName().toString(); String methodName = StringUtils.uncapitalize(Strings.CI.removeStart(setterName, "set")); - MethodDto method = new MethodDto(methodName, definition.builderTypeName()); - method.setModifier(AccessModifier.PUBLIC); + MethodDto method = + MethodDtoBuilder.create() + .methodName(methodName) + .returnType(definition.builderTypeName()) + .modifier(AccessModifier.PUBLIC) + .code( + """ + target.$setterName:N($paramName:N); + return this;""") + .build(); String paramName = setter.getParameters().get(0).getSimpleName().toString(); method.addParameter(JavaLangMapper.map2MethodParameter(setter.getParameters().get(0), ctx)); - method.setCode( - """ - target.$setterName:N($paramName:N); - return this;"""); method.addArgument("setterName", setterName); method.addArgument("paramName", paramName); target.addMethod(method); } - MethodDto build = new MethodDto("build", definition.sourceTypeName()); - build.setModifier(AccessModifier.PUBLIC); - build.setCode("return target;"); + MethodDto build = + MethodDtoBuilder.create() + .methodName("build") + .returnType(definition.sourceTypeName()) + .modifier(AccessModifier.PUBLIC) + .code("return target;") + .build(); target.addMethod(build); return target; } From d8c56a7ec68b899e795ac600dfff07b060ca4859 Mon Sep 17 00:00:00 2001 From: AndreasIgelCC Date: Sat, 21 Nov 2026 14:50:13 +0100 Subject: [PATCH 04/15] refactor: rename @Ignore4BuilderGeneration to @IgnoreForBuilderGeneration (#416) --- ...n.java => IgnoreForBuilderGeneration.java} | 2 +- .../core/annotations/SimpleBuilder.java | 19 ++++++++++--------- .../core/annotations/SimpleBuilderFor.java | 4 ++-- .../annotations/SimpleMinimalBuilder.java | 4 ++-- docs/CONFIGURATION.md | 12 ++++++------ .../builders/processor/BuilderProcessor.java | 8 ++++---- .../analysis/BuilderScopeResolver.java | 6 +++--- .../mapstruct/MapStructBuilderProvider.java | 6 +++--- .../processing/BuilderDefinitionCreator.java | 2 +- .../BuilderAnnotationInheritanceTest.java | 8 ++++---- .../processor/BuilderScopeProcessingTest.java | 4 ++-- ...va => IgnoreForBuilderGenerationTest.java} | 18 +++++++++--------- .../processor/MapStructSpiProbeTest.java | 4 ++-- .../processor/SimpleBuilderForTest.java | 6 +++--- 14 files changed, 52 insertions(+), 51 deletions(-) rename core/src/main/java/org/javahelpers/simple/builders/core/annotations/{Ignore4BuilderGeneration.java => IgnoreForBuilderGeneration.java} (98%) rename processor/src/test/java/org/javahelpers/simple/builders/processor/{Ignore4BuilderGenerationTest.java => IgnoreForBuilderGenerationTest.java} (94%) diff --git a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/Ignore4BuilderGeneration.java b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/IgnoreForBuilderGeneration.java similarity index 98% rename from core/src/main/java/org/javahelpers/simple/builders/core/annotations/Ignore4BuilderGeneration.java rename to core/src/main/java/org/javahelpers/simple/builders/core/annotations/IgnoreForBuilderGeneration.java index 6d260bbf..ef929591 100644 --- a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/Ignore4BuilderGeneration.java +++ b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/IgnoreForBuilderGeneration.java @@ -48,4 +48,4 @@ */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) -public @interface Ignore4BuilderGeneration {} +public @interface IgnoreForBuilderGeneration {} diff --git a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilder.java b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilder.java index 00e39bd3..a771d68e 100644 --- a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilder.java +++ b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilder.java @@ -78,16 +78,17 @@ * *

    This annotation is {@link Inherited}: a subclass of an annotated type is treated as if it also * carried {@code @SimpleBuilder} for the purpose of triggering builder generation, unless it is - * explicitly excluded via {@link Ignore4BuilderGeneration}. The {@link Template} meta-annotation is - * {@link Inherited} as well, so custom template annotations that are themselves {@code @Inherited} - * propagate to subclasses in the same way. Configuration options declared on the parent's - * {@code @SimpleBuilder(options = ...)} or template are also inherited by subclass builders. + * explicitly excluded via {@link IgnoreForBuilderGeneration}. The {@link Template} meta-annotation + * is {@link Inherited} as well, so custom template annotations that are themselves + * {@code @Inherited} propagate to subclasses in the same way. Configuration options declared on the + * parent's {@code @SimpleBuilder(options = ...)} or template are also inherited by subclass + * builders. * *

    Related annotations: * *

      *
    • {@link IgnoreInBuilder} - exclude individual setters/constructors from builder generation - *
    • {@link Ignore4BuilderGeneration} - exclude a class/record from builder generation, even + *
    • {@link IgnoreForBuilderGeneration} - exclude a class/record from builder generation, even * when an inherited {@code @SimpleBuilder} or {@code @SimpleBuilder.Template} would otherwise * trigger it *
    @@ -95,7 +96,7 @@ * @see Options * @see Template * @see IgnoreInBuilder - * @see Ignore4BuilderGeneration + * @see IgnoreForBuilderGeneration */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) @@ -733,7 +734,7 @@ * precedence over the compiler option, so a type can include its own package even when the * global scope excludes it. Set on a {@link Template} annotation or a base class ({@code * SimpleBuilder} is {@code @Inherited}), it instead filters which inheriting types get a - * builder. To exclude a single type, prefer {@link Ignore4BuilderGeneration}. + * builder. To exclude a single type, prefer {@link IgnoreForBuilderGeneration}. * *

    Example: {@code "com.example.dto, com.example.shared"} * @@ -979,12 +980,12 @@ * *

      *
    • {@link IgnoreInBuilder} - exclude individual setters/constructors from builder generation - *
    • {@link Ignore4BuilderGeneration} - exclude a class/record from builder generation, even + *
    • {@link IgnoreForBuilderGeneration} - exclude a class/record from builder generation, even * when this template is inherited from a parent type *
    * * @see IgnoreInBuilder - * @see Ignore4BuilderGeneration + * @see IgnoreForBuilderGeneration */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.ANNOTATION_TYPE) diff --git a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilderFor.java b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilderFor.java index 81bcf7da..69d31444 100644 --- a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilderFor.java +++ b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleBuilderFor.java @@ -45,7 +45,7 @@ * constructors and setters, or package-visible members when the holder shares the target's package) * are used for builder generation. If no suitable construction mechanism is available, generation * fails with a compile-time error. The target type's own annotations are not consulted - the - * explicit declaration wins, so even an {@link Ignore4BuilderGeneration} on the target does not + * explicit declaration wins, so even an {@link IgnoreForBuilderGeneration} on the target does not * suppress generation. This annotation is intentionally not {@code @Inherited}: it declares * generation for exactly the types listed on the annotated element. * @@ -115,7 +115,7 @@ * * @see SimpleBuilder * @see SimpleBuilder.Options - * @see Ignore4BuilderGeneration + * @see IgnoreForBuilderGeneration */ @Target({ElementType.TYPE, ElementType.PACKAGE}) @Retention(RetentionPolicy.CLASS) diff --git a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleMinimalBuilder.java b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleMinimalBuilder.java index 52ade3f5..5b6d8a35 100644 --- a/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleMinimalBuilder.java +++ b/core/src/main/java/org/javahelpers/simple/builders/core/annotations/SimpleMinimalBuilder.java @@ -42,7 +42,7 @@ *

    This annotation is implemented purely as a {@link SimpleBuilder.Template} with every optional * feature set to {@link OptionState#DISABLED}. Because the template is {@link Inherited}, * subclasses of an annotated type also receive a minimal builder unless explicitly excluded by - * {@link Ignore4BuilderGeneration}. + * {@link IgnoreForBuilderGeneration}. * *

    Example: * @@ -67,7 +67,7 @@ * @see SimpleBuilder * @see SimpleBuilder.Template * @see SimpleBuilder.Options - * @see Ignore4BuilderGeneration + * @see IgnoreForBuilderGeneration */ @SimpleBuilder.Template( options = diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 65afe043..1e8c4e1d 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -156,19 +156,19 @@ public class ChildDto extends ParentDto { ... } ## Excluding Types from Builder Generation -You can opt a whole DTO out of builder generation with `@Ignore4BuilderGeneration`. This is useful when a class inherits `@SimpleBuilder` (which is itself `@Inherited`) or an `@SimpleBuilder.Template`-based annotation from a parent and you do not want a builder for that specific subclass. +You can opt a whole DTO out of builder generation with `@IgnoreForBuilderGeneration`. This is useful when a class inherits `@SimpleBuilder` (which is itself `@Inherited`) or an `@SimpleBuilder.Template`-based annotation from a parent and you do not want a builder for that specific subclass. ```java -import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; +import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; -@Ignore4BuilderGeneration +@IgnoreForBuilderGeneration public class IgnoredDto extends ParentDto { // No builder will be generated for IgnoredDto, even if ParentDto carries // @SimpleBuilder or an @Inherited template annotation. } ``` -A type marked with `@Ignore4BuilderGeneration` is treated as having **no builder available**. Other builders that reference it will fall back to plain setters instead of emitting nested-builder consumers. The annotation is intentionally **not** `@Inherited`, so it only suppresses the exact type it is placed on and does not cascade to further subclasses. +A type marked with `@IgnoreForBuilderGeneration` is treated as having **no builder available**. Other builders that reference it will fall back to plain setters instead of emitting nested-builder consumers. The annotation is intentionally **not** `@Inherited`, so it only suppresses the exact type it is placed on and does not cascade to further subclasses. ## Generating Builders for External Types @@ -200,7 +200,7 @@ public class ExternalBuildersProvider { Interfaces, abstract classes, enums and annotation types are skipped (a debug log lists each skip), and package scanning only sees *top-level* types - nested types keep requiring an explicit `value` entry. Only packages visible to the compilation can be resolved: an unresolvable package name produces a warning and is skipped. Types a package contributes are ordered by qualified name, so the generated set is deterministic. -The target type must be constructible through accessible Java APIs from the builder's package: it needs a visible type and an accessible constructor, otherwise generation fails with a compile-time diagnostic. The target type's own annotations are not consulted - the explicit declaration wins, so `@Ignore4BuilderGeneration` on the target does not suppress generation either. `@SimpleBuilderFor` is not `@Inherited`, and the provider class or package itself never gets a builder. +The target type must be constructible through accessible Java APIs from the builder's package: it needs a visible type and an accessible constructor, otherwise generation fails with a compile-time diagnostic. The target type's own annotations are not consulted - the explicit declaration wins, so `@IgnoreForBuilderGeneration` on the target does not suppress generation either. `@SimpleBuilderFor` is not `@Inherited`, and the provider class or package itself never gets a builder. `@SimpleBuilderFor` is `@Repeatable`: several declarations may be placed on the same holder or `package-info.java` when the listed types need different options - for example a different `packageName` per declaration: @@ -757,7 +757,7 @@ current compilation, so references to their builders do not require a type searc This option is an allowlist for whole packages: once set, builders are generated only inside the listed packages and every other package is excluded implicitly. Excluding a single package while generating everywhere else is not expressible; to exclude a single class, -use `@Ignore4BuilderGeneration` instead. The scope also applies to types that carry +use `@IgnoreForBuilderGeneration` instead. The scope also applies to types that carry `@SimpleBuilder` only through inheritance or a template annotation. #### `builderUsagePackages` diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/BuilderProcessor.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/BuilderProcessor.java index 50284486..c3722eb1 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/BuilderProcessor.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/BuilderProcessor.java @@ -63,7 +63,7 @@ import org.javahelpers.codegen.processing.ElementCollector; import org.javahelpers.codegen.processing.ElementGroups; import org.javahelpers.codegen.processing.ProcessorOptionRegistry; -import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; +import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; import org.javahelpers.simple.builders.core.annotations.SimpleBuilder.Template; import org.javahelpers.simple.builders.core.annotations.SimpleBuilderFor; import org.javahelpers.simple.builders.core.annotations.SimpleBuilderFors; @@ -102,7 +102,7 @@ public class BuilderProcessor /** * Which elements builders are generated for: types carrying {@code @SimpleBuilder} or a * user-defined {@code @SimpleBuilder.Template}-meta-annotated annotation (opt-out via - * {@code @Ignore4BuilderGeneration}), plus classes declaring external types with + * {@code @IgnoreForBuilderGeneration}), plus classes declaring external types with * {@code @SimpleBuilderFor}. */ private static final ElementCollector ELEMENT_COLLECTOR = @@ -112,7 +112,7 @@ public class BuilderProcessor selector .groupName(GROUP_ANNOTATED_ELEMENTS) .metaMarker(Template.class) - .optOutAnnotation(Ignore4BuilderGeneration.class)) + .optOutAnnotation(IgnoreForBuilderGeneration.class)) .selector( selector -> selector @@ -298,7 +298,7 @@ private List> planGenerationOfTypeByHolder( /** * Plans a builder for a single type listed in {@code @SimpleBuilderFor}, or reports on the holder * why no builder is generated for it. An explicit declaration always generates a builder - the - * target type's own annotations (such as {@code @Ignore4BuilderGeneration}) are not consulted, + * target type's own annotations (such as {@code @IgnoreForBuilderGeneration}) are not consulted, * and the {@code builderGenerationPackages} scope only filters annotated types, so a scope that * would exclude an explicitly named type is a contradictory configuration and only warns. */ diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java index f0780bf7..583ebfc6 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java @@ -43,7 +43,7 @@ import org.javahelpers.codegen.model.core.PackageScopes; import org.javahelpers.codegen.model.type.TypeInstantiation; import org.javahelpers.codegen.model.type.TypeName; -import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; +import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; import org.javahelpers.simple.builders.processor.model.core.BuilderConfiguration; import org.javahelpers.simple.builders.processor.model.type.PrefillCall; import org.javahelpers.simple.builders.processor.model.type.ResolvedBuilder; @@ -127,7 +127,7 @@ public BuilderScopeResolver(BuilderProcessingContext context) { * generated builder's package. The contract check is annotation-agnostic, so builders * generated with custom template annotations, external tools, or different suffixes are * supported. The referenced type must not be opted out with - * {@code @Ignore4BuilderGeneration}. + * {@code @IgnoreForBuilderGeneration}. * * * @param referencedType the type element being referenced as a field or collection element @@ -772,6 +772,6 @@ private static boolean isIgnoredForBuilderGeneration(TypeElement typeElement) { if (typeElement == null) { return false; } - return JavaLangAnalyser.findAnnotation(typeElement, Ignore4BuilderGeneration.class).isPresent(); + return JavaLangAnalyser.findAnnotation(typeElement, IgnoreForBuilderGeneration.class).isPresent(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java index fbba220b..044bca6a 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java @@ -42,7 +42,7 @@ import org.javahelpers.codegen.logging.SinkProcessingLogger; import org.javahelpers.codegen.model.core.PackageScopes; import org.javahelpers.codegen.processing.CompilerArgumentsReader; -import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; +import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; import org.javahelpers.simple.builders.processor.SimpleBuildersSpiIntegration; import org.javahelpers.simple.builders.processor.SimpleBuildersSpiIntegration.PublishedBuilder; @@ -275,13 +275,13 @@ private String packageNameOf(TypeElement beanElement) { /** * Whether {@code beanElement} is marked for builder generation ({@code @SimpleBuilder} or a - * builder template annotation, not opted out via {@code @Ignore4BuilderGeneration}), directly or + * builder template annotation, not opted out via {@code @IgnoreForBuilderGeneration}), directly or * through an inherited annotation. The marker decides the finished-state warning and whether an * unfinished miss can be answered as "no builder" — deferral and claiming never depend on it. */ private boolean isBuilderGenerationTarget(TypeElement beanElement) { Objects.requireNonNull(beanElement, "beanElement must not be null"); - if (JavaLangAnalyser.findAnnotation(beanElement, Ignore4BuilderGeneration.class).isPresent()) { + if (JavaLangAnalyser.findAnnotation(beanElement, IgnoreForBuilderGeneration.class).isPresent()) { return false; } for (AnnotationMirror mirror : elementUtils.getAllAnnotationMirrors(beanElement)) { diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java index c112222e..d241ef90 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java @@ -443,7 +443,7 @@ private static void removeMethodsFromBuilder( /** * Whether an annotation must not be copied onto generated code: either a simple-builders - * framework annotation (e.g. {@code @Default}, {@code @Ignore4BuilderGeneration}) — those + * framework annotation (e.g. {@code @Default}, {@code @IgnoreForBuilderGeneration}) — those * configure generation — or one of {@link #SKIPPED_COPIED_ANNOTATIONS}. * * @param annotation the annotation DTO diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java index 4b8a1fc7..4c738a11 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java @@ -168,7 +168,7 @@ public class ChildDto extends ParentDto { } /** - * A subclass annotated with {@code @Ignore4BuilderGeneration} must NOT get a builder even though + * A subclass annotated with {@code @IgnoreForBuilderGeneration} must NOT get a builder even though * it would otherwise inherit {@code @SimpleBuilder} from its parent. The parent's builder is * still generated. */ @@ -195,9 +195,9 @@ public class ParentDto { """ package test; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; - @Ignore4BuilderGeneration + @IgnoreForBuilderGeneration public class ChildDto extends ParentDto { } """); @@ -211,7 +211,7 @@ public class ChildDto extends ParentDto { } assertNoBuilderGenerated( compilation, "ChildDto", - "ChildDto builder should not have been generated due to @Ignore4BuilderGeneration"); + "ChildDto builder should not have been generated due to @IgnoreForBuilderGeneration"); } /** diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderScopeProcessingTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderScopeProcessingTest.java index 8e064810..c6bd2df3 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderScopeProcessingTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderScopeProcessingTest.java @@ -527,10 +527,10 @@ private static JavaFileObject optedOutDto() { return ProcessorTestUtils.forSource( """ package test; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; @SimpleBuilder - @Ignore4BuilderGeneration + @IgnoreForBuilderGeneration public class OptedOutDto { public OptedOutDto() {} } """); } diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/Ignore4BuilderGenerationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java similarity index 94% rename from processor/src/test/java/org/javahelpers/simple/builders/processor/Ignore4BuilderGenerationTest.java rename to processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java index a3b54fff..0cbf1ec5 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/Ignore4BuilderGenerationTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java @@ -39,12 +39,12 @@ import org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils; import org.junit.jupiter.api.Test; -/** Tests for the {@code @Ignore4BuilderGeneration} opt-out annotation. */ -class Ignore4BuilderGenerationTest { +/** Tests for the {@code @IgnoreForBuilderGeneration} opt-out annotation. */ +class IgnoreForBuilderGenerationTest { /** * (a) A subclass that inherits a template annotation from its parent and is annotated with - * {@code @Ignore4BuilderGeneration} must NOT get a builder, while the parent's builder is still + * {@code @IgnoreForBuilderGeneration} must NOT get a builder, while the parent's builder is still * generated. */ @Test @@ -87,9 +87,9 @@ public class ParentDto { """ package test; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; - @Ignore4BuilderGeneration + @IgnoreForBuilderGeneration public class ChildDto extends ParentDto { } """); @@ -104,11 +104,11 @@ public class ChildDto extends ParentDto { } assertNoBuilderGenerated( compilation, "ChildDto", - "ChildDto builder should not have been generated due to @Ignore4BuilderGeneration"); + "ChildDto builder should not have been generated due to @IgnoreForBuilderGeneration"); } /** - * (b) A DTO field whose type is annotated with {@code @Ignore4BuilderGeneration} must not trigger + * (b) A DTO field whose type is annotated with {@code @IgnoreForBuilderGeneration} must not trigger * nested-builder consumer generation in the referencing DTO. The referencing builder falls back * to a plain setter and must not reference a non-existent builder class. */ @@ -120,10 +120,10 @@ void referencedOptedOutDtoFallsBackToPlainSetter() { package test; import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; @SimpleBuilder - @Ignore4BuilderGeneration + @IgnoreForBuilderGeneration public class IgnoredDto { private String value; diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/MapStructSpiProbeTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/MapStructSpiProbeTest.java index 742c0c78..efc67bf7 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/MapStructSpiProbeTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/MapStructSpiProbeTest.java @@ -378,11 +378,11 @@ private static JavaFileObject ignoredDto() { """ package test; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; @SimpleBuilder - @Ignore4BuilderGeneration + @IgnoreForBuilderGeneration public class IgnoredDto { private String name; } diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/SimpleBuilderForTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/SimpleBuilderForTest.java index 17b2ff1d..857d6dc9 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/SimpleBuilderForTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/SimpleBuilderForTest.java @@ -230,8 +230,8 @@ void ignore4BuilderGenerationOnTarget_ExplicitDeclarationStillGenerates() { ProcessorTestUtils.forSource( """ package ext; - import org.javahelpers.simple.builders.core.annotations.Ignore4BuilderGeneration; - @Ignore4BuilderGeneration + import org.javahelpers.simple.builders.core.annotations.IgnoreForBuilderGeneration; + @IgnoreForBuilderGeneration public class OptedOut { public OptedOut() {} } @@ -242,7 +242,7 @@ public OptedOut() {} .compile(optedOut, holder("test", "Builders", "ext.OptedOut")); // The explicit @SimpleBuilderFor declaration wins - the target type's own annotations - // (including @Ignore4BuilderGeneration) are not consulted + // (including @IgnoreForBuilderGeneration) are not consulted assertThat(compilation).succeededWithoutWarnings(); String generated = ProcessorTestUtils.loadGeneratedSource(compilation, "OptedOutBuilder"); BuilderAsserts.assertGenerationSucceeded(compilation, "OptedOutBuilder", generated); From 548373a01ac85722fe07d87c47bc1d328c8f3474 Mon Sep 17 00:00:00 2001 From: AndreasIgelCC Date: Sat, 21 Nov 2026 14:56:24 +0100 Subject: [PATCH 05/15] fix: do not abort generation on reserved-word property names (#418) --- .../processor/model/core/BuilderFieldDto.java | 24 +++- .../processing/BuilderDefinitionCreator.java | 72 +++++++++- .../processor/ReservedPropertyNameTest.java | 125 ++++++++++++++++++ 3 files changed, 217 insertions(+), 4 deletions(-) create mode 100644 processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java index 718c990c..b3cc7f2d 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java @@ -45,6 +45,13 @@ public class BuilderFieldDto { /** Name of the field as it appears in the original DTO (used for method names and setters). */ private String originalFieldName; + /** + * Name of the DTO setter invoked for this field. {@code null} when the setter name can be derived + * from {@link #originalFieldName} via JavaBeans conventions; set explicitly when the real setter + * name deviates (e.g. {@code setStatic} for a field renamed to {@code isStatic}). + */ + private String setterName; + /** Name of the field as stored in the builder (may be renamed to avoid conflicts). */ private String fieldNameInBuilder; @@ -138,13 +145,24 @@ public void setFieldNameInBuilder(String fieldNameInBuilder) { } /** - * Gets the setter method name for this field. The setter name is derived from the original field - * name and follows JavaBean conventions (e.g., "userName" becomes "setUserName"). + * Gets the setter method name for this field. Defaults to the name derived from the original + * field name following JavaBean conventions (e.g., "userName" becomes "setUserName"); an + * explicitly set name takes precedence. * * @return the setter method name for this field (never null) */ public String getSetterName() { - return "set" + StringUtils.capitalize(originalFieldName); + return setterName != null ? setterName : "set" + StringUtils.capitalize(originalFieldName); + } + + /** + * Sets the setter method name to invoke for this field. Use this when the real setter name cannot + * be derived from {@link #getOriginalFieldName()} via JavaBeans conventions. + * + * @param setterName the setter method name, or {@code null} to fall back to the derived name + */ + public void setSetterName(String setterName) { + this.setterName = setterName; } /** diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java index c112222e..273f3440 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java @@ -40,9 +40,11 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.javahelpers.codegen.analysis.FieldAnnotationExtractor; @@ -699,6 +701,31 @@ private static Optional createFieldFromSetter( String fullJavaDoc = context.getDocComment(mth); String javaDocDescription = JavaLangAnalyser.extractParamJavaDoc(fullJavaDoc, fieldParameter); + // The setter-derived property name is used as-is for generated method and field names. + // setX -> x can yield a name that is not a legal Java identifier (e.g. setStatic -> + // "static"). Prefer a backing field with a legal name; if none exists, skip only this + // property instead of failing the whole target. + if (!SourceVersion.isName(fieldName)) { + Optional legalFieldName = + findLegalBackingFieldName(dtoTypeElement, fieldName, fieldParameter, context); + if (legalFieldName.isEmpty()) { + context.reportBasedOnStrictMode( + mth, + "Setter '%s' derives property name '%s', which is not a legal Java identifier. " + + "No backing field with a legal name was found, so this property is skipped. " + + "Rename the setter, add a backing field, or use @IgnoreInBuilder to silence " + + "this message.", + methodName, + fieldName); + return Optional.empty(); + } + context.debug( + "Setter '%s' derives property name '%s', which is not a legal Java identifier - " + + "using backing field name '%s' for builder members", + methodName, fieldName, legalFieldName.get()); + fieldName = legalFieldName.get(); + } + // Check for field name conflicts and rename if necessary String finalFieldName = resolveFieldNameConflict(fieldName, fieldParameter, fieldNameRegistry, context); @@ -720,6 +747,10 @@ private static Optional createFieldFromSetter( BuilderFieldDto field = result.get(); + // The real setter name is authoritative: the derived field name may have been renamed + // (e.g. setStatic -> "static" resolved to the backing field "isStatic"). + field.setSetterName(methodName); + // If no default was found on the setter parameter, check the field element itself // (annotations like @Default may be placed on the field rather than the setter param) if (field.getDefaultValue().isEmpty()) { @@ -764,6 +795,35 @@ private static Optional createFieldFromConstructor( return result; } + /** + * Finds a backing field on the DTO that corresponds to an illegal setter-derived property name. A + * field cannot itself be named after a keyword, so the legal candidates are the JavaBeans {@code + * is}-prefixed boolean convention: a field {@code isX} maps to property {@code x} the same way + * setter {@code setX} does (e.g. field {@code isStatic} for setter {@code setStatic}). + * + * @param dtoTypeElement the DTO type declaring the setter + * @param propertyName the illegal property name derived from the setter (e.g. {@code "static"}) + * @param fieldParameter the setter parameter, used to verify the field type matches + * @param context processing context + * @return the legal backing field name, or empty if no matching field exists + */ + private static Optional findLegalBackingFieldName( + TypeElement dtoTypeElement, + String propertyName, + VariableElement fieldParameter, + BuilderProcessingContext context) { + for (VariableElement field : ElementFilter.fieldsIn(dtoTypeElement.getEnclosedElements())) { + String name = field.getSimpleName().toString(); + if (name.length() > 2 + && name.startsWith("is") + && propertyName.equals(StringUtils.uncapitalize(name.substring(2))) + && context.isSameType(field.asType(), fieldParameter.asType())) { + return Optional.of(name); + } + } + return Optional.empty(); + } + /** * Resolves field name conflicts by checking the registry and renaming if necessary. If a field * with the same name already exists but has a different type, the new field is renamed by @@ -971,8 +1031,18 @@ private static void detectAndApplyFieldDeprecation( Optional recordComponent = JavaLangAnalyser.findRecordComponent(dtoTypeElement, fieldName); + // The setter name is usually set; after reserved-name fallback (e.g. + // setStatic -> field "isStatic") the name-derived lookup misses, so the enclosing + // executable of the parameter is used as an additional candidate — for setter fields + // that enclosing element IS the setter. Optional setter = - JavaLangAnalyser.findSetterForField(dtoTypeElement, fieldName, context); + JavaLangAnalyser.findSetterForField(dtoTypeElement, fieldName, context) + .or( + () -> + param.getEnclosingElement() instanceof ExecutableElement e + && e.getKind() == ElementKind.METHOD + ? Optional.of(e) + : Optional.empty()); // Search the relevant elements in priority order for the @Deprecated annotation to propagate. // Note: the backing field is intentionally NOT checked — it is uncommon to deprecate a diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java new file mode 100644 index 00000000..0d21658a --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java @@ -0,0 +1,125 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.simple.builders.processor; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; +import static org.javahelpers.simple.builders.processor.testing.BuilderAsserts.assertGenerationSucceeded; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.createCompiler; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.loadGeneratedSource; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.simpleBuilderClass; + +import com.google.testing.compile.Compilation; +import javax.tools.JavaFileObject; +import org.junit.jupiter.api.Test; + +/** + * Tests for setters whose JavaBeans-derived property name is a reserved Java identifier (issue + * #418). {@code setStatic} derives the property name {@code static}, {@code setDefault} derives + * {@code default} — both illegal as generated method names. Generation must not fail for the whole + * target: if a backing field with a legal name exists (e.g. {@code isStatic}), its name is used for + * builder members; otherwise only the offending property is skipped. + */ +class ReservedPropertyNameTest { + + private static final String PACKAGE = "pkg.reserved"; + + /** + * A setter {@code setStatic} with a backing field {@code isStatic} yields a builder whose helpers + * are named {@code isStatic(...)} while {@code build()} still invokes the real setter {@code + * setStatic(...)}. + */ + @Test + void reservedPropertyName_fallsBackToBackingFieldName() { + JavaFileObject dto = + simpleBuilderClass( + PACKAGE, + "StaticFlagDto", + """ + private boolean isStatic; + private String name; + public boolean isStatic() { return isStatic; } + public void setStatic(boolean isStatic) { this.isStatic = isStatic; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + """); + + Compilation compilation = createCompiler().compile(dto); + + String generated = loadGeneratedSource(compilation, "StaticFlagDtoBuilder"); + assertGenerationSucceeded(compilation, "StaticFlagDtoBuilder", generated); + assertContaining( + generated, "isStatic(boolean isStatic)", "name(String name)", "setStatic", "setName"); + } + + /** + * A setter {@code setDefault} without a legally named backing field is skipped with a warning; + * the other properties are still generated and compilation succeeds. + */ + @Test + void reservedPropertyName_withoutBackingField_isSkippedWithWarning() { + JavaFileObject dto = + simpleBuilderClass( + PACKAGE, + "DefaultFlagDto", + """ + private boolean defaultValue; + private String name; + public boolean isDefaultValue() { return defaultValue; } + public void setDefault(boolean defaultValue) { this.defaultValue = defaultValue; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + """); + + Compilation compilation = createCompiler().compile(dto); + + assertThat(compilation).succeeded(); + assertThat(compilation).hadWarningContaining("not a legal Java identifier"); + String generated = loadGeneratedSource(compilation, "DefaultFlagDtoBuilder"); + assertContaining(generated, "name(String name)"); + } + + /** + * In strict mode the skipped property is reported as an error instead of a warning, consistent + * with the existing strict diagnostics handling. + */ + @Test + void reservedPropertyName_strictMode_isError() { + JavaFileObject dto = + simpleBuilderClass( + PACKAGE, + "StrictDefaultDto", + """ + private boolean defaultValue; + public boolean isDefaultValue() { return defaultValue; } + public void setDefault(boolean defaultValue) { this.defaultValue = defaultValue; } + """); + + Compilation compilation = + createCompiler().withOptions("-Asimplebuilder.strict=true").compile(dto); + + assertThat(compilation).hadErrorContaining("not a legal Java identifier"); + } +} From e983a17b67e3de68ffb50711b6b47aa4f86c804e Mon Sep 17 00:00:00 2001 From: AndreasIgelCC Date: Sat, 21 Nov 2026 14:49:27 +0100 Subject: [PATCH 06/15] fix: qualify colliding simple type names in generated classes (#417) --- .../codegen/util/ImportCollector.java | 32 ++++- .../codegen/roaster/RoasterCodeGenerator.java | 27 +++- .../codegen/roaster/RoasterMapper.java | 117 +++++++++++++++--- .../roaster/RoasterCodeGeneratorTest.java | 28 +++++ .../RoasterCodeGeneratorEdgeCasesTest.java | 37 ++++++ 5 files changed, 219 insertions(+), 22 deletions(-) diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java index 1e53ccf2..9340bd41 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java @@ -25,8 +25,10 @@ package org.javahelpers.codegen.util; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; @@ -59,6 +61,7 @@ public class ImportCollector { private final Set imports = new LinkedHashSet<>(); + private final Map> typeUsageBySimpleName = new LinkedHashMap<>(); private final TypeName currentType; /** @@ -243,7 +246,20 @@ private void addBodyImports(MethodDto method) { * @param importStatement the import statement to add */ private void addImport(ImportStatement importStatement) { - if (importStatement == null || shouldSkipImport(importStatement)) { + if (importStatement == null) { + return; + } + // Track every concrete type usage by its simple name so callers can detect collisions + // between types of different packages (e.g. java.util.Date vs java.sql.Date). Tracking + // happens before the import filter: same-package and java.lang types resolve by simple + // name without an import and still participate in name binding. + if (importStatement instanceof RegularImport regularImport) { + TypeName usedType = regularImport.getType(); + typeUsageBySimpleName + .computeIfAbsent(usedType.getClassName(), k -> new LinkedHashSet<>()) + .add(usedType.getFullQualifiedName()); + } + if (shouldSkipImport(importStatement)) { return; } imports.add(importStatement); @@ -309,6 +325,20 @@ private void addImport(TypeName type) { addImport(new RegularImport(type)); } + /** + * Returns the simple type names that are used with more than one distinct qualified name in the + * collected class definition. Usages of such types must be emitted fully qualified to keep the + * generated source compilable (e.g. {@code java.util.Date} next to {@code java.sql.Date}). + * + * @return set of colliding simple names, empty if every simple name is unambiguous + */ + public Set getCollidingSimpleNames() { + return typeUsageBySimpleName.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + /** * Returns the collected import statements as a sorted set. * diff --git a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java index dd35dca0..166f0672 100644 --- a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java +++ b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java @@ -57,6 +57,7 @@ import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDto; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocTagDto; +import org.javahelpers.codegen.model.method.CodeTemplateDto; import org.javahelpers.codegen.model.method.ConstructorDto; import org.javahelpers.codegen.model.method.MethodCodeDto; import org.javahelpers.codegen.model.method.MethodDto; @@ -89,6 +90,13 @@ public class RoasterCodeGenerator implements ClassCodeGenerator { /** Reporter for problems found during generation; the reporter decides the severity. */ private final GenerationIssueReporter issueReporter; + /** + * Simple type names used by more than one distinct type in the class currently being generated + * (e.g. {@code java.util.Date} next to {@code java.sql.Date}). Usages of such types are emitted + * fully qualified; recomputed per {@link #generateClass} call. + */ + private Set collidingSimpleNames = Set.of(); + /** * Creates a code generator using the given generation environment. * @@ -151,6 +159,10 @@ public void generateClass(GenerationTargetClassDto classDef, SourceFormatter for private JavaClassSource buildClassSource(GenerationTargetClassDto classDef) { performanceTracker.startPhase(); + collidingSimpleNames = + new ImportCollector(classDef.getTypeName()) + .collectImports(classDef) + .getCollidingSimpleNames(); JavaClassSource source = createJavaClassSource(classDef); addClassMetadata(source, classDef); appendFields(source, classDef); @@ -211,7 +223,8 @@ private void addClassMetadata(JavaClassSource source, GenerationTargetClassDto c // Add interfaces for (InterfaceName interfaceName : classDef.getInterfaces()) { - source.addInterface(RoasterMapper.mapInterfaceToTypeName(interfaceName)); + source.addInterface( + RoasterMapper.mapInterfaceToTypeName(interfaceName, collidingSimpleNames)); } logger.debug("Class metadata added"); @@ -406,7 +419,7 @@ private void addGenericDeclarations( TypeVariableSource typeVariable = source.addTypeVariable(generic.getName()); if (CollectionUtils.isNotEmpty(generic.getUpperBounds())) { typeVariable.setBounds( - generic.getUpperBounds().stream().map(RoasterMapper::mapType).toArray(String[]::new)); + generic.getUpperBounds().stream().map(this::mapType).toArray(String[]::new)); } } } @@ -421,7 +434,7 @@ private void addGenericDeclarations( TypeVariableSource typeVariable = source.addTypeVariable(generic.getName()); if (CollectionUtils.isNotEmpty(generic.getUpperBounds())) { typeVariable.setBounds( - generic.getUpperBounds().stream().map(RoasterMapper::mapType).toArray(String[]::new)); + generic.getUpperBounds().stream().map(this::mapType).toArray(String[]::new)); } } } @@ -560,6 +573,14 @@ private void addParameter( applyAnnotations(parameter, paramDto.getAnnotations()); } + private String mapType(TypeName typeName) { + return RoasterMapper.mapType(typeName, collidingSimpleNames); + } + + private String resolveCodeTemplate(CodeTemplateDto codeDto) { + return RoasterMapper.resolveCodeTemplate(codeDto, collidingSimpleNames); + } + private String formatSource(String rawSource, SourceFormatter formatter) { return formatter.format(rawSource); } diff --git a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java index b64826a3..846ad70d 100644 --- a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java +++ b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.annotation.InterfaceName; @@ -47,30 +48,47 @@ public final class RoasterMapper { private RoasterMapper() {} /** - * Maps a type model to Java source code using fully qualified names for robustness. + * Maps a type model to Java source code. * * @param typeName type to map * @return Java source representation of the type */ public static String mapType(TypeName typeName) { + return mapType(typeName, Set.of()); + } + + /** + * Maps a type model to Java source code, qualifying types whose simple name is ambiguous within + * the generated class. + * + * @param typeName type to map + * @param collidingSimpleNames simple names used by more than one distinct type in the generated + * class; affected types are emitted fully qualified (e.g. {@code java.sql.Date} next to + * {@code java.util.Date}) + * @return Java source representation of the type + */ + public static String mapType(TypeName typeName, Set collidingSimpleNames) { String mappedType; if (typeName instanceof TypeNameVariable) { mappedType = typeName.getClassName(); } else if (typeName instanceof TypeNamePrimitive primitive) { mappedType = primitive.getFullQualifiedName(); } else if (typeName instanceof TypeNameArray arrayType) { - mappedType = mapType(arrayType.getTypeOfArray()) + "[]"; + mappedType = mapType(arrayType.getTypeOfArray(), collidingSimpleNames) + "[]"; } else if (typeName instanceof TypeNameGeneric genericType) { - mappedType = mapGenericType(genericType); + mappedType = mapGenericType(genericType, collidingSimpleNames); } else if (typeName instanceof TypeNameNested) { // Roaster splits a bare "Outer.Inner" into package "Outer" + class "Inner"; passing the // full qualified name makes it emit "import pkg.Outer.Inner" and use "Inner" in code. mappedType = typeName.getFullQualifiedName(); } else { - mappedType = typeName.getClassName(); + mappedType = + collidingSimpleNames.contains(typeName.getClassName()) + ? typeName.getFullQualifiedName() + : typeName.getClassName(); } - return prependTypeUseAnnotations(mappedType, typeName.getAnnotations()); + return prependTypeUseAnnotations(mappedType, typeName.getAnnotations(), collidingSimpleNames); } /** @@ -80,6 +98,18 @@ public static String mapType(TypeName typeName) { * @return boxed Java source representation of the type */ public static String mapBoxedType(TypeName typeName) { + return mapBoxedType(typeName, Set.of()); + } + + /** + * Maps a type to a boxed Java source representation, qualifying ambiguous simple names. + * + * @param typeName type to map + * @param collidingSimpleNames simple names used by more than one distinct type in the generated + * class + * @return boxed Java source representation of the type + */ + public static String mapBoxedType(TypeName typeName, Set collidingSimpleNames) { if (typeName instanceof TypeNamePrimitive primitive) { String boxedType = switch (primitive.getType()) { @@ -93,25 +123,28 @@ public static String mapBoxedType(TypeName typeName) { case SHORT -> Short.class.getSimpleName(); case VOID -> Void.class.getSimpleName(); }; - return prependTypeUseAnnotations(boxedType, typeName.getAnnotations()); + return prependTypeUseAnnotations(boxedType, typeName.getAnnotations(), collidingSimpleNames); } - return mapType(typeName); + return mapType(typeName, collidingSimpleNames); } - private static String mapGenericType(TypeNameGeneric genericType) { + private static String mapGenericType( + TypeNameGeneric genericType, Set collidingSimpleNames) { // Nested generic types keep the fully qualified name: Roaster parses "pkg.Outer.Pair" by // importing "pkg.Outer.Pair" and using "Pair" in code. The raw type's FQN is used because // TypeNameGeneric.getFullQualifiedName() already includes the type arguments. String baseName = genericType.isNestedType() ? genericType.getRawType().getFullQualifiedName() - : genericType.getClassName(); + : collidingSimpleNames.contains(genericType.getClassName()) + ? genericType.getFullQualifiedName() + : genericType.getClassName(); if (genericType.getInnerTypeArguments().isEmpty()) { return baseName; } String innerTypes = genericType.getInnerTypeArguments().stream() - .map(RoasterMapper::mapBoxedType) + .map(inner -> mapBoxedType(inner, collidingSimpleNames)) .reduce((a, b) -> a + ", " + b) .orElse(""); return baseName + "<" + innerTypes + ">"; @@ -124,8 +157,21 @@ private static String mapGenericType(TypeNameGeneric genericType) { * @return Java source representation of the annotation */ public static String mapAnnotation(AnnotationDto annotationDto) { + return mapAnnotation(annotationDto, Set.of()); + } + + /** + * Maps an annotation to source code, qualifying ambiguous simple names. + * + * @param annotationDto annotation DTO + * @param collidingSimpleNames simple names used by more than one distinct type in the generated + * class + * @return Java source representation of the annotation + */ + public static String mapAnnotation( + AnnotationDto annotationDto, Set collidingSimpleNames) { try { - String annotationType = mapType(annotationDto.getAnnotationType()); + String annotationType = mapType(annotationDto.getAnnotationType(), collidingSimpleNames); if (annotationDto.getMembers().isEmpty()) { return "@" + annotationType; } @@ -158,17 +204,34 @@ private static String mapAnnotationMember(Map.Entry member) { * @return source representation of the interface type */ public static String mapInterfaceToTypeName(InterfaceName interfaceName) { + return mapInterfaceToTypeName(interfaceName, Set.of()); + } + + /** + * Maps an interface name to Java source code, qualifying ambiguous simple names. + * + * @param interfaceName interface model + * @param collidingSimpleNames simple names used by more than one distinct type in the generated + * class + * @return source representation of the interface type + */ + public static String mapInterfaceToTypeName( + InterfaceName interfaceName, Set collidingSimpleNames) { try { - String qualifiedName = interfaceName.getSimpleName(); + String qualifiedName = + collidingSimpleNames.contains(interfaceName.getSimpleName()) + ? interfaceName.getPackageName() + "." + interfaceName.getSimpleName() + : interfaceName.getSimpleName(); if (interfaceName.hasTypeParameters()) { String typeParameters = interfaceName.getTypeParameters().stream() - .map(RoasterMapper::mapType) + .map(t -> mapType(t, collidingSimpleNames)) .reduce((a, b) -> a + ", " + b) .orElse(""); qualifiedName = qualifiedName + "<" + typeParameters + ">"; } - return prependTypeUseAnnotations(qualifiedName, interfaceName.getAnnotations()); + return prependTypeUseAnnotations( + qualifiedName, interfaceName.getAnnotations(), collidingSimpleNames); } catch (Exception e) { throw new RoasterMapperException( e, "Failed to map interface %s: %s", interfaceName.toString(), e.getMessage()); @@ -185,6 +248,20 @@ public static String mapInterfaceToTypeName(InterfaceName interfaceName) { * @return resolved Java source code */ public static String resolveCodeTemplate(CodeTemplateDto codeDto) { + return resolveCodeTemplate(codeDto, Set.of()); + } + + /** + * Resolves the JavaPoet-style named template used in CodeTemplateDto to plain Java source code, + * qualifying ambiguous simple names. + * + * @param codeDto code template DTO + * @param collidingSimpleNames simple names used by more than one distinct type in the generated + * class + * @return resolved Java source code + */ + public static String resolveCodeTemplate( + CodeTemplateDto codeDto, Set collidingSimpleNames) { String code = codeDto.getCodeFormat(); for (MethodCodePlaceholder placeHolderValue : codeDto.getCodeArguments()) { String label = placeHolderValue.getLabel(); @@ -193,8 +270,12 @@ public static String resolveCodeTemplate(CodeTemplateDto codeDto) { code = code.replace("$" + label + ":L", stringPlaceholder.getValue()); code = code.replace("$" + label + ":S", quote(stringPlaceholder.getValue())); } else if (placeHolderValue instanceof MethodCodeTypePlaceholder typePlaceholder) { - code = code.replace("$" + label + ":T", mapType(typePlaceholder.getValue())); - code = code.replace("$" + label + ":B", mapBoxedType(typePlaceholder.getValue())); + code = + code.replace( + "$" + label + ":T", mapType(typePlaceholder.getValue(), collidingSimpleNames)); + code = + code.replace( + "$" + label + ":B", mapBoxedType(typePlaceholder.getValue(), collidingSimpleNames)); } else { throw new RoasterMapperException( "Unsupported placeholder type: %s", placeHolderValue.getClass().getName()); @@ -235,13 +316,13 @@ public static String packageNameOf(String fqn) { } private static String prependTypeUseAnnotations( - String baseType, List annotations) { + String baseType, List annotations, Set collidingSimpleNames) { if (CollectionUtils.isEmpty(annotations)) { return baseType; } String prefix = annotations.stream() - .map(RoasterMapper::mapAnnotation) + .map(a -> mapAnnotation(a, collidingSimpleNames)) .reduce((a, b) -> a + " " + b) .orElse(""); return prefix + " " + baseType; diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index ed02a2d7..a1df7777 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -85,6 +85,34 @@ void writesFileUnderQualifiedName() throws Exception { assertEquals("mem:///com/example/EmptyBuilder.java", generate(empty).writtenUri().toString()); } + @Test + void qualifiesCollidingSimpleTypeNames() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "DateBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + + ClassFieldDto utilDate = new ClassFieldDto(); + utilDate.setFieldName("utilDate"); + utilDate.setFieldType(new TypeName("java.util", "Date")); + classDef.addClassField(utilDate); + + ClassFieldDto sqlDate = new ClassFieldDto(); + sqlDate.setFieldName("sqlDate"); + sqlDate.setFieldType(new TypeName("java.sql", "Date")); + classDef.addClassField(sqlDate); + + assertGeneratedSource( + """ + package test; + import java.sql.Date; + public class DateBuilder { + private java.util.Date utilDate; + private Date sqlDate; + }""", + classDef); + } + @Test void generatesClassMetadataJavadocAndAnnotations() throws Exception { GenerationTargetClassDto classDef = new GenerationTargetClassDto(); diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorEdgeCasesTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorEdgeCasesTest.java index 07bb34c0..4317e5f7 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorEdgeCasesTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorEdgeCasesTest.java @@ -362,4 +362,41 @@ public class GenericDto { "public GenericDto build()", "public static GenericDtoBuilder create()"); } + + /** + * Tests that fields whose types share a simple name but live in different packages generate a + * compilable builder. + * + *

    Regression test for the {@code java.util.Date} / {@code java.sql.Date} collision: the + * generated builder must qualify at least one of the two types instead of emitting the ambiguous + * simple name for both. + */ + @Test + void shouldQualifyCollidingSimpleTypeNames() { + JavaFileObject sourceFile = + JavaFileObjects.forSourceString( + "test.DateDto", + """ + package test; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + + @SimpleBuilder + public class DateDto { + private java.util.Date utilDateTestField; + private java.sql.Date sqlDateTestField; + public java.util.Date getUtilDateTestField() { return utilDateTestField; } + public void setUtilDateTestField(java.util.Date d) { this.utilDateTestField = d; } + public java.sql.Date getSqlDateTestField() { return sqlDateTestField; } + public void setSqlDateTestField(java.sql.Date d) { this.sqlDateTestField = d; } + } + """); + + Compilation compilation = ProcessorTestUtils.createCompiler().compile(sourceFile); + + String generatedCode = loadGeneratedSource(compilation, "DateDtoBuilder"); + assertGenerationSucceeded(compilation, "DateDtoBuilder", generatedCode); + assertTrue( + generatedCode.contains("java.util.Date") || generatedCode.contains("java.sql.Date"), + () -> "colliding types must be qualified in the generated builder, was: " + generatedCode); + } } From d4d1455516942c683459a8441a0da506364578e6 Mon Sep 17 00:00:00 2001 From: AndreasIgelCC Date: Sun, 22 Nov 2026 08:15:08 +0100 Subject: [PATCH 07/15] Add shared generator conformance suite with ServiceLoader backend discovery Introduces GeneratorConformanceTest in codegen-testing: backend-agnostic contract tests that verify every ClassCodeGenerator emits compilable, semantically correct Java source for a common set of model fixtures (fields/methods/ctors, generics, collections, nested types, annotations, code templates, static imports, colliding type names). Backends bind via the TestBackendProvider SPI discovered through ServiceLoader, so each generator module opts in with a provider class and services file - no test code is duplicated per backend. Parameterized invocations are named after the provider so failures identify the failing generator. codegen-roaster registers RoasterTestBackendProvider and scans the suite from the codegen-testing jar via surefire dependenciesToScan. This is the acceptance harness needed before adding further generator implementations (issue #366). Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- codegen-roaster/pom.xml | 6 + .../roaster/RoasterTestBackendProvider.java | 52 ++ ...elpers.codegen.testing.TestBackendProvider | 1 + .../testing/GeneratorConformanceTest.java | 447 ++++++++++++++++++ .../codegen/testing/TestBackendProvider.java | 68 +++ .../testing/TestTypeUseAnnotation.java | 45 ++ 6 files changed, 619 insertions(+) create mode 100644 codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java create mode 100644 codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java diff --git a/codegen-roaster/pom.xml b/codegen-roaster/pom.xml index 886f27af..6f40ac6a 100644 --- a/codegen-roaster/pom.xml +++ b/codegen-roaster/pom.xml @@ -145,6 +145,12 @@ org.apache.maven.plugins maven-surefire-plugin ${plugin.maven.surefire.version} + + + + io.github.java-helpers.codegen:codegen-testing + + diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java new file mode 100644 index 00000000..cfae9519 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java @@ -0,0 +1,52 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.roaster; + +import org.javahelpers.codegen.CodegenBackend; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.logging.ProcessingLogger; +import org.javahelpers.codegen.testing.TestBackendProvider; + +/** + * Registers the Roaster backend for the shared generator conformance suite (loaded via {@link + * java.util.ServiceLoader}). + */ +public class RoasterTestBackendProvider implements TestBackendProvider { + + @Override + public String name() { + return "Roaster"; + } + + @Override + public CodegenBackend create(GenerationEnvironment environment, ProcessingLogger logger) { + return new RoasterBackend(environment, logger, null); + } + + @Override + public String toString() { + return name(); + } +} diff --git a/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider b/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider new file mode 100644 index 00000000..f265fa8e --- /dev/null +++ b/codegen-roaster/src/test/resources/META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider @@ -0,0 +1 @@ +org.javahelpers.codegen.roaster.RoasterTestBackendProvider diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java new file mode 100644 index 00000000..42b9e4a8 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java @@ -0,0 +1,447 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.ServiceLoader; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import org.javahelpers.codegen.ClassCodeGenerator; +import org.javahelpers.codegen.CodegenBackend; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; +import org.javahelpers.codegen.model.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNamePrimitive; +import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Shared conformance suite for {@link ClassCodeGenerator} implementations. + * + *

    Backends under test are discovered via {@link ServiceLoader}: each backend module registers a + * {@link TestBackendProvider} on its test classpath (see {@link TestBackendProvider} for the + * contract). Every test in this class then runs once per discovered backend, with the provider's + * {@link TestBackendProvider#name() name} in the test display name — so a failure always identifies + * the failing generator. New backends (issue #366) gain identical coverage without writing or + * copying any test. + * + *

    Each fixture is asserted on two levels: + * + *

      + *
    • Compilability — the emitted source is fed through {@code javac} and must compile + * without errors + *
    • Semantic content — backend-independent fragments (declaration kinds, member names, + * disambiguated type references), not exact formatting + *
    + * + *

    Backend modules must configure surefire's {@code dependenciesToScan} to include {@code + * codegen-testing} so this class is discovered from the dependency jar. + */ +public class GeneratorConformanceTest { + + private static final String PACKAGE = "it.conformance"; + private static final Path WORK_DIR = Path.of("target", "generator-conformance"); + + /** + * Provides all backends registered via {@link ServiceLoader}, named for the test display. + * + * @return one named argument per discovered {@link TestBackendProvider} + */ + static Stream backends() { + return ServiceLoader.load(TestBackendProvider.class).stream() + .map(provider -> Arguments.of(Named.of(provider.get().name(), provider.get()))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void simpleClassWithFieldsMethodsAndConstructor_compiles(TestBackendProvider backend) + throws Exception { + GenerationTargetClassDto classDef = baseClass("SimpleClass"); + + addField(classDef, "name", TypeName.of(String.class)); + addField(classDef, "age", TypeNamePrimitive.INT); + addField(classDef, "active", TypeNamePrimitive.BOOLEAN); + + var ctor = ConstructorDtoBuilder.create().visibility(AccessModifier.PUBLIC).build(); + ctor.getMethodCodeDto().setCodeFormat("this.name = name;"); + ctor.addParameter(param("name", TypeName.of(String.class))); + classDef.addConstructor(ctor); + + classDef.addMethod( + MethodDtoBuilder.create() + .methodName("describe") + .returnType(TypeName.of(String.class)) + .modifier(AccessModifier.PUBLIC) + .code("return name + \"#\" + age;") + .build()); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, "public class SimpleClass", "String describe(", "SimpleClass(String name)"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("GenericBox"); + var generic = GenericParameterDtoBuilder.create().name("T").build(); + generic.addUpperBound( + new TypeNameGeneric(TypeName.of(Comparable.class), new TypeNameVariable("T"))); + classDef.addGeneric(generic); + + MethodDto method = + MethodDtoBuilder.create() + .methodName("pick") + .returnType(new TypeNameVariable("R")) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return first;") + .build(); + var methodGeneric = GenericParameterDtoBuilder.create().name("R").build(); + methodGeneric.addUpperBound(TypeName.of(Number.class)); + method.addGenericParameter(methodGeneric); + method.addParameter(param("first", new TypeNameVariable("R"))); + method.addParameter(param("second", new TypeNameVariable("R"))); + classDef.addMethod(method); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining(source, "class GenericBox>", ""); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("ContainerClass"); + + addField(classDef, "names", new TypeNameGeneric(List.class, String.class)); + addField( + classDef, + "scores", + new TypeNameGeneric( + TypeName.of(java.util.Map.class), + TypeName.of(String.class), + TypeName.of(Integer.class))); + addField(classDef, "numbers", new TypeNameArray(TypeNamePrimitive.INT)); + addField(classDef, "nickname", new TypeNameGeneric(java.util.Optional.class, String.class)); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, "List names", "Map scores", "Optional nickname"); + } + + /** + * Two field types sharing the simple name {@code Date} from different packages must never be + * rendered ambiguously — at least one of them has to stay fully qualified (issue #417). + */ + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void collidingSimpleNames_areDisambiguated(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("CollidingDates"); + + addField(classDef, "utilDate", new TypeName("java.util", "Date")); + addField(classDef, "sqlDate", new TypeName("java.sql", "Date")); + + MethodDto method = + MethodDtoBuilder.create() + .methodName("touch") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .code("if (when == null) { return; }") + .build(); + method.addParameter(param("when", new TypeName("java.sql", "Date"))); + classDef.addMethod(method); + + String source = generate(backend, classDef); + assertTrue( + source.contains("java.util.Date") || source.contains("java.sql.Date"), + () -> "colliding Date types must be qualified in the generated source, was:\n" + source); + assertCompiles(classDef, source); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void nestedTypesWithMembers_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("OuterClass"); + + NestedTypeDto nested = + NestedTypeDtoBuilder.create() + .typeName("Helper") + .kind(NestedTypeDto.NestedTypeKind.CLASS) + .visibility(AccessModifier.PUBLIC) + .build(); + nested.addMethod( + MethodDtoBuilder.create() + .methodName("assist") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .code("int touched = 0;") + .build()); + classDef.addNestedType(nested); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining(source, "class Helper", "void assist("); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void annotationsOnClassMembersAndTypeUse_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("AnnotatedClass"); + + AnnotationDto deprecated = + AnnotationDtoBuilder.create().annotationType(TypeName.of(Deprecated.class)).build(); + deprecated.addMember("since", "\"0.9\""); + deprecated.addMember("forRemoval", "true"); + classDef.addClassAnnotation(deprecated); + + AnnotationDto generated = + AnnotationDtoBuilder.create() + .annotationType(new TypeName("javax.annotation.processing", "Generated")) + .build(); + generated.addMember("value", "\"conformance\""); + classDef.addClassAnnotation(generated); + + TypeName annotatedString = TypeName.of(String.class); + annotatedString + .getAnnotations() + .add( + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(TestTypeUseAnnotation.class)) + .build()); + addField(classDef, "flagged", annotatedString); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining(source, "@Deprecated", "@Generated", "TestTypeUseAnnotation"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void codeTemplatePlaceholders_resolve(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("TemplateClass"); + + MethodDto method = + MethodDtoBuilder.create() + .methodName("parse") + .returnType(TypeNamePrimitive.LONG) + .modifier(AccessModifier.PUBLIC) + .build(); + method + .getMethodCodeDto() + .setCodeFormat("int $l:L = 0;\n$b:B box = null;\nreturn $t:T.parseLong($s:S);"); + method.getMethodCodeDto().addArgument("l", "count"); + method.getMethodCodeDto().addArgument("b", TypeNamePrimitive.INT); + method.getMethodCodeDto().addArgument("t", TypeName.of(Long.class)); + method.getMethodCodeDto().addArgument("s", "42"); + classDef.addMethod(method); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining(source, "int count = 0", "Integer box", "Long.parseLong(\"42\")"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void superTypeAndInterfaces_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("DerivedClass"); + classDef.setSuperType(new TypeNameGeneric(java.util.ArrayList.class, String.class)); + classDef.addInterface(new InterfaceName("java.io", "Serializable")); + classDef.addInterface(new InterfaceName("java.lang", "Cloneable")); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining(source, "extends ArrayList", "implements Serializable, Cloneable"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("FactoryClass"); + classDef.addStaticImport(java.util.Collections.class, "emptyList"); + + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("initial") + .fieldType(new TypeNameGeneric(List.class, String.class)) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("emptyList()") + .build(); + classDef.addClassField(field); + + MethodDto factory = + MethodDtoBuilder.create() + .methodName("of") + .returnType(TypeNamePrimitive.INT) + .modifier(AccessModifier.PUBLIC) + .isStatic(true) + .code("return names.length;") + .build(); + factory.addParameter(param("names", new TypeNameArray(TypeName.of(String.class)))); + classDef.addMethod(factory); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + // array types in parameter position may render as "String[]" or normalized "String..." + assertTrue( + source.contains("String[] names") || source.contains("String... names"), + () -> "array parameter must be rendered as array or varargs, was:\n" + source); + assertContaining(source, "import static"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exception { + GenerationTargetClassDto classDef = baseClass("DocumentedClass"); + classDef.setClassJavadoc( + JavadocDtoBuilder.create().format("Documented conformance class.").args().build()); + + var javadoc = JavadocDtoBuilder.create().format("Echoes the value.").args().build(); + javadoc.addParam("value", "the input"); + javadoc.addReturn("the echoed value"); + MethodDto method = + MethodDtoBuilder.create() + .methodName("echo") + .returnType(TypeName.of(String.class)) + .modifier(AccessModifier.PUBLIC) + .javadoc(javadoc) + .code("return value;") + .build(); + method.addParameter(param("value", TypeName.of(String.class))); + classDef.addMethod(method); + + String source = generate(backend, classDef); + assertContaining(source, "Documented conformance class.", "@param", "@return"); + } + + /** Generates {@code classDef} through {@code provider}'s backend and returns the source text. */ + private String generate(TestBackendProvider provider, GenerationTargetClassDto classDef) + throws Exception { + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(); + CodegenBackend backend = provider.create(env, env.getLogger()); + backend.generator().generateClass(classDef, backend.formatterFor(FormattingMode.NONE)); + return env.generatedSource(); + } + + /** + * Compiles {@code source} with the JDK compiler on the test classpath; fails when javac reports + * an error. + */ + private void assertCompiles(GenerationTargetClassDto classDef, String source) throws IOException { + String qualifiedName = classDef.getTypeName().getFullQualifiedName(); + Path sourceFile = WORK_DIR.resolve(qualifiedName.replace('.', '/') + ".java"); + Files.createDirectories(sourceFile.getParent()); + Files.writeString(sourceFile, source, StandardCharsets.UTF_8); + Path classes = Files.createDirectories(WORK_DIR.resolve("classes")); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fileManager = + compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { + boolean ok = + compiler + .getTask( + null, + fileManager, + diagnostics, + List.of( + "-proc:none", + "-classpath", + System.getProperty("java.class.path"), + "-d", + classes.toString()), + null, + fileManager.getJavaFileObjects(sourceFile)) + .call(); + assertTrue( + ok, + () -> + "generated source for " + + qualifiedName + + " must compile:\n" + + diagnostics.getDiagnostics().stream() + .map(Object::toString) + .collect(Collectors.joining("\n")) + + "\n--- source ---\n" + + source); + } + } + + private static GenerationTargetClassDto baseClass(String simpleName) { + return GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName(PACKAGE, simpleName)) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + } + + private static void addField(GenerationTargetClassDto classDef, String name, TypeName type) { + classDef.addClassField( + ClassFieldDtoBuilder.create() + .fieldName(name) + .fieldType(type) + .visibility(AccessModifier.PRIVATE) + .build()); + } + + private static MethodParameterDto param(String name, TypeName type) { + return MethodParameterDtoBuilder.create().parameterName(name).parameterTypeName(type).build(); + } +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java new file mode 100644 index 00000000..41ae3275 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java @@ -0,0 +1,68 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import org.javahelpers.codegen.CodegenBackend; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.logging.ProcessingLogger; + +/** + * Service-provider interface binding a {@link CodegenBackend} implementation to the shared + * generator conformance suite. + * + *

    Every backend module (Roaster today; JavaPoet or the built-in lightweight generator planned in + * issue #366) registers exactly one implementation in its test sources: + * + *

      + *
    • a provider class implementing this interface + *
    • a {@code META-INF/services/org.javahelpers.codegen.testing.TestBackendProvider} file in + * test resources listing it + *
    + * + *

    {@link GeneratorConformanceTest} discovers providers via {@link java.util.ServiceLoader}, so a + * new backend gains the complete conformance coverage by dropping its provider on the test + * classpath — no test code needs to be written or copied. + */ +public interface TestBackendProvider { + + /** + * Short display name of the backend under test (e.g. {@code "Roaster"}). Shown in the test name + * of every conformance test, so failures identify the failing backend. Implementations should + * also return this name from {@link #toString()} so the parameterized invocation renders as the + * backend name in all test reporters. + * + * @return the backend display name + */ + String name(); + + /** + * Creates the backend under test. + * + * @param environment the testing environment capturing generated source + * @param logger the processing logger to pass to the backend + * @return a ready-to-use backend instance + */ + CodegenBackend create(GenerationEnvironment environment, ProcessingLogger logger); +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java new file mode 100644 index 00000000..36ffa813 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestTypeUseAnnotation.java @@ -0,0 +1,45 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marker annotation for generator conformance fixtures. Carries no semantics — it exists so that + * generated sources can annotate elements and type usages with a real, classpath-resolvable + * annotation. + */ +@Target({ + ElementType.TYPE, + ElementType.FIELD, + ElementType.METHOD, + ElementType.PARAMETER, + ElementType.TYPE_USE +}) +@Retention(RetentionPolicy.RUNTIME) +public @interface TestTypeUseAnnotation {} From 4bb753bf3cd10ebe00e133992e7aaa197cef33bf Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:28:59 +0000 Subject: [PATCH 08/15] style: apply google-java-format to renamed references --- .../processor/analysis/BuilderScopeResolver.java | 3 ++- .../processor/mapstruct/MapStructBuilderProvider.java | 9 +++++---- .../processor/BuilderAnnotationInheritanceTest.java | 6 +++--- .../processor/IgnoreForBuilderGenerationTest.java | 6 +++--- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java index 583ebfc6..7d0477a8 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/analysis/BuilderScopeResolver.java @@ -772,6 +772,7 @@ private static boolean isIgnoredForBuilderGeneration(TypeElement typeElement) { if (typeElement == null) { return false; } - return JavaLangAnalyser.findAnnotation(typeElement, IgnoreForBuilderGeneration.class).isPresent(); + return JavaLangAnalyser.findAnnotation(typeElement, IgnoreForBuilderGeneration.class) + .isPresent(); } } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java index 044bca6a..940bd830 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/mapstruct/MapStructBuilderProvider.java @@ -275,13 +275,14 @@ private String packageNameOf(TypeElement beanElement) { /** * Whether {@code beanElement} is marked for builder generation ({@code @SimpleBuilder} or a - * builder template annotation, not opted out via {@code @IgnoreForBuilderGeneration}), directly or - * through an inherited annotation. The marker decides the finished-state warning and whether an - * unfinished miss can be answered as "no builder" — deferral and claiming never depend on it. + * builder template annotation, not opted out via {@code @IgnoreForBuilderGeneration}), directly + * or through an inherited annotation. The marker decides the finished-state warning and whether + * an unfinished miss can be answered as "no builder" — deferral and claiming never depend on it. */ private boolean isBuilderGenerationTarget(TypeElement beanElement) { Objects.requireNonNull(beanElement, "beanElement must not be null"); - if (JavaLangAnalyser.findAnnotation(beanElement, IgnoreForBuilderGeneration.class).isPresent()) { + if (JavaLangAnalyser.findAnnotation(beanElement, IgnoreForBuilderGeneration.class) + .isPresent()) { return false; } for (AnnotationMirror mirror : elementUtils.getAllAnnotationMirrors(beanElement)) { diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java index 4c738a11..0cccaa2a 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderAnnotationInheritanceTest.java @@ -168,9 +168,9 @@ public class ChildDto extends ParentDto { } /** - * A subclass annotated with {@code @IgnoreForBuilderGeneration} must NOT get a builder even though - * it would otherwise inherit {@code @SimpleBuilder} from its parent. The parent's builder is - * still generated. + * A subclass annotated with {@code @IgnoreForBuilderGeneration} must NOT get a builder even + * though it would otherwise inherit {@code @SimpleBuilder} from its parent. The parent's builder + * is still generated. */ @Test void subclassOptedOutViaIgnoreDoesNotGetInheritedBuilder() { diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java index 0cbf1ec5..9a1a2bb4 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/IgnoreForBuilderGenerationTest.java @@ -108,9 +108,9 @@ public class ChildDto extends ParentDto { } } /** - * (b) A DTO field whose type is annotated with {@code @IgnoreForBuilderGeneration} must not trigger - * nested-builder consumer generation in the referencing DTO. The referencing builder falls back - * to a plain setter and must not reference a non-existent builder class. + * (b) A DTO field whose type is annotated with {@code @IgnoreForBuilderGeneration} must not + * trigger nested-builder consumer generation in the referencing DTO. The referencing builder + * falls back to a plain setter and must not reference a non-existent builder class. */ @Test void referencedOptedOutDtoFallsBackToPlainSetter() { From 6c9d39dbeef20eb11d7a4a37bfb56963447526f6 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:53:41 +0000 Subject: [PATCH 09/15] Require field names for Javadoc example value helpers --- .../builders/example/BookDtoBuilder.java | 4 +- .../field/ListConsumerGenerator.java | 1 + .../field/SetConsumerGenerator.java | 1 + .../generators/util/JavadocExampleValues.java | 31 +++----- .../generators/util/MethodGeneratorUtil.java | 79 ++----------------- .../processor/BuilderJavadocExampleTest.java | 2 +- .../ComprehensiveFeatureIntegrationTest.java | 10 +-- .../processor/JavadocExampleValuesTest.java | 61 ++++++++++++++ 8 files changed, 89 insertions(+), 100 deletions(-) create mode 100644 processor/src/test/java/org/javahelpers/simple/builders/processor/JavadocExampleValuesTest.java diff --git a/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java index 3332d079..504dbf11 100644 --- a/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java +++ b/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java @@ -33,7 +33,7 @@ * .genres(Set.of("example genres")) * .isbn("example isbn") * .lastUpdated(LocalDateTime.now()) - * .metadata(Map.of("example value", "example metadata")) + * .metadata(Map.of("example metadata", "example metadata")) * .pages(42) * .price(3.14) * .publishDate(LocalDate.now()) @@ -345,7 +345,7 @@ public BookDtoBuilder lastUpdated(LocalDateTime lastUpdated) { *

    Example:

    * *
    {@code
    -   * builder.metadata(Map.of("example value", "example metadata"));
    +   * builder.metadata(Map.of("example metadata", "example metadata"));
        * }
    * * @param metadata the metadata map to set diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java index 61a3ade8..e8dab7da 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java @@ -186,6 +186,7 @@ private void addExampleToListConsumerWithBuilder( * @param method the method to add the example to * @param elementType the element type * @param fieldName the original field name used for String example values + * @param builderResolver resolves a type's builder for builder-backed examples */ private void addExampleToListConsumerWithSimpleValue( BuilderMethodDto method, diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java index 9411cd04..7be9408c 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java @@ -176,6 +176,7 @@ private void addExampleToSetConsumerWithBuilder( * @param method the method to add the example to * @param elementType the element type * @param fieldName the original field name used for String example values + * @param builderResolver resolves a type's builder for builder-backed examples */ private void addExampleToSetConsumerWithSimpleValue( BuilderMethodDto method, diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java index 36f89fc4..a02c7903 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/JavadocExampleValues.java @@ -27,6 +27,7 @@ import java.util.Map; import java.util.Optional; import java.util.function.Function; +import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameCollection; @@ -116,25 +117,8 @@ private JavadocExampleValues() { * * * @param typeName the type name to get an example value for - * @param builderResolver resolves a type's builder for builder-backed examples - * @return an Optional containing the example value, or empty if no example is available - */ - public static Optional getExampleValue( - TypeName typeName, Function> builderResolver) { - return getExampleValue(typeName, null, builderResolver); - } - - /** - * Returns an example value for the given type name, if available. - * - *

    Behaves like {@link #getExampleValue(TypeName, Function)}, but derives String examples from - * the given field name (e.g. field {@code category} → {@code "example category"}). The field name - * is passed through to nested String types (List/Set elements, array elements, Optional inner - * type, Map value type). All non-String types ignore the field name. - * - * @param typeName the type name to get an example value for - * @param fieldName the original field name used for String examples, or {@code null}/blank to - * fall back to {@value STRING_EXAMPLE} + * @param fieldName the original field name used for String examples; blank names use {@value + * STRING_EXAMPLE} * @param builderResolver resolves a type's builder for builder-backed examples * @return an Optional containing the example value, or empty if no example is available */ @@ -180,6 +164,11 @@ private static Optional resolveCollection( /** * Resolves an example for a collection element type, falling back to the element's builder type * (e.g. {@code SponsorDtoBuilder.create().build()}) when no direct example value exists. + * + * @param collectionType the collection whose element needs an example + * @param fieldName the original field name used for String examples + * @param builderResolver resolves a type's builder for builder-backed examples + * @return an example for the element, or empty if none is available */ private static Optional getElementExample( TypeNameCollection collectionType, @@ -211,7 +200,7 @@ private static Optional resolveMap( TypeNameMap mapType, String fieldName, Function> builderResolver) { - Optional keyExample = getExampleValue(mapType.getKeyType(), builderResolver); + Optional keyExample = getExampleValue(mapType.getKeyType(), fieldName, builderResolver); Optional valueExample = getExampleValue(mapType.getValueType(), fieldName, builderResolver); if (keyExample.isPresent() && valueExample.isPresent()) { @@ -243,7 +232,7 @@ private static Optional resolveCommonType(TypeName typeName) { private static Optional resolveString(TypeName typeName, String fieldName) { if (typeName.is(String.class)) { - if (fieldName == null || fieldName.isBlank()) { + if (StringUtils.isBlank(fieldName)) { return Optional.of(STRING_EXAMPLE); } return Optional.of(STRING_EXAMPLE_PREFIX + fieldName + STRING_EXAMPLE_SUFFIX); diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java index 063905cd..d44ae973 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java @@ -464,23 +464,8 @@ public static BuilderMethodDto createSimpleFieldConsumer( * * @param methodDto the method DTO to add the fragment to * @param fieldType the field type to get an example value for - */ - public static void addExampleChainFragment( - BuilderMethodDto methodDto, - TypeName fieldType, - Function> builderResolver) { - addExampleChainFragment(methodDto, fieldType, null, builderResolver); - } - - /** - * Adds the fluent-chain fragment for Javadoc examples to a method. - * - *

    Behaves like {@link #addExampleChainFragment(BuilderMethodDto, TypeName, Function)}, but - * derives String example values from the given field name (e.g. {@code "example "}). - * - * @param methodDto the method DTO to add the fragment to - * @param fieldType the field type to get an example value for - * @param fieldName the original field name used for String example values (may be {@code null}) + * @param fieldName the original field name used for String examples; blank names use a default + * @param builderResolver resolves a type's builder for builder-backed examples */ public static void addExampleChainFragment( BuilderMethodDto methodDto, @@ -504,23 +489,8 @@ public static void addExampleChainFragment( * * @param methodDto the method DTO to add the fragment to * @param elementType the element type to get an example value for - */ - public static void addExampleChainFragmentVarArgs( - BuilderMethodDto methodDto, - TypeName elementType, - Function> builderResolver) { - addExampleChainFragmentVarArgs(methodDto, elementType, null, builderResolver); - } - - /** - * Adds the fluent-chain fragment for Javadoc examples to a varargs method. - * - *

    Behaves like {@link #addExampleChainFragmentVarArgs(BuilderMethodDto, TypeName, Function)}, - * but derives String example values from the given field name. - * - * @param methodDto the method DTO to add the fragment to - * @param elementType the element type to get an example value for - * @param fieldName the original field name used for String example values (may be {@code null}) + * @param fieldName the original field name used for String examples; blank names use a default + * @param builderResolver resolves a type's builder for builder-backed examples */ public static void addExampleChainFragmentVarArgs( BuilderMethodDto methodDto, @@ -548,23 +518,8 @@ public static void addExampleChainFragmentVarArgs( * * @param methodDto the method DTO to add the fragment to * @param fieldType the field type to get an example value for - */ - public static void addExampleChainFragmentWithSupplier( - BuilderMethodDto methodDto, - TypeName fieldType, - Function> builderResolver) { - addExampleChainFragmentWithSupplier(methodDto, fieldType, null, builderResolver); - } - - /** - * Adds the fluent-chain fragment for Javadoc examples to a method using a supplier pattern. - * - *

    Behaves like {@link #addExampleChainFragmentWithSupplier(BuilderMethodDto, TypeName, - * Function)}, but derives String example values from the given field name. - * - * @param methodDto the method DTO to add the fragment to - * @param fieldType the field type to get an example value for - * @param fieldName the original field name used for String example values (may be {@code null}) + * @param fieldName the original field name used for String examples; blank names use a default + * @param builderResolver resolves a type's builder for builder-backed examples */ public static void addExampleChainFragmentWithSupplier( BuilderMethodDto methodDto, @@ -598,26 +553,8 @@ public static void addExampleChainFragmentWithSupplier( * @param template the template string with placeholders (e.g., {@code * #{methodName}(#{exampleValue})}) * @param fieldType the field type to get an example value for (can be {@code null}) - */ - public static void addExampleChainFragmentTemplate( - BuilderMethodDto methodDto, - String template, - TypeName fieldType, - Function> builderResolver) { - addExampleChainFragmentTemplate(methodDto, template, fieldType, null, builderResolver); - } - - /** - * Adds the fluent-chain fragment for Javadoc examples to a method using a template string. - * - *

    Behaves like {@link #addExampleChainFragmentTemplate(BuilderMethodDto, String, TypeName, - * Function)}, but derives String example values from the given field name. - * - * @param methodDto the method DTO to add the fragment to - * @param template the template string with placeholders (e.g., {@code - * #{methodName}(#{exampleValue})}) - * @param fieldType the field type to get an example value for (can be {@code null}) - * @param fieldName the original field name used for String example values (may be {@code null}) + * @param fieldName the original field name used for String examples; blank names use a default + * @param builderResolver resolves a type's builder for builder-backed examples */ public static void addExampleChainFragmentTemplate( BuilderMethodDto methodDto, diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java index 0785882e..5e3ed199 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderJavadocExampleTest.java @@ -268,7 +268,7 @@ public TagsDtoBuilder add2Tags(String element) *

    Example:

    * *
    {@code
    -            * builder.values(Map.of("example value", 42));
    +            * builder.values(Map.of("example values", 42));
                 * }
    """), Arguments.of( diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java index 4757ab40..b33249f2 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/ComprehensiveFeatureIntegrationTest.java @@ -139,8 +139,8 @@ void allFeatures_generatedCorrectly() { * .tags("example tags", "example tags") * .tagsUpdate(TreeSet::new) * .add2Tags("example tags") - * .metadata(Map.of("example value", "example metadata")) - * .metadata(() -> Map.of("example value", "example metadata")) + * .metadata(Map.of("example metadata", "example metadata")) + * .metadata(() -> Map.of("example metadata", "example metadata")) * .metadata(Map.entry("key", "example metadata")) * .metadataUpdate(Map::copyOf) * .address(AddressDtoBuilder.create().build()) @@ -597,7 +597,7 @@ public PersonDtoBuilder metadata(Consumer> metada *

    Example:

    * *
    {@code
    -           * builder.metadata(() -> Map.of("example value", "example metadata"));
    +           * builder.metadata(() -> Map.of("example metadata", "example metadata"));
                * }
    * * @param metadataSupplier supplier for metadata @@ -619,7 +619,7 @@ public PersonDtoBuilder metadata(Supplier> metadataSupplier) *

    Example:

    * *
    {@code
    -           * builder.metadata(Map.of("example value", "example metadata"));
    +           * builder.metadata(Map.of("example metadata", "example metadata"));
                * }
    * * @param metadata metadata @@ -644,7 +644,7 @@ public PersonDtoBuilder metadata(Map metadata) { *

    Example:

    * *
    {@code
    -           * builder.metadata(Map.of("example value", "example metadata")).metadataUpdate(Map::copyOf);
    +           * builder.metadata(Map.of("example metadata", "example metadata")).metadataUpdate(Map::copyOf);
                * }
    * * @param metadataUpdater operator applied to the current value; its result becomes the new value diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/JavadocExampleValuesTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/JavadocExampleValuesTest.java new file mode 100644 index 00000000..db0c8e1f --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/JavadocExampleValuesTest.java @@ -0,0 +1,61 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.simple.builders.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Optional; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.processor.generators.util.JavadocExampleValues; +import org.junit.jupiter.api.Test; + +class JavadocExampleValuesTest { + + @Test + void shouldDeriveStringExampleFromFieldName() { + assertEquals( + Optional.of("\"example category\""), + JavadocExampleValues.getExampleValue( + TypeName.of(String.class), "category", type -> Optional.empty())); + } + + @Test + void shouldUseDefaultStringExampleForBlankNames() { + for (String fieldName : new String[] {null, "", " \t\n"}) { + assertEquals( + Optional.of("\"example value\""), + JavadocExampleValues.getExampleValue( + TypeName.of(String.class), fieldName, type -> Optional.empty())); + } + } + + @Test + void shouldOmitExampleForUnsupportedType() { + assertEquals( + Optional.empty(), + JavadocExampleValues.getExampleValue( + new TypeName("test", "Unsupported"), "category", type -> Optional.empty())); + } +} From 9f33838b863fdb251070e30a912cb33030c7677c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:03:38 +0000 Subject: [PATCH 10/15] fix: preserve Roaster type-use annotations in declarations --- .../codegen/roaster/RoasterCodeGenerator.java | 23 ++-- .../roaster/RoasterCodeGeneratorTest.java | 126 ++++++++++++++++++ 2 files changed, 137 insertions(+), 12 deletions(-) diff --git a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java index dd35dca0..7a76a4bf 100644 --- a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java +++ b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterCodeGenerator.java @@ -71,6 +71,7 @@ import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.JavaInterfaceSource; import org.jboss.forge.roaster.model.source.JavaSource; +import org.jboss.forge.roaster.model.source.MethodHolderSource; import org.jboss.forge.roaster.model.source.MethodSource; import org.jboss.forge.roaster.model.source.ParameterSource; import org.jboss.forge.roaster.model.source.TypeVariableSource; @@ -233,9 +234,8 @@ private void appendFields(JavaClassSource source, GenerationTargetClassDto class } private void appendField(JavaClassSource source, ClassFieldDto fieldDto) { - FieldSource field = source.addField(); - field.setName(fieldDto.getFieldName()); - field.setType(mapType(fieldDto.getFieldType())); + FieldSource field = + source.addField(mapType(fieldDto.getFieldType()) + " " + fieldDto.getFieldName() + ";"); applyVisibility(field, fieldDto.getVisibility()); applyLiteralInitializer(field, fieldDto.getLiteralInitializer()); applyJavadoc(field, fieldDto.getJavadoc()); @@ -320,7 +320,7 @@ private void appendMethod( MethodDto methodDto, boolean nestedTypeMethod, boolean interfaceMethod) { - MethodSource method = source.addMethod(); + MethodSource method = createMethod(source, methodDto); configureMethod(method, methodDto, nestedTypeMethod, interfaceMethod); applyCodeBlock(method, methodDto.getMethodCodeDto()); } @@ -356,7 +356,7 @@ private void appendNestedType(JavaClassSource source, NestedTypeDto nestedType) private void appendNestedMethod(JavaSource source, MethodDto methodDto, boolean isInterface) { org.jboss.forge.roaster.model.source.MethodHolderSource methodHolder = (org.jboss.forge.roaster.model.source.MethodHolderSource) source; - MethodSource method = methodHolder.addMethod(); + MethodSource method = createMethod(methodHolder, methodDto); configureMethod(method, methodDto, true, isInterface); if (methodDto.getMethodCodeDto() != null && StringUtils.isNotBlank(methodDto.getMethodCodeDto().getCodeFormat())) { @@ -507,18 +507,17 @@ private void applyAnnotations( } } + private MethodSource createMethod(MethodHolderSource source, MethodDto methodDto) { + String returnType = + methodDto.getReturnType() == null ? "void" : mapType(methodDto.getReturnType()); + return source.addMethod(returnType + " " + methodDto.getMethodName() + "();"); + } + private void configureMethod( MethodSource method, MethodDto methodDto, boolean nestedTypeMethod, boolean interfaceMethod) { - method.setName(methodDto.getMethodName()); - if (methodDto.getReturnType() == null) { - method.setReturnTypeVoid(); - } else { - method.setReturnType(mapType(methodDto.getReturnType())); - } - if (nestedTypeMethod) { boolean hasBody = interfaceMethod diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index ed02a2d7..d7ed8b97 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -27,6 +27,8 @@ import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import com.google.testing.compile.Compilation; +import com.google.testing.compile.JavaFileObjects; import java.util.List; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; @@ -44,6 +46,7 @@ import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.testing.CodegenTestUtils; import org.javahelpers.codegen.testing.TestingGenerationEnvironment; import org.junit.jupiter.api.Test; @@ -54,6 +57,129 @@ */ class RoasterCodeGeneratorTest { + @Test + void preservesLeadingFieldTypeAnnotation() throws Exception { + GenerationTargetClassDto classDef = annotatedClassDefinition(); + ClassFieldDto field = new ClassFieldDto(); + field.setFieldName("value"); + field.setFieldType(nullableString()); + field.setVisibility(AccessModifier.PRIVATE); + classDef.addClassField(field); + + assertAnnotatedSource( + """ + package test; + import test.anno.Nullable; + public class AnnotatedTypes { + @Nullable + private String value; + } + """, + classDef); + } + + @Test + void preservesLeadingReturnTypeAnnotation() throws Exception { + GenerationTargetClassDto classDef = annotatedClassDefinition(); + MethodDto method = new MethodDto("value", nullableString()); + method.setModifier(AccessModifier.PUBLIC); + method.setCode("return null;"); + AnnotationDto deprecated = new AnnotationDto(); + deprecated.setAnnotationType(TypeName.of(Deprecated.class)); + method.addAnnotation(deprecated); + classDef.addMethod(method); + + assertAnnotatedSource( + """ + package test; + import test.anno.Nullable; + public class AnnotatedTypes { + @Nullable + @Deprecated + public String value() { + return null; + } + } + """, + classDef); + } + + @Test + void preservesAnnotatedGenericReturnType() throws Exception { + GenerationTargetClassDto classDef = annotatedClassDefinition(); + TypeName list = new TypeNameGeneric(TypeName.of(List.class), nullableString()); + MethodDto method = new MethodDto("values", list); + method.setModifier(AccessModifier.PUBLIC); + method.setCode("return null;"); + classDef.addMethod(method); + + NestedTypeDto nested = new NestedTypeDto(); + nested.setTypeName("Nested"); + nested.setKind(NestedTypeDto.NestedTypeKind.INTERFACE); + nested.setVisibility(AccessModifier.PUBLIC); + MethodDto nestedMethod = + new MethodDto("values", new TypeNameGeneric(TypeName.of(List.class), list)); + nestedMethod.setCode("return null;"); + nested.addMethod(nestedMethod); + classDef.addNestedType(nested); + + assertAnnotatedSource( + """ + package test; + import java.util.List; + import test.anno.Nullable; + public class AnnotatedTypes { + public List<@Nullable String> values() { + return null; + } + public interface Nested { + default List> values() { + return null; + } + } + } + """, + classDef); + } + + private static GenerationTargetClassDto annotatedClassDefinition() { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "AnnotatedTypes")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + return classDef; + } + + private static TypeName nullableString() { + AnnotationDto nullable = new AnnotationDto(); + nullable.setAnnotationType(new TypeName("test.anno", "Nullable")); + TypeName type = TypeName.of(String.class); + type.addAnnotation(nullable); + return type; + } + + private static void assertAnnotatedSource(String expected, GenerationTargetClassDto classDef) + throws Exception { + String source = generate(classDef).generatedSource(); + assertNormalizedEquals(expected, source, "annotated declarations must be preserved"); + Compilation compilation = + CodegenTestUtils.createCompiler() + .compile( + JavaFileObjects.forSourceString("test.AnnotatedTypes", source), + JavaFileObjects.forSourceString( + "test.anno.Nullable", + """ + package test.anno; + import java.lang.annotation.ElementType; + import java.lang.annotation.Target; + @Target(ElementType.TYPE_USE) + public @interface Nullable { + } + """)); + assertEquals( + Compilation.Status.SUCCESS, compilation.status(), compilation.diagnostics().toString()); + } + @Test void generatesDelegatingBuilderFromDto() throws Exception { assertGeneratedSource( From 44e492b0953e1c6ee20556fbf2085e7a8c26a3a3 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:05:57 +0000 Subject: [PATCH 11/15] test: tighten shared generator conformance assertions --- .../roaster/RoasterCodeGeneratorTest.java | 2 +- .../roaster/RoasterTestBackendProvider.java | 3 +- codegen-testing/pom.xml | 2 +- .../testing/GeneratorConformanceTest.java | 130 +++++++++++++++--- .../codegen/testing/TestBackendProvider.java | 2 +- 5 files changed, 115 insertions(+), 24 deletions(-) diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index 6470d988..158ee3b9 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -245,7 +245,7 @@ void qualifiesCollidingSimpleTypeNames() throws Exception { import java.sql.Date; public class DateBuilder { private java.util.Date utilDate; - private Date sqlDate; + private java.sql.Date sqlDate; }""", classDef); } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java index cfae9519..ffe81824 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java @@ -42,7 +42,8 @@ public String name() { @Override public CodegenBackend create(GenerationEnvironment environment, ProcessingLogger logger) { - return new RoasterBackend(environment, logger, null); + return new RoasterBackend( + environment, logger, RoasterSourceFormatter.DEFAULT_FORMATTER_PROFILE_RESOURCE); } @Override diff --git a/codegen-testing/pom.xml b/codegen-testing/pom.xml index 4b5bfca6..dd147c83 100644 --- a/codegen-testing/pom.xml +++ b/codegen-testing/pom.xml @@ -131,7 +131,7 @@ org.junit.jupiter junit-jupiter-engine ${junit-jupiter.version} - compile + test diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java index 42b9e4a8..01aa8386 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java @@ -77,7 +77,7 @@ * {@link TestBackendProvider} on its test classpath (see {@link TestBackendProvider} for the * contract). Every test in this class then runs once per discovered backend, with the provider's * {@link TestBackendProvider#name() name} in the test display name — so a failure always identifies - * the failing generator. New backends (issue #366) gain identical coverage without writing or + * the failing generator. New backends (issue #364) gain identical coverage without writing or * copying any test. * *

    Each fixture is asserted on two levels: @@ -85,8 +85,7 @@ *

      *
    • Compilability — the emitted source is fed through {@code javac} and must compile * without errors - *
    • Semantic content — backend-independent fragments (declaration kinds, member names, - * disambiguated type references), not exact formatting + *
    • Semantic content — exact declarations and blocks, ignoring whitespace *
    * *

    Backend modules must configure surefire's {@code dependenciesToScan} to include {@code @@ -104,7 +103,8 @@ public class GeneratorConformanceTest { */ static Stream backends() { return ServiceLoader.load(TestBackendProvider.class).stream() - .map(provider -> Arguments.of(Named.of(provider.get().name(), provider.get()))); + .map(ServiceLoader.Provider::get) + .map(provider -> Arguments.of(Named.of(provider.name(), provider))); } @ParameterizedTest(name = "{0}") @@ -133,7 +133,20 @@ void simpleClassWithFieldsMethodsAndConstructor_compiles(TestBackendProvider bac String source = generate(backend, classDef); assertCompiles(classDef, source); assertContaining( - source, "public class SimpleClass", "String describe(", "SimpleClass(String name)"); + source, + """ + public class SimpleClass { + private String name; + private int age; + private boolean active; + public SimpleClass(String name) { + this.name = name; + } + public String describe() { + return name + "#" + age; + } + } + """); } @ParameterizedTest(name = "{0}") @@ -162,7 +175,15 @@ void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exc String source = generate(backend, classDef); assertCompiles(classDef, source); - assertContaining(source, "class GenericBox>", ""); + assertContaining( + source, + """ + public class GenericBox> { + public static R pick(R first, R second) { + return first; + } + } + """); } @ParameterizedTest(name = "{0}") @@ -184,7 +205,13 @@ void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws String source = generate(backend, classDef); assertCompiles(classDef, source); assertContaining( - source, "List names", "Map scores", "Optional nickname"); + source, + """ + private List names; + private Map scores; + private int[] numbers; + private Optional nickname; + """); } /** @@ -210,10 +237,18 @@ void collidingSimpleNames_areDisambiguated(TestBackendProvider backend) throws E classDef.addMethod(method); String source = generate(backend, classDef); - assertTrue( - source.contains("java.util.Date") || source.contains("java.sql.Date"), - () -> "colliding Date types must be qualified in the generated source, was:\n" + source); assertCompiles(classDef, source); + assertContaining( + source, + """ + private java.util.Date utilDate; + private java.sql.Date sqlDate; + public void touch(java.sql.Date when) { + if (when == null) { + return; + } + } + """); } @ParameterizedTest(name = "{0}") @@ -238,7 +273,15 @@ void nestedTypesWithMembers_compile(TestBackendProvider backend) throws Exceptio String source = generate(backend, classDef); assertCompiles(classDef, source); - assertContaining(source, "class Helper", "void assist("); + assertContaining( + source, + """ + public class Helper { + public void assist() { + int touched = 0; + } + } + """); } @ParameterizedTest(name = "{0}") @@ -270,7 +313,16 @@ void annotationsOnClassMembersAndTypeUse_compile(TestBackendProvider backend) th String source = generate(backend, classDef); assertCompiles(classDef, source); - assertContaining(source, "@Deprecated", "@Generated", "TestTypeUseAnnotation"); + assertContaining( + source, + """ + @Deprecated(since = "0.9", forRemoval = true) + @Generated("conformance") + public class AnnotatedClass { + @TestTypeUseAnnotation + private String flagged; + } + """); } @ParameterizedTest(name = "{0}") @@ -295,7 +347,15 @@ void codeTemplatePlaceholders_resolve(TestBackendProvider backend) throws Except String source = generate(backend, classDef); assertCompiles(classDef, source); - assertContaining(source, "int count = 0", "Integer box", "Long.parseLong(\"42\")"); + assertContaining( + source, + """ + public long parse() { + int count = 0; + Integer box = null; + return Long.parseLong("42"); + } + """); } @ParameterizedTest(name = "{0}") @@ -308,7 +368,12 @@ void superTypeAndInterfaces_compile(TestBackendProvider backend) throws Exceptio String source = generate(backend, classDef); assertCompiles(classDef, source); - assertContaining(source, "extends ArrayList", "implements Serializable, Cloneable"); + assertContaining( + source, + """ + public class DerivedClass extends ArrayList implements Serializable, Cloneable { + } + """); } @ParameterizedTest(name = "{0}") @@ -339,11 +404,19 @@ void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws E String source = generate(backend, classDef); assertCompiles(classDef, source); - // array types in parameter position may render as "String[]" or normalized "String..." - assertTrue( - source.contains("String[] names") || source.contains("String... names"), - () -> "array parameter must be rendered as array or varargs, was:\n" + source); - assertContaining(source, "import static"); + assertContaining( + source, + """ + import static java.util.Collections.emptyList; + """, + """ + private List initial = emptyList(); + """, + """ + public static int of(String... names) { + return names.length; + } + """); } @ParameterizedTest(name = "{0}") @@ -368,7 +441,24 @@ void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exce classDef.addMethod(method); String source = generate(backend, classDef); - assertContaining(source, "Documented conformance class.", "@param", "@return"); + assertCompiles(classDef, source); + assertContaining( + source, + """ + /** + * Documented conformance class. + */ + public class DocumentedClass { + /** + * Echoes the value. + * @param value the input + * @return the echoed value + */ + public String echo(String value) { + return value; + } + } + """); } /** Generates {@code classDef} through {@code provider}'s backend and returns the source text. */ diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java index 41ae3275..dc264a63 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestBackendProvider.java @@ -33,7 +33,7 @@ * generator conformance suite. * *

    Every backend module (Roaster today; JavaPoet or the built-in lightweight generator planned in - * issue #366) registers exactly one implementation in its test sources: + * issue #364) registers exactly one implementation in its test sources: * *

      *
    • a provider class implementing this interface From 6aab31d9d9fbb184fa9783edd64baf4a25d9620d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:44:09 +0000 Subject: [PATCH 12/15] fix: derive reserved builder property names from getters --- .../processor/model/core/BuilderFieldDto.java | 12 +- .../processing/BuilderDefinitionCreator.java | 72 ++++-------- .../processor/ReservedPropertyNameTest.java | 110 +++++++++++------- .../codegen/analysis/JavaLangAnalyser.java | 39 +++++-- 4 files changed, 128 insertions(+), 105 deletions(-) diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java index b3cc7f2d..43b478c3 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java @@ -29,7 +29,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.core.DeprecationInfoDto; import org.javahelpers.codegen.model.javadoc.JavadocDto; @@ -145,21 +144,18 @@ public void setFieldNameInBuilder(String fieldNameInBuilder) { } /** - * Gets the setter method name for this field. Defaults to the name derived from the original - * field name following JavaBean conventions (e.g., "userName" becomes "setUserName"); an - * explicitly set name takes precedence. + * Gets the setter method name for this field. * * @return the setter method name for this field (never null) */ public String getSetterName() { - return setterName != null ? setterName : "set" + StringUtils.capitalize(originalFieldName); + return setterName; } /** - * Sets the setter method name to invoke for this field. Use this when the real setter name cannot - * be derived from {@link #getOriginalFieldName()} via JavaBeans conventions. + * Sets the setter method name to invoke for this field. * - * @param setterName the setter method name, or {@code null} to fall back to the derived name + * @param setterName the setter method name */ public void setSetterName(String setterName) { this.setterName = setterName; diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java index 273f3440..6fc9752d 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java @@ -44,7 +44,6 @@ import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.ElementFilter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.javahelpers.codegen.analysis.FieldAnnotationExtractor; @@ -701,19 +700,21 @@ private static Optional createFieldFromSetter( String fullJavaDoc = context.getDocComment(mth); String javaDocDescription = JavaLangAnalyser.extractParamJavaDoc(fullJavaDoc, fieldParameter); - // The setter-derived property name is used as-is for generated method and field names. - // setX -> x can yield a name that is not a legal Java identifier (e.g. setStatic -> - // "static"). Prefer a backing field with a legal name; if none exists, skip only this - // property instead of failing the whole target. if (!SourceVersion.isName(fieldName)) { Optional legalFieldName = - findLegalBackingFieldName(dtoTypeElement, fieldName, fieldParameter, context); + JavaLangAnalyser.findGettersForField( + dtoTypeElement, fieldName, fieldParameter.asType(), context) + .stream() + .map(getter -> getter.getSimpleName().toString()) + .map(name -> StringUtils.uncapitalize(StringUtils.removeStart(name, "get"))) + .filter(SourceVersion::isName) + .findFirst(); if (legalFieldName.isEmpty()) { context.reportBasedOnStrictMode( mth, "Setter '%s' derives property name '%s', which is not a legal Java identifier. " - + "No backing field with a legal name was found, so this property is skipped. " - + "Rename the setter, add a backing field, or use @IgnoreInBuilder to silence " + + "No getter yielding a legal name was found, so this property is skipped. " + + "Rename the setter, add a getter, or use @IgnoreInBuilder to silence " + "this message.", methodName, fieldName); @@ -721,7 +722,7 @@ private static Optional createFieldFromSetter( } context.debug( "Setter '%s' derives property name '%s', which is not a legal Java identifier - " - + "using backing field name '%s' for builder members", + + "using getter-derived name '%s' for builder members", methodName, fieldName, legalFieldName.get()); fieldName = legalFieldName.get(); } @@ -735,6 +736,7 @@ private static Optional createFieldFromSetter( createFieldDto( fieldName, finalFieldName, + methodName, javaDocDescription, fieldParameter, dtoType, @@ -747,10 +749,6 @@ private static Optional createFieldFromSetter( BuilderFieldDto field = result.get(); - // The real setter name is authoritative: the derived field name may have been renamed - // (e.g. setStatic -> "static" resolved to the backing field "isStatic"). - field.setSetterName(methodName); - // If no default was found on the setter parameter, check the field element itself // (annotations like @Default may be placed on the field rather than the setter param) if (field.getDefaultValue().isEmpty()) { @@ -786,7 +784,14 @@ private static Optional createFieldFromConstructor( // Pass both original field name (for methods) and final field name (for builder field) Optional result = createFieldDto( - fieldName, finalFieldName, javaDocDescription, param, dtoType, builderType, context); + fieldName, + finalFieldName, + "set" + StringUtils.capitalize(fieldName), + javaDocDescription, + param, + dtoType, + builderType, + context); if (result.isPresent()) { fieldNameRegistry.put(finalFieldName, result.get()); @@ -795,35 +800,6 @@ private static Optional createFieldFromConstructor( return result; } - /** - * Finds a backing field on the DTO that corresponds to an illegal setter-derived property name. A - * field cannot itself be named after a keyword, so the legal candidates are the JavaBeans {@code - * is}-prefixed boolean convention: a field {@code isX} maps to property {@code x} the same way - * setter {@code setX} does (e.g. field {@code isStatic} for setter {@code setStatic}). - * - * @param dtoTypeElement the DTO type declaring the setter - * @param propertyName the illegal property name derived from the setter (e.g. {@code "static"}) - * @param fieldParameter the setter parameter, used to verify the field type matches - * @param context processing context - * @return the legal backing field name, or empty if no matching field exists - */ - private static Optional findLegalBackingFieldName( - TypeElement dtoTypeElement, - String propertyName, - VariableElement fieldParameter, - BuilderProcessingContext context) { - for (VariableElement field : ElementFilter.fieldsIn(dtoTypeElement.getEnclosedElements())) { - String name = field.getSimpleName().toString(); - if (name.length() > 2 - && name.startsWith("is") - && propertyName.equals(StringUtils.uncapitalize(name.substring(2))) - && context.isSameType(field.asType(), fieldParameter.asType())) { - return Optional.of(name); - } - } - return Optional.empty(); - } - /** * Resolves field name conflicts by checking the registry and renaming if necessary. If a field * with the same name already exists but has a different type, the new field is renamed by @@ -889,7 +865,8 @@ The reason could be having helperfunctions in the DTO or a mistake in the DTO (e * * @param fieldName the estimated field name (used for method names) * @param fieldNameInBuilder the builder field name (used for storage, may be renamed) - * @param javaDoc the javadoc for the field + * @param setterName the setter method name + * @param javaDocDescription the javadoc for the field * @param param the parameter element (from constructor or setter) * @param dtoType the DTO type containing this field * @param builderType the builder type (may include generic type parameters) @@ -899,6 +876,7 @@ The reason could be having helperfunctions in the DTO or a mistake in the DTO (e private static Optional createFieldDto( String fieldName, String fieldNameInBuilder, + String setterName, String javaDocDescription, VariableElement param, TypeName dtoType, @@ -913,6 +891,7 @@ private static Optional createFieldDto( TypeMirror fieldTypeMirror = param.asType(); BuilderFieldDto field = new BuilderFieldDto(); + field.setSetterName(setterName); field.setFieldNameInBuilder( fieldNameInBuilder); // Use renamed field name for builder field storage field.setOriginalFieldName(fieldName); @@ -931,8 +910,6 @@ private static Optional createFieldDto( fieldNameInBuilder, javaDocDescriptionOrFieldname); field.setJavaDoc(trackedValueJavadoc); - // Note: setterName will be set explicitly by the caller before field renaming - // Find matching getter on the DTO type using the builder field name TypeElement dtoTypeElement = context.getTypeElement(dtoType); Optional getter = @@ -1032,7 +1009,8 @@ private static void detectAndApplyFieldDeprecation( Optional recordComponent = JavaLangAnalyser.findRecordComponent(dtoTypeElement, fieldName); // The setter name is usually set; after reserved-name fallback (e.g. - // setStatic -> field "isStatic") the name-derived lookup misses, so the enclosing + // setStatic -> getter-derived property "isStatic") the name-derived lookup misses, so the + // enclosing // executable of the parameter is used as an additional candidate — for setter fields // that enclosing element IS the setter. Optional setter = diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java index 0d21658a..670e69af 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java @@ -28,98 +28,130 @@ import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; import static org.javahelpers.simple.builders.processor.testing.BuilderAsserts.assertGenerationSucceeded; import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.createCompiler; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.forSource; import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.loadGeneratedSource; import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.simpleBuilderClass; import com.google.testing.compile.Compilation; import javax.tools.JavaFileObject; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; /** * Tests for setters whose JavaBeans-derived property name is a reserved Java identifier (issue * #418). {@code setStatic} derives the property name {@code static}, {@code setDefault} derives * {@code default} — both illegal as generated method names. Generation must not fail for the whole - * target: if a backing field with a legal name exists (e.g. {@code isStatic}), its name is used for - * builder members; otherwise only the offending property is skipped. + * target: a matching getter supplies a legal name; otherwise only the offending property is + * skipped. */ class ReservedPropertyNameTest { private static final String PACKAGE = "pkg.reserved"; /** - * A setter {@code setStatic} with a backing field {@code isStatic} yields a builder whose helpers - * are named {@code isStatic(...)} while {@code build()} still invokes the real setter {@code - * setStatic(...)}. + * The getter determines the property name independently of the backing field and setter prefix. */ - @Test - void reservedPropertyName_fallsBackToBackingFieldName() { + @ParameterizedTest + @CsvSource({"'', isStatic", "with, withIsStatic"}) + void reservedPropertyUsesGetterName(String prefix, String methodName) { JavaFileObject dto = simpleBuilderClass( PACKAGE, "StaticFlagDto", """ - private boolean isStatic; - private String name; - public boolean isStatic() { return isStatic; } - public void setStatic(boolean isStatic) { this.isStatic = isStatic; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } + private boolean staticValue; + public boolean getStatic() { return staticValue; } + public boolean isStatic() { return staticValue; } + public void setStatic(boolean value) { this.staticValue = value; } """); - Compilation compilation = createCompiler().compile(dto); + Compilation compilation = + createCompiler().withOptions("-Asimplebuilder.setterPrefix=" + prefix).compile(dto); String generated = loadGeneratedSource(compilation, "StaticFlagDtoBuilder"); assertGenerationSucceeded(compilation, "StaticFlagDtoBuilder", generated); assertContaining( - generated, "isStatic(boolean isStatic)", "name(String name)", "setStatic", "setName"); + generated, + """ + private TrackedValue isStatic = unsetValue(); + """, + """ + public StaticFlagDtoBuilder %s(boolean isStatic) { + this.isStatic = changedValue(isStatic); + return this; + } + """ + .formatted(methodName)); } - /** - * A setter {@code setDefault} without a legally named backing field is skipped with a warning; - * the other properties are still generated and compilation succeeds. - */ - @Test - void reservedPropertyName_withoutBackingField_isSkippedWithWarning() { + /** A matching backing field cannot rescue a property without a usable getter. */ + @ParameterizedTest + @ValueSource( + strings = { + "", + "public boolean getDefault() { return isDefault; }", + "private boolean isDefault() { return isDefault; }", + "public String isDefault() { return null; }", + "public boolean isDefault(boolean value) { return value; }" + }) + void reservedPropertyWithoutLegalGetterIsSkipped(String getter) { JavaFileObject dto = simpleBuilderClass( PACKAGE, "DefaultFlagDto", """ - private boolean defaultValue; + private boolean isDefault; private String name; - public boolean isDefaultValue() { return defaultValue; } - public void setDefault(boolean defaultValue) { this.defaultValue = defaultValue; } + public void setDefault(boolean value) { this.isDefault = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } - """); + """ + + getter); Compilation compilation = createCompiler().compile(dto); assertThat(compilation).succeeded(); - assertThat(compilation).hadWarningContaining("not a legal Java identifier"); + assertThat(compilation) + .hadWarningContaining("No getter yielding a legal name was found") + .inFile(dto) + .onLine(9); String generated = loadGeneratedSource(compilation, "DefaultFlagDtoBuilder"); - assertContaining(generated, "name(String name)"); + assertContaining( + generated, + """ + public DefaultFlagDtoBuilder name(String name) { + this.name = changedValue(name); + return this; + } + """); } - /** - * In strict mode the skipped property is reported as an error instead of a warning, consistent - * with the existing strict diagnostics handling. - */ + /** Strict mode reports the invalid property at its setter and fails compilation. */ @Test - void reservedPropertyName_strictMode_isError() { + void reservedPropertyWithoutGetterFailsInStrictMode() { JavaFileObject dto = - simpleBuilderClass( - PACKAGE, - "StrictDefaultDto", + forSource( """ - private boolean defaultValue; - public boolean isDefaultValue() { return defaultValue; } - public void setDefault(boolean defaultValue) { this.defaultValue = defaultValue; } + package pkg.reserved; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class StrictDefaultDto { + private boolean isDefault; + public void setDefault(boolean value) { this.isDefault = value; } + } """); Compilation compilation = createCompiler().withOptions("-Asimplebuilder.strict=true").compile(dto); - assertThat(compilation).hadErrorContaining("not a legal Java identifier"); + assertThat(compilation).failed(); + assertThat(compilation) + .hadErrorContaining( + "Setter 'setDefault' derives property name 'default', which is not a legal Java identifier. " + + "No getter yielding a legal name was found") + .inFile(dto) + .onLine(6); } } diff --git a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangAnalyser.java b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangAnalyser.java index 4627f93a..191258b4 100644 --- a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangAnalyser.java +++ b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangAnalyser.java @@ -806,23 +806,40 @@ public static Optional findGetterForField( String fieldName, TypeMirror fieldTypeMirror, AnnotationProcessingContext context) { + return findGettersForField(dtoType, fieldName, fieldTypeMirror, context).stream().findFirst(); + } + + /** + * Finds accessible, parameterless getters whose names and return types match a property. + * + * @param dtoType the enclosing type + * @param fieldName the property name + * @param fieldTypeMirror the expected return type + * @param context processing context + * @return matching getters in member order + */ + public static List findGettersForField( + TypeElement dtoType, + String fieldName, + TypeMirror fieldTypeMirror, + AnnotationProcessingContext context) { if (dtoType == null || fieldName == null || fieldTypeMirror == null) { - return Optional.empty(); + return List.of(); } List methods = ElementFilter.methodsIn(context.getAllMembers(dtoType)); // Check for accessor methods: // Record-style (fieldName), boolean-style (isXxx), or standard (getXxx) - for (ExecutableElement candidate : methods) { - String name = candidate.getSimpleName().toString(); - if (Strings.CI.equalsAny(name, fieldName, "is" + fieldName, "get" + fieldName) - && candidate.getParameters().isEmpty() - && context.isSameType(candidate.getReturnType(), fieldTypeMirror) - && context.isAccessibleFromGeneratedPackage(candidate)) { - return Optional.of(candidate); - } - } - return Optional.empty(); + return methods.stream() + .filter( + candidate -> { + String name = candidate.getSimpleName().toString(); + return Strings.CI.equalsAny(name, fieldName, "is" + fieldName, "get" + fieldName) + && candidate.getParameters().isEmpty() + && context.isSameType(candidate.getReturnType(), fieldTypeMirror) + && context.isAccessibleFromGeneratedPackage(candidate); + }) + .toList(); } /** From f9a8d39e0a665a7ff400cdc8fcc062427ca41c79 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:53:18 +0000 Subject: [PATCH 13/15] fix: preserve wildcard type arguments in generated builders --- .../codegen/model/core/ClassFieldDto.java | 5 +- .../model/core/GenerationTargetClassDto.java | 5 +- .../codegen/model/method/CodeTemplateDto.java | 5 +- .../codegen/model/type/TypeNameGeneric.java | 9 ++ .../codegen/model/type/TypeNameWildcard.java | 103 ++++++++++++++++++ .../codegen/util/ImportCollector.java | 5 + .../model/type/TypeNameWildcardTest.java | 70 ++++++++++++ .../codegen/util/ImportCollectorTest.java | 40 +++++++ .../codegen/roaster/RoasterMapper.java | 10 +- .../codegen/roaster/RoasterMapperTest.java | 17 +++ .../field/AddToCollectionGenerator.java | 6 + .../field/FieldInstanceConsumerGenerator.java | 6 + .../field/ListConsumerGenerator.java | 5 + .../field/MapConsumerGenerator.java | 5 + .../field/NestedBuilderConsumerGenerator.java | 6 + .../field/OptionalHelperGenerator.java | 5 + .../field/SetConsumerGenerator.java | 5 + .../field/VarArgsHelperGenerator.java | 5 + .../processor/WildcardTypeArgumentsTest.java | 87 +++++++++++++++ .../codegen/analysis/JavaLangMapper.java | 13 +++ .../codegen/analysis/JavaLangMapperTest.java | 28 +++++ 21 files changed, 436 insertions(+), 4 deletions(-) create mode 100644 codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameWildcard.java create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/model/type/TypeNameWildcardTest.java create mode 100644 processor/src/test/java/org/javahelpers/simple/builders/processor/WildcardTypeArgumentsTest.java diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java index d86442bc..67fbf592 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java @@ -38,6 +38,7 @@ import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameWildcard; /** * Represents a field declaration in the generated class. @@ -129,7 +130,9 @@ public void addImport(Class clazz) { * @param typeName the type to import */ public void addImport(TypeName typeName) { - if (typeName instanceof TypeNameGeneric generic) { + if (typeName instanceof TypeNameWildcard wildcard) { + wildcard.getBound().ifPresent(this::addImport); + } else if (typeName instanceof TypeNameGeneric generic) { addImport(generic.getRawType()); generic.getInnerTypeArguments().forEach(this::addImport); } else if (typeName instanceof TypeNameArray array) { diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java index 6615e1c7..f84636ce 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java @@ -43,6 +43,7 @@ import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameWildcard; /** * Generic representation of a class to generate. @@ -171,7 +172,9 @@ public void addImport(Class clazz) { * @param typeName the type to import */ public void addImport(TypeName typeName) { - if (typeName instanceof TypeNameGeneric generic) { + if (typeName instanceof TypeNameWildcard wildcard) { + wildcard.getBound().ifPresent(this::addImport); + } else if (typeName instanceof TypeNameGeneric generic) { addImport(generic.getRawType()); generic.getInnerTypeArguments().forEach(this::addImport); } else if (typeName instanceof TypeNameArray array) { diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java index fbd13981..2b45684b 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java @@ -36,6 +36,7 @@ import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameWildcard; /** * Base DTO for holding code template information with placeholders. @@ -131,7 +132,9 @@ public Set getCodeBlockImports() { * @param typeName type to import */ public void addCodeBlockImport(TypeName typeName) { - if (typeName instanceof TypeNameGeneric generic) { + if (typeName instanceof TypeNameWildcard wildcard) { + wildcard.getBound().ifPresent(this::addCodeBlockImport); + } else if (typeName instanceof TypeNameGeneric generic) { addCodeBlockImport(generic.getRawType()); generic.getInnerTypeArguments().forEach(this::addCodeBlockImport); } else if (typeName instanceof TypeNameArray array) { diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java index a8f6519d..bb751574 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java @@ -44,6 +44,15 @@ * way. */ public class TypeNameGeneric extends TypeName { + /** + * Checks whether any immediate type argument is a wildcard, rather than a writable element type. + * + * @return true if an immediate argument is a wildcard + */ + public boolean hasWildcardArguments() { + return innerTypeArguments.stream().anyMatch(TypeNameWildcard.class::isInstance); + } + private final List innerTypeArguments; /** The raw (outer) type before generic parameterization; preserves nested-type structure. */ diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameWildcard.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameWildcard.java new file mode 100644 index 00000000..b199ce4f --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameWildcard.java @@ -0,0 +1,103 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.model.type; + +import java.util.Objects; +import java.util.Optional; + +/** A wildcard type argument, optionally bounded above or below by another type. */ +public final class TypeNameWildcard extends TypeName { + public enum BoundKind { + UNBOUNDED, + EXTENDS, + SUPER + } + + private final BoundKind boundKind; + private final TypeName bound; + + /** Creates an unbounded wildcard. */ + public TypeNameWildcard() { + super("", "?"); + boundKind = BoundKind.UNBOUNDED; + bound = null; + } + + private TypeNameWildcard(BoundKind boundKind, TypeName bound) { + super("", "?"); + this.boundKind = boundKind; + this.bound = Objects.requireNonNull(bound, "bound"); + } + + /** + * Creates an upper-bounded wildcard. + * + * @param bound the non-null upper bound + * @return the wildcard + */ + public static TypeNameWildcard extendsBound(TypeName bound) { + return new TypeNameWildcard(BoundKind.EXTENDS, bound); + } + + /** + * Creates a lower-bounded wildcard. + * + * @param bound the non-null lower bound + * @return the wildcard + */ + public static TypeNameWildcard superBound(TypeName bound) { + return new TypeNameWildcard(BoundKind.SUPER, bound); + } + + public BoundKind getBoundKind() { + return boundKind; + } + + public Optional getBound() { + return Optional.ofNullable(bound); + } + + @Override + public String getFullQualifiedName() { + return switch (boundKind) { + case UNBOUNDED -> "?"; + case EXTENDS -> "? extends " + bound.getFullQualifiedName(); + case SUPER -> "? super " + bound.getFullQualifiedName(); + }; + } + + @Override + public boolean equals(Object other) { + return other instanceof TypeNameWildcard wildcard + && super.equals(other) + && boundKind == wildcard.boundKind + && Objects.equals(bound, wildcard.bound); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), boundKind, bound); + } +} diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java index 1e53ccf2..b0454a75 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java @@ -46,6 +46,7 @@ import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.model.type.TypeNameWildcard; /** * Utility class for collecting, deduplicating, and sorting imports for generated classes. @@ -84,6 +85,10 @@ public ImportCollector addTypeImports(TypeName type) { type.getAnnotations().forEach(this::addAnnotationImports); // Adding the type + if (type instanceof TypeNameWildcard wildcard) { + wildcard.getBound().ifPresent(this::addTypeImports); + return this; + } addImport(type); return this; diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/model/type/TypeNameWildcardTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/type/TypeNameWildcardTest.java new file mode 100644 index 00000000..7f237c8a --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/type/TypeNameWildcardTest.java @@ -0,0 +1,70 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.model.type; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class TypeNameWildcardTest { + @Test + void modelsBoundsAndQualifiedNames() { + TypeNameWildcard unbounded = new TypeNameWildcard(); + assertEquals("?", unbounded.getFullQualifiedName()); + assertEquals(TypeNameWildcard.BoundKind.UNBOUNDED, unbounded.getBoundKind()); + assertTrue(unbounded.getBound().isEmpty()); + TypeNameWildcard upper = TypeNameWildcard.extendsBound(TypeName.of(Number.class)); + assertEquals("? extends java.lang.Number", upper.getFullQualifiedName()); + assertEquals(TypeName.of(Number.class), upper.getBound().orElseThrow()); + TypeNameWildcard lower = + TypeNameWildcard.superBound(new TypeNameGeneric(List.class, String.class)); + assertEquals("? super java.util.List", lower.getFullQualifiedName()); + assertEquals(TypeNameWildcard.BoundKind.SUPER, lower.getBoundKind()); + } + + @Test + void equalityIncludesDirectionAndBound() { + TypeNameWildcard upper = TypeNameWildcard.extendsBound(TypeName.of(Number.class)); + TypeNameWildcard same = TypeNameWildcard.extendsBound(TypeName.of(Number.class)); + assertEquals(upper, same); + assertEquals(upper.hashCode(), same.hashCode()); + assertEquals(new TypeNameWildcard(), new TypeNameWildcard()); + assertNotEquals(upper, new TypeNameWildcard()); + assertNotEquals(upper, TypeNameWildcard.superBound(TypeName.of(Number.class))); + assertNotEquals(upper, TypeNameWildcard.extendsBound(TypeName.of(Integer.class))); + assertNotEquals(upper, TypeName.of(Number.class)); + assertNotEquals(upper, null); + } + + @Test + void rejectsMissingBound() { + assertThrows(NullPointerException.class, () -> TypeNameWildcard.extendsBound(null)); + assertThrows(NullPointerException.class, () -> TypeNameWildcard.superBound(null)); + } +} diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java index 56e628fe..6cefb73c 100644 --- a/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java @@ -31,14 +31,54 @@ import org.javahelpers.codegen.model.core.ClassFieldDto; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.method.CodeTemplateDto; import org.javahelpers.codegen.model.method.MethodDto; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNameWildcard; import org.junit.jupiter.api.Test; /** Unit tests for {@link ImportCollector}: skip rules, generic args and sort order. */ class ImportCollectorTest { + @Test + void convenienceImportMethodsTraverseWildcardBounds() { + TypeNameWildcard wildcard = TypeNameWildcard.extendsBound(new TypeName("java.time", "Instant")); + GenerationTargetClassDto target = classDef("test", "Target"); + ClassFieldDto field = new ClassFieldDto(); + CodeTemplateDto code = new CodeTemplateDto(); + target.addImport(new TypeNameWildcard()); + target.addImport(wildcard); + field.addImport(new TypeNameWildcard()); + field.addImport(wildcard); + code.addCodeBlockImport(new TypeNameWildcard()); + code.addCodeBlockImport(wildcard); + assertEquals( + List.of("java.time.Instant"), + target.getImports().stream().map(ImportStatement::getFullyQualifiedName).toList()); + assertEquals( + List.of("java.time.Instant"), + field.getFieldTypeImports().stream().map(ImportStatement::getFullyQualifiedName).toList()); + assertEquals( + List.of("java.time.Instant"), + code.getCodeBlockImports().stream().map(ImportStatement::getFullyQualifiedName).toList()); + } + + @Test + void collectsWildcardBoundImportsInsteadOfWildcardTokens() { + ImportCollector collector = new ImportCollector(new TypeName("test", "Target")); + collector.addTypeImports(new TypeNameWildcard()); + collector.addTypeImports(TypeNameWildcard.extendsBound(new TypeName("java.time", "Instant"))); + collector.addTypeImports( + TypeNameWildcard.superBound( + new TypeNameGeneric( + TypeName.of(List.class), List.of(new TypeName("java.io", "File"))))); + assertEquals( + List.of("java.io.File", "java.time.Instant", "java.util.List"), + collector.getSortedImports().stream().map(ImportStatement::getFullyQualifiedName).toList()); + } + private static List fqns(GenerationTargetClassDto classDef) { return ImportCollector.collectAndSortImports(classDef).stream() .map(ImportStatement::getFullyQualifiedName) diff --git a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java index b64826a3..6ece4f37 100644 --- a/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java +++ b/codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java @@ -39,6 +39,7 @@ import org.javahelpers.codegen.model.type.TypeNameNested; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.model.type.TypeNameWildcard; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; /** Helper functions to create Roaster-compatible source code strings from DTOs. */ @@ -54,7 +55,14 @@ private RoasterMapper() {} */ public static String mapType(TypeName typeName) { String mappedType; - if (typeName instanceof TypeNameVariable) { + if (typeName instanceof TypeNameWildcard wildcard) { + mappedType = + switch (wildcard.getBoundKind()) { + case UNBOUNDED -> "?"; + case EXTENDS -> "? extends " + mapType(wildcard.getBound().orElseThrow()); + case SUPER -> "? super " + mapType(wildcard.getBound().orElseThrow()); + }; + } else if (typeName instanceof TypeNameVariable) { mappedType = typeName.getClassName(); } else if (typeName instanceof TypeNamePrimitive primitive) { mappedType = primitive.getFullQualifiedName(); diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java index bee5f6e9..42d0e972 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -39,12 +39,29 @@ import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.model.type.TypeNameWildcard; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; import org.junit.jupiter.api.Test; /** Unit tests for {@link RoasterMapper}'s type/annotation/code-template rendering. */ class RoasterMapperTest { + @Test + void rendersWildcardBoundsRecursively() { + assertEquals("?", RoasterMapper.mapType(new TypeNameWildcard())); + assertEquals( + "? extends Number", + RoasterMapper.mapType(TypeNameWildcard.extendsBound(TypeName.of(Number.class)))); + assertEquals( + "? super List", + RoasterMapper.mapType( + TypeNameWildcard.superBound(new TypeNameGeneric(List.class, String.class)))); + assertEquals( + "List", + RoasterMapper.mapType( + new TypeNameGeneric(TypeName.of(List.class), List.of(new TypeNameWildcard())))); + } + @Test void mapType_rendersPlainClassName() { assertEquals("String", RoasterMapper.mapType(TypeName.of(String.class))); diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java index 4bddb965..64aada53 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java @@ -34,6 +34,7 @@ import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNameList; import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.simple.builders.processor.generators.MethodGenerator; @@ -92,6 +93,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateAddToCollectionHelpers()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/FieldInstanceConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/FieldInstanceConsumerGenerator.java index c5369fce..b6c039d2 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/FieldInstanceConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/FieldInstanceConsumerGenerator.java @@ -29,6 +29,7 @@ import java.util.Collections; import java.util.List; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNameList; import org.javahelpers.codegen.model.type.TypeNameMap; import org.javahelpers.codegen.model.type.TypeNameSet; @@ -92,6 +93,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateFieldConsumer()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java index 171dbf32..33b9fc73 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java @@ -101,6 +101,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateBuilderConsumer()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/MapConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/MapConsumerGenerator.java index 1e146f2b..ca34b5eb 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/MapConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/MapConsumerGenerator.java @@ -106,6 +106,11 @@ public int getPriority() { @Override public boolean appliesTo( final BuilderFieldDto field, final TypeName dtoType, final BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + BuilderConfiguration configuration = context.getConfiguration(); TypeName fieldType = field.getFieldType(); return diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/NestedBuilderConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/NestedBuilderConsumerGenerator.java index 55736275..25cd4dad 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/NestedBuilderConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/NestedBuilderConsumerGenerator.java @@ -32,6 +32,7 @@ import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.simple.builders.processor.generators.MethodGenerator; import org.javahelpers.simple.builders.processor.model.core.BuilderFieldDto; import org.javahelpers.simple.builders.processor.model.method.BuilderMethodDto; @@ -91,6 +92,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateBuilderConsumer()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java index 83aa7e96..2918d9e3 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java @@ -85,6 +85,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateUnboxedOptional()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java index afb2e6c7..8c66199b 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java @@ -98,6 +98,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateBuilderConsumer()) { return false; } diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java index 2ed88da9..f5266909 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java @@ -90,6 +90,11 @@ public int getPriority() { @Override public boolean appliesTo( BuilderFieldDto field, TypeName dtoType, BuilderProcessingContext context) { + if (field.getFieldType() instanceof TypeNameGeneric genericType + && genericType.hasWildcardArguments()) { + return false; + } + if (!context.getConfiguration().shouldGenerateVarArgsHelpers()) { return false; } diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/WildcardTypeArgumentsTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/WildcardTypeArgumentsTest.java new file mode 100644 index 00000000..a1fc2def --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/WildcardTypeArgumentsTest.java @@ -0,0 +1,87 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.simple.builders.processor; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.createCompiler; +import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.loadGeneratedSource; + +import com.google.testing.compile.Compilation; +import com.google.testing.compile.JavaFileObjects; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Wildcards survive mapping and compilation without unsafe element-writing helpers. */ +class WildcardTypeArgumentsTest { + @ParameterizedTest + @ValueSource( + strings = { + "List", + "List", + "List", + "List>", + "Set", + "Map", + "Optional", + "ArrayList" + }) + void preservesWildcardSignatures(String type) { + Compilation compilation = + createCompiler() + .withOptions("-Asimplebuilder.strict=true") + .compile( + JavaFileObjects.forSourceString("wild.Foo", "package wild; public class Foo {}"), + JavaFileObjects.forSourceString( + "wild.WildcardDto", + """ + package wild; + import java.util.*; + import org.javahelpers.simple.builders.core.annotations.SimpleBuilder; + @SimpleBuilder + public class WildcardDto { + private %s values; + public %s getValues() { return values; } + public void setValues(%s values) { this.values = values; } + } + """ + .formatted(type, type, type))); + assertThat(compilation).succeeded(); + String source = loadGeneratedSource(compilation, "WildcardDtoBuilder"); + assertContaining( + source, + """ + private TrackedValue<%s> values = unsetValue(); + """ + .formatted(type), + """ + public WildcardDtoBuilder values(%s values) { + this.values = changedValue(values); + return this; + } + """ + .formatted(type)); + } +} diff --git a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java index d0443530..087b7f5e 100644 --- a/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java +++ b/simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangMapper.java @@ -38,6 +38,7 @@ import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; +import javax.lang.model.type.WildcardType; import javax.lang.model.util.SimpleTypeVisitor14; import org.apache.commons.lang3.Strings; import org.javahelpers.codegen.model.annotation.AnnotationDto; @@ -52,6 +53,7 @@ import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.model.type.TypeNameWildcard; /** Helper functions to create codegen {@link TypeName}s from java.lang types. */ public final class JavaLangMapper { @@ -574,6 +576,17 @@ public TypeName visitTypeVariable(TypeVariable t, Void p) { protected TypeName defaultAction(TypeMirror e, Void p) { throw new IllegalArgumentException("Unexpected type mirror: " + e); } + + @Override + public TypeName visitWildcard(WildcardType t, Void p) { + if (t.getExtendsBound() != null) { + return TypeNameWildcard.extendsBound(extractType(t.getExtendsBound(), context)); + } + if (t.getSuperBound() != null) { + return TypeNameWildcard.superBound(extractType(t.getSuperBound(), context)); + } + return new TypeNameWildcard(); + } }, null); diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java index 0f1b9e76..f5ceb584 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -46,12 +46,40 @@ import org.javahelpers.codegen.model.type.TypeNameNested; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameSet; +import org.javahelpers.codegen.model.type.TypeNameWildcard; import org.javahelpers.codegen.processing.AnnotationProcessingContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ class JavaLangMapperTest { + @ParameterizedTest + @ValueSource( + strings = {"?", "? extends java.time.Instant", "? super java.util.List"}) + void mapsWildcardArguments(String argument) { + AtomicReference result = new AtomicReference<>(); + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set( + JavaLangMapper.map2MethodParameter( + parameter(method(dto, "setValues"), 0), context(processingEnv)) + .getParameterType()); + }, + """ + package test; + public class Dto { + public void setValues(java.util.List<%s> values) {} + } + """ + .formatted(argument)); + TypeNameList list = assertInstanceOf(TypeNameList.class, result.get()); + TypeNameWildcard wildcard = assertInstanceOf(TypeNameWildcard.class, list.getElementType()); + assertEquals(argument, wildcard.getFullQualifiedName()); + } + @Test void map2TypeName_mapsJavaClass() { TypeName typeName = JavaLangMapper.map2TypeName(String.class); From 60ed4eff404f861c0147199673eca4f3778b8f9f Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:56:28 +0000 Subject: [PATCH 14/15] feat: complete and reproducibly regenerate codegen DTO builders --- .github/workflows/maven.yml | 6 + .../model/annotation/AnnotationDto.java | 13 + .../annotation/AnnotationDtoBuilder.java | 136 +- .../codegen/model/core/ClassFieldDto.java | 13 + .../model/core/ClassFieldDtoBuilder.java | 155 +- .../model/core/GenerationTargetClassDto.java | 98 ++ .../core/GenerationTargetClassDtoBuilder.java | 1535 +++++++++++++++-- .../javadoc/JavadocCodeBlockDtoBuilder.java | 271 ++- .../codegen/model/javadoc/JavadocDto.java | 12 + .../model/javadoc/JavadocDtoBuilder.java | 130 +- .../codegen/model/method/CodeTemplateDto.java | 25 + .../model/method/CodeTemplateDtoBuilder.java | 270 ++- .../codegen/model/method/ConstructorDto.java | 25 + .../model/method/ConstructorDtoBuilder.java | 335 +++- .../model/method/MethodCodeDtoBuilder.java | 270 ++- .../codegen/model/method/MethodDto.java | 51 + .../model/method/MethodDtoBuilder.java | 642 ++++++- .../model/method/MethodParameterDto.java | 13 + .../method/MethodParameterDtoBuilder.java | 183 +- .../model/type/GenericParameterDto.java | 14 + .../type/GenericParameterDtoBuilder.java | 141 +- .../codegen/model/type/NestedTypeDto.java | 24 + .../model/type/NestedTypeDtoBuilder.java | 343 +++- .../model/core/CodegenDtoBuildersTest.java | 334 ++++ .../GenerationTargetClassDtoBuilderTest.java | 3 +- docs/CODEGEN_BUILDERS.md | 24 + .../CodegenDtoBuilderRegenerationTest.java | 126 ++ 27 files changed, 4965 insertions(+), 227 deletions(-) create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java create mode 100644 docs/CODEGEN_BUILDERS.md create mode 100644 processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 1a63e5d6..3f8b72ae 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -79,6 +79,12 @@ jobs: - name: Build with Maven run: mvn -B install -Pmetrics --file pom.xml + - name: Check committed codegen DTO builders + run: | + mvn -B -pl processor -Dtest=CodegenDtoBuilderRegenerationTest -Dcodegen.regenerate=true test + mvn -B -pl codegen-core fmt:format + git diff --exit-code -- 'codegen-core/src/main/java/**/*Builder.java' + - name: License header check (incl. performance-test) run: mvn -B license:check -Pperformance-test --file pom.xml diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java index 73bfc2a8..916c8211 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java @@ -35,6 +35,19 @@ * and its members in a plain format suitable for code generation. */ public class AnnotationDto { + + /** + * Replaces members with a defensive copy; the DTO retains its own mutable collection. + * + * @param members the replacement collection (not null) + * @throws NullPointerException if members is null + */ + public void setMembers(Map members) { + Map copy = new LinkedHashMap<>(members); + this.members.clear(); + this.members.putAll(copy); + } + /** The annotation type (fully qualified name). */ private TypeName annotationType; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java index 8d6fde37..8e9a9a79 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java @@ -21,12 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.annotation; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.Map; +import java.util.Map.Entry; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -34,6 +37,9 @@ import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.HashMapBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -44,13 +50,28 @@ * org.javahelpers.codegen.model.annotation.AnnotationDto with method chaining and validation. Use * the static {@code create()} method to obtain a new builder instance, configure the desired * properties using the setter methods, and then call {@code build()} to create the final DTO. + * + *

      Example:

      + * + *
      {@code
      + * AnnotationDto result = AnnotationDtoBuilder.create()
      + *     .members(Map.of("example members", "example members"))
      + *     .members(() -> Map.of("example members", "example members"))
      + *     .members(Map.entry("key", "example members"))
      + *     .membersUpdate(Map::copyOf)
      + *     .build();
      + * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class AnnotationDtoBuilder { +@BuilderImplementation(forClass = AnnotationDto.class) +public class AnnotationDtoBuilder implements IBuilderBase { /** Tracked value for annotationType: the type of the annotation. */ private TrackedValue annotationType = unsetValue(); + /** Tracked value for members: the replacement collection (not null). */ + private TrackedValue> members = unsetValue(); + /** * Empty constructor of builder for {@code * org.javahelpers.codegen.model.annotation.AnnotationDto}. @@ -65,6 +86,7 @@ public AnnotationDtoBuilder() {} */ public AnnotationDtoBuilder(AnnotationDto instance) { this.annotationType = initialValue(instance.getAnnotationType()); + this.members = initialValue(instance.getMembers()); } /** @@ -133,6 +155,115 @@ public AnnotationDtoBuilder annotationTypeUpdate(UnaryOperator annotat return this; } + /** + * Sets the value for members. + * + *

      Generated from setter {@link AnnotationDto#setMembers(Map) setMembers(Map + * members)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.members(Map.entry("key", "example members"));
      +   * }
      + * + * @param members the replacement collection (not null) + * @return current instance of builder + */ + public AnnotationDtoBuilder members(Entry... members) { + this.members = changedValue(Map.ofEntries(members)); + return this; + } + + /** + * Sets the value for members using a builder consumer that produces the value. + * + *

      Generated from setter {@link AnnotationDto#setMembers(Map) setMembers(Map + * members)} + * + * @param membersBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public AnnotationDtoBuilder members( + Consumer> membersBuilderConsumer) { + HashMapBuilder builder = + this.members.isSet() + ? new HashMapBuilder(this.members.value()) + : new HashMapBuilder(); + membersBuilderConsumer.accept(builder); + this.members = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for members by invoking the provided supplier. + * + *

      Generated from setter {@link AnnotationDto#setMembers(Map) setMembers(Map + * members)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.members(() -> Map.of("example members", "example members"));
      +   * }
      + * + * @param membersSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public AnnotationDtoBuilder members(Supplier> membersSupplier) { + this.members = changedValue(membersSupplier.get()); + return this; + } + + /** + * Sets the value for members. + * + *

      Generated from setter {@link AnnotationDto#setMembers(Map) setMembers(Map + * members)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.members(Map.of("example members", "example members"));
      +   * }
      + * + * @param members the replacement collection (not null) + * @return current instance of builder + */ + public AnnotationDtoBuilder members(Map members) { + this.members = changedValue(members); + return this; + } + + /** + * Updates the current value of members in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link AnnotationDto#setMembers(Map) setMembers(Map + * members)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.members(Map.of("example members", "example members")).membersUpdate(Map::copyOf);
      +   * }
      + * + * @param membersUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if members has not been set yet + */ + public AnnotationDtoBuilder membersUpdate(UnaryOperator> membersUpdater) { + if (!this.members.isSet()) { + throw new IllegalStateException("Cannot update 'members' before it is set"); + } + this.members = changedValue(membersUpdater.apply(this.members.value())); + return this; + } + /** * Conditionally applies builder modifications if the condition is true. * @@ -174,9 +305,11 @@ public AnnotationDtoBuilder conditional( * AnnotationDto result = builder.build(); * } */ + @Override public AnnotationDto build() { AnnotationDto result = new AnnotationDto(); this.annotationType.ifSet(result::setAnnotationType); + this.members.ifSet(result::setMembers); return result; } @@ -189,6 +322,7 @@ public AnnotationDto build() { public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) .append("annotationType", this.annotationType) + .append("members", this.members) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java index 67fbf592..0fe22271 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java @@ -46,6 +46,19 @@ *

      This DTO contains only rendering information for a field, consumed by the code generator. */ public class ClassFieldDto { + + /** + * Replaces fieldTypeImports with a defensive copy; the DTO retains its own mutable collection. + * + * @param fieldTypeImports the replacement collection (not null) + * @throws NullPointerException if fieldTypeImports is null + */ + public void setFieldTypeImports(Set fieldTypeImports) { + Set copy = new LinkedHashSet<>(fieldTypeImports); + this.fieldTypeImports.clear(); + this.fieldTypeImports.addAll(copy); + } + /** Field name in generated class. */ private String fieldName; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java index 794f5030..7b3782b3 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java @@ -21,12 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.core; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.HashSet; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -34,9 +37,13 @@ import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.imports.ImportStatement; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.HashSetBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -52,24 +59,26 @@ * *

      {@code
        * ClassFieldDto result = ClassFieldDtoBuilder.create()
      - *     .fieldName("example value")
      + *     .fieldName("example fieldName")
        *     .fieldName("Hello %s", "World")
      - *     .fieldName(() -> "example value")
      + *     .fieldName(() -> "example fieldName")
        *     .fieldName(sb -> sb.append("text"))
        *     .fieldNameUpdate(String::trim)
      + *     .fieldTypeImportsUpdate(TreeSet::new)
        *     .javadoc(new JavadocDto())
        *     .javadoc(JavadocDto::new)
        *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
      - *     .literalInitializer("example value")
      + *     .literalInitializer("example literalInitializer")
        *     .literalInitializer("Hello %s", "World")
      - *     .literalInitializer(() -> "example value")
      + *     .literalInitializer(() -> "example literalInitializer")
        *     .literalInitializer(sb -> sb.append("text"))
        *     .literalInitializerUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class ClassFieldDtoBuilder { +@BuilderImplementation(forClass = ClassFieldDto.class) +public class ClassFieldDtoBuilder implements IBuilderBase { /** Tracked value for fieldName: fieldName. */ private TrackedValue fieldName = unsetValue(); @@ -77,6 +86,9 @@ public class ClassFieldDtoBuilder { /** Tracked value for fieldType: fieldType. */ private TrackedValue fieldType = unsetValue(); + /** Tracked value for fieldTypeImports: the replacement collection (not null). */ + private TrackedValue> fieldTypeImports = unsetValue(); + /** Tracked value for javadoc: javadoc. */ private TrackedValue javadoc = unsetValue(); @@ -98,6 +110,7 @@ public ClassFieldDtoBuilder() {} public ClassFieldDtoBuilder(ClassFieldDto instance) { this.fieldName = initialValue(instance.getFieldName()); this.fieldType = initialValue(instance.getFieldType()); + this.fieldTypeImports = initialValue(instance.getFieldTypeImports()); this.javadoc = initialValue(instance.getJavadoc()); this.literalInitializer = initialValue(instance.getLiteralInitializer()); this.visibility = initialValue(instance.getVisibility()); @@ -149,7 +162,7 @@ public ClassFieldDtoBuilder fieldName(Consumer fieldNameStringBui *

      Example:

      * *
      {@code
      -   * builder.fieldName(() -> "example value");
      +   * builder.fieldName(() -> "example fieldName");
          * }
      * * @param fieldNameSupplier supplier for fieldName @@ -191,7 +204,7 @@ public ClassFieldDtoBuilder fieldName(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.fieldName("example value");
      +   * builder.fieldName("example fieldName");
          * }
      * * @param fieldName fieldName @@ -215,7 +228,7 @@ public ClassFieldDtoBuilder fieldName(String fieldName) { *

      Example:

      * *
      {@code
      -   * builder.fieldName("example value").fieldNameUpdate(String::trim);
      +   * builder.fieldName("example fieldName").fieldNameUpdate(String::trim);
          * }
      * * @param fieldNameUpdater operator applied to the current value; its result becomes the new value @@ -280,6 +293,123 @@ public ClassFieldDtoBuilder fieldTypeUpdate(UnaryOperator fieldTypeUpd return this; } + /** + * Adds a single element to fieldTypeImports. + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + * @param element the element to add + * @return current instance of builder + */ + public ClassFieldDtoBuilder add2FieldTypeImports(ImportStatement element) { + Set newCollection; + if (this.fieldTypeImports.isSet()) { + newCollection = new HashSet<>(this.fieldTypeImports.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.fieldTypeImports = changedValue(newCollection); + return this; + } + + /** + * Sets the value for fieldTypeImports. + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + * @param fieldTypeImports the replacement collection (not null) + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldTypeImports(ImportStatement... fieldTypeImports) { + this.fieldTypeImports = changedValue(Set.of(fieldTypeImports)); + return this; + } + + /** + * Sets the value for fieldTypeImports using a builder consumer that produces the + * value. + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + * @param fieldTypeImportsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldTypeImports( + Consumer> fieldTypeImportsBuilderConsumer) { + HashSetBuilder builder = + this.fieldTypeImports.isSet() + ? new HashSetBuilder(this.fieldTypeImports.value()) + : new HashSetBuilder(); + fieldTypeImportsBuilderConsumer.accept(builder); + this.fieldTypeImports = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for fieldTypeImports by invoking the provided supplier. + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + * @param fieldTypeImportsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldTypeImports( + Supplier> fieldTypeImportsSupplier) { + this.fieldTypeImports = changedValue(fieldTypeImportsSupplier.get()); + return this; + } + + /** + * Sets the value for fieldTypeImports. + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + * @param fieldTypeImports the replacement collection (not null) + * @return current instance of builder + */ + public ClassFieldDtoBuilder fieldTypeImports(Set fieldTypeImports) { + this.fieldTypeImports = changedValue(fieldTypeImports); + return this; + } + + /** + * Updates the current value of fieldTypeImports in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link ClassFieldDto#setFieldTypeImports(Set) + * setFieldTypeImports(Set fieldTypeImports)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.fieldTypeImportsUpdate(TreeSet::new);
      +   * }
      + * + * @param fieldTypeImportsUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if fieldTypeImports has not been set yet + */ + public ClassFieldDtoBuilder fieldTypeImportsUpdate( + UnaryOperator> fieldTypeImportsUpdater) { + if (!this.fieldTypeImports.isSet()) { + throw new IllegalStateException("Cannot update 'fieldTypeImports' before it is set"); + } + this.fieldTypeImports = + changedValue(fieldTypeImportsUpdater.apply(this.fieldTypeImports.value())); + return this; + } + /** * Sets the value for javadoc using a builder consumer that produces the value. * @@ -401,7 +531,7 @@ public ClassFieldDtoBuilder literalInitializer( *

      Example:

      * *
      {@code
      -   * builder.literalInitializer(() -> "example value");
      +   * builder.literalInitializer(() -> "example literalInitializer");
          * }
      * * @param literalInitializerSupplier supplier for literalInitializer @@ -443,7 +573,7 @@ public ClassFieldDtoBuilder literalInitializer(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.literalInitializer("example value");
      +   * builder.literalInitializer("example literalInitializer");
          * }
      * * @param literalInitializer literalInitializer @@ -467,7 +597,7 @@ public ClassFieldDtoBuilder literalInitializer(String literalInitializer) { *

      Example:

      * *
      {@code
      -   * builder.literalInitializer("example value").literalInitializerUpdate(String::trim);
      +   * builder.literalInitializer("example literalInitializer").literalInitializerUpdate(String::trim);
          * }
      * * @param literalInitializerUpdater operator applied to the current value; its result becomes the @@ -577,10 +707,12 @@ public ClassFieldDtoBuilder conditional( * ClassFieldDto result = builder.build(); * } */ + @Override public ClassFieldDto build() { ClassFieldDto result = new ClassFieldDto(); this.fieldName.ifSet(result::setFieldName); this.fieldType.ifSet(result::setFieldType); + this.fieldTypeImports.ifSet(result::setFieldTypeImports); this.javadoc.ifSet(result::setJavadoc); this.literalInitializer.ifSet(result::setLiteralInitializer); this.visibility.ifSet(result::setVisibility); @@ -597,6 +729,7 @@ public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) .append("fieldName", this.fieldName) .append("fieldType", this.fieldType) + .append("fieldTypeImports", this.fieldTypeImports) .append("javadoc", this.javadoc) .append("literalInitializer", this.literalInitializer) .append("visibility", this.visibility) diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java index f84636ce..9d659dab 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java @@ -24,6 +24,7 @@ package org.javahelpers.codegen.model.core; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -52,6 +53,103 @@ * independent of whether it's a builder, Jackson module, or other generated class type. */ public class GenerationTargetClassDto { + + /** + * Replaces classFields with a defensive copy; the DTO retains its own mutable collection. + * + * @param classFields the replacement collection (not null) + * @throws NullPointerException if classFields is null + */ + public void setClassFields(List classFields) { + List copy = new ArrayList<>(classFields); + this.classFields.clear(); + this.classFields.addAll(copy); + } + + /** + * Replaces constructors with a defensive copy; the DTO retains its own mutable collection. + * + * @param constructors the replacement collection (not null) + * @throws NullPointerException if constructors is null + */ + public void setConstructors(List constructors) { + List copy = new ArrayList<>(constructors); + this.constructors.clear(); + this.constructors.addAll(copy); + } + + /** + * Replaces methods with a defensive copy; the DTO retains its own mutable collection. + * + * @param methods the replacement collection (not null) + * @throws NullPointerException if methods is null + */ + public void setMethods(List methods) { + List copy = new ArrayList<>(methods); + this.methods.clear(); + this.methods.addAll(copy); + } + + /** + * Replaces generics with a defensive copy; the DTO retains its own mutable collection. + * + * @param generics the replacement collection (not null) + * @throws NullPointerException if generics is null + */ + public void setGenerics(List generics) { + List copy = new ArrayList<>(generics); + this.generics.clear(); + this.generics.addAll(copy); + } + + /** + * Replaces imports with a defensive copy; the DTO retains its own mutable collection. + * + * @param imports the replacement collection (not null) + * @throws NullPointerException if imports is null + */ + public void setImports(Set imports) { + Set copy = new LinkedHashSet<>(imports); + this.imports.clear(); + this.imports.addAll(copy); + } + + /** + * Replaces nestedTypes with a defensive copy; the DTO retains its own mutable collection. + * + * @param nestedTypes the replacement collection (not null) + * @throws NullPointerException if nestedTypes is null + */ + public void setNestedTypes(List nestedTypes) { + List copy = new ArrayList<>(nestedTypes); + this.nestedTypes.clear(); + this.nestedTypes.addAll(copy); + } + + /** + * Replaces classAnnotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param classAnnotations the replacement collection (not null) + * @throws NullPointerException if classAnnotations is null + */ + public void setClassAnnotations(Set classAnnotations) { + Set copy = new LinkedHashSet<>(classAnnotations); + this.classAnnotations.clear(); + this.classAnnotations.addAll(copy); + } + + /** + * Replaces interfaces with a defensive copy; the DTO retains its own mutable collection. + * + * @param interfaces the replacement collection (not null) + * @throws NullPointerException if interfaces is null + */ + public void setInterfaces(Set interfaces) { + Set copy = new LinkedHashSet<>(interfaces); + this.interfaces.clear(); + this.interfaces.addAll(copy); + } + /** Generated class FQN. */ private TypeName typeName; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java index e2700bea..a9caffc0 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java @@ -21,12 +21,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.core; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -35,9 +40,26 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.imports.ImportStatement; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.method.ConstructorDto; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; +import org.javahelpers.codegen.model.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.builders.HashSetBuilder; +import org.javahelpers.simple.builders.core.builders.HashSetBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -53,27 +75,90 @@ * *
      {@code
        * GenerationTargetClassDto result = GenerationTargetClassDtoBuilder.create()
      + *     .classAnnotations(Set.of(AnnotationDtoBuilder.create().build()))
      + *     .classAnnotations(() -> Set.of(AnnotationDtoBuilder.create().build()))
      + *     .classAnnotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder))
      + *     .classAnnotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
      + *     .classAnnotationsUpdate(TreeSet::new)
      + *     .add2ClassAnnotations(AnnotationDtoBuilder.create().build())
      + *     .classFields(List.of(ClassFieldDtoBuilder.create().build()))
      + *     .classFields(() -> List.of(ClassFieldDtoBuilder.create().build()))
      + *     .classFields(t -> t.add(classFieldDtoBuilder -> classFieldDtoBuilder))
      + *     .classFields(ClassFieldDtoBuilder.create().build(), ClassFieldDtoBuilder.create().build())
      + *     .classFieldsUpdate(list -> list.stream().sorted().toList())
      + *     .add2ClassFields(ClassFieldDtoBuilder.create().build())
        *     .classJavadoc(new JavadocDto())
        *     .classJavadoc(JavadocDto::new)
        *     .classJavadoc(javadocDtoBuilder -> javadocDtoBuilder)
      + *     .constructors(List.of(ConstructorDtoBuilder.create().build()))
      + *     .constructors(() -> List.of(ConstructorDtoBuilder.create().build()))
      + *     .constructors(t -> t.add(constructorDtoBuilder -> constructorDtoBuilder))
      + *     .constructors(ConstructorDtoBuilder.create().build(), ConstructorDtoBuilder.create().build())
      + *     .constructorsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Constructors(ConstructorDtoBuilder.create().build())
      + *     .generics(List.of(GenericParameterDtoBuilder.create().build()))
      + *     .generics(() -> List.of(GenericParameterDtoBuilder.create().build()))
      + *     .generics(t -> t.add(genericParameterDtoBuilder -> genericParameterDtoBuilder))
      + *     .generics(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build())
      + *     .genericsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Generics(GenericParameterDtoBuilder.create().build())
      + *     .importsUpdate(TreeSet::new)
      + *     .interfacesUpdate(TreeSet::new)
      + *     .methods(List.of(MethodDtoBuilder.create().build()))
      + *     .methods(() -> List.of(MethodDtoBuilder.create().build()))
      + *     .methods(t -> t.add(methodDtoBuilder -> methodDtoBuilder))
      + *     .methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build())
      + *     .methodsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Methods(MethodDtoBuilder.create().build())
      + *     .nestedTypes(List.of(NestedTypeDtoBuilder.create().build()))
      + *     .nestedTypes(() -> List.of(NestedTypeDtoBuilder.create().build()))
      + *     .nestedTypes(t -> t.add(nestedTypeDtoBuilder -> nestedTypeDtoBuilder))
      + *     .nestedTypes(NestedTypeDtoBuilder.create().build(), NestedTypeDtoBuilder.create().build())
      + *     .nestedTypesUpdate(list -> list.stream().sorted().toList())
      + *     .add2NestedTypes(NestedTypeDtoBuilder.create().build())
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class GenerationTargetClassDtoBuilder { +@BuilderImplementation(forClass = GenerationTargetClassDto.class) +public class GenerationTargetClassDtoBuilder implements IBuilderBase { /** Tracked value for classAccessModifier: classAccessModifier. */ private TrackedValue classAccessModifier = unsetValue(); + /** Tracked value for classAnnotations: the replacement collection (not null). */ + private TrackedValue> classAnnotations = unsetValue(); + + /** Tracked value for classFields: the replacement collection (not null). */ + private TrackedValue> classFields = unsetValue(); + /** Tracked value for classJavadoc: the class JavaDoc to set. */ private TrackedValue classJavadoc = unsetValue(); + /** Tracked value for constructors: the replacement collection (not null). */ + private TrackedValue> constructors = unsetValue(); + /** * Tracked value for formattingMode: the formatting mode, or null to use the global * default. */ private TrackedValue formattingMode = unsetValue(); + /** Tracked value for generics: the replacement collection (not null). */ + private TrackedValue> generics = unsetValue(); + + /** Tracked value for imports: the replacement collection (not null). */ + private TrackedValue> imports = unsetValue(); + + /** Tracked value for interfaces: the replacement collection (not null). */ + private TrackedValue> interfaces = unsetValue(); + + /** Tracked value for methods: the replacement collection (not null). */ + private TrackedValue> methods = unsetValue(); + + /** Tracked value for nestedTypes: the replacement collection (not null). */ + private TrackedValue> nestedTypes = unsetValue(); + /** Tracked value for superType: superType. */ private TrackedValue superType = unsetValue(); @@ -94,8 +179,16 @@ public GenerationTargetClassDtoBuilder() {} */ public GenerationTargetClassDtoBuilder(GenerationTargetClassDto instance) { this.classAccessModifier = initialValue(instance.getClassAccessModifier()); + this.classAnnotations = initialValue(instance.getClassAnnotations()); + this.classFields = initialValue(instance.getClassFields()); this.classJavadoc = initialValue(instance.getClassJavadoc()); + this.constructors = initialValue(instance.getConstructors()); this.formattingMode = initialValue(instance.getFormattingMode()); + this.generics = initialValue(instance.getGenerics()); + this.imports = initialValue(instance.getImports()); + this.interfaces = initialValue(instance.getInterfaces()); + this.methods = initialValue(instance.getMethods()); + this.nestedTypes = initialValue(instance.getNestedTypes()); this.superType = initialValue(instance.getSuperType()); this.typeName = initialValue(instance.getTypeName()); } @@ -170,297 +263,1433 @@ public GenerationTargetClassDtoBuilder classAccessModifierUpdate( } /** - * Sets the value for classJavadoc using a builder consumer that produces the value. + * Adds a single element to classAnnotations. * - *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) - * setClassJavadoc(JavadocDto classJavadoc)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * *

      Example:

      * *
      {@code
      -   * builder.classJavadoc(javadocDtoBuilder -> javadocDtoBuilder);
      +   * builder.add2ClassAnnotations(AnnotationDtoBuilder.create().build());
          * }
      * - * @param classJavadocBuilderConsumer consumer providing an instance of a builder for the class - * JavaDoc to set + * @param element the element to add * @return current instance of builder */ - public GenerationTargetClassDtoBuilder classJavadoc( - Consumer classJavadocBuilderConsumer) { - JavadocDtoBuilder builder = - this.classJavadoc.isSet() - ? new JavadocDtoBuilder(this.classJavadoc.value()) - : JavadocDtoBuilder.create(); - classJavadocBuilderConsumer.accept(builder); - this.classJavadoc = changedValue(builder.build()); + public GenerationTargetClassDtoBuilder add2ClassAnnotations(AnnotationDto element) { + Set newCollection; + if (this.classAnnotations.isSet()) { + newCollection = new HashSet<>(this.classAnnotations.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.classAnnotations = changedValue(newCollection); return this; } /** - * Sets the value for classJavadoc by invoking the provided supplier. + * Sets the value for classAnnotations. * - *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) - * setClassJavadoc(JavadocDto classJavadoc)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * *

      Example:

      * *
      {@code
      -   * builder.classJavadoc(JavadocDto::new);
      +   * builder.classAnnotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build());
          * }
      * - * @param classJavadocSupplier supplier for the class JavaDoc to set + * @param classAnnotations the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder classJavadoc(Supplier classJavadocSupplier) { - this.classJavadoc = changedValue(classJavadocSupplier.get()); + public GenerationTargetClassDtoBuilder classAnnotations(AnnotationDto... classAnnotations) { + this.classAnnotations = changedValue(Set.of(classAnnotations)); return this; } /** - * Sets the value for classJavadoc. + * Sets the value for classAnnotations using a builder consumer that produces the + * value. * - *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) - * setClassJavadoc(JavadocDto classJavadoc)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * *

      Example:

      * *
      {@code
      -   * builder.classJavadoc(new JavadocDto());
      +   * builder.classAnnotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
          * }
      * - * @param classJavadoc the class JavaDoc to set + * @param classAnnotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder classJavadoc(JavadocDto classJavadoc) { - this.classJavadoc = changedValue(classJavadoc); + public GenerationTargetClassDtoBuilder classAnnotations( + Consumer> + classAnnotationsBuilderConsumer) { + HashSetBuilderWithElementBuilders builder = + this.classAnnotations.isSet() + ? new HashSetBuilderWithElementBuilders( + this.classAnnotations.value(), AnnotationDtoBuilder::create) + : new HashSetBuilderWithElementBuilders( + AnnotationDtoBuilder::create); + classAnnotationsBuilderConsumer.accept(builder); + this.classAnnotations = changedValue(builder.build()); return this; } /** - * Updates the current value of classJavadoc in place by applying the given operator, - * instead of reading it out, changing it and setting it again. Useful for adjustments relative to - * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination - * with the With copy-and-modify flow. The value must have been set before (directly - * or via an existing instance). For changing multiple values of a nested DTO, prefer the - * builder-consumer helper {@link #classJavadoc(Consumer)}. + * Sets the value for classAnnotations by invoking the provided supplier. * - *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) - * setClassJavadoc(JavadocDto classJavadoc)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * - * @param classJavadocUpdater operator applied to the current value; its result becomes the new - * value - * @return current instance of builder - * @throws IllegalStateException if classJavadoc has not been set yet - */ - public GenerationTargetClassDtoBuilder classJavadocUpdate( - UnaryOperator classJavadocUpdater) { - if (!this.classJavadoc.isSet()) { - throw new IllegalStateException("Cannot update 'classJavadoc' before it is set"); - } - this.classJavadoc = changedValue(classJavadocUpdater.apply(this.classJavadoc.value())); - return this; - } - - /** - * Sets the value for formattingMode by invoking the provided supplier. + *

      Example:

      * - *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) - * setFormattingMode(FormattingMode formattingMode)} + *

      {@code
      +   * builder.classAnnotations(() -> Set.of(AnnotationDtoBuilder.create().build()));
      +   * }
      * - * @param formattingModeSupplier supplier for the formatting mode, or null to use the global - * default + * @param classAnnotationsSupplier supplier for the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder formattingMode( - Supplier formattingModeSupplier) { - this.formattingMode = changedValue(formattingModeSupplier.get()); + public GenerationTargetClassDtoBuilder classAnnotations( + Supplier> classAnnotationsSupplier) { + this.classAnnotations = changedValue(classAnnotationsSupplier.get()); return this; } /** - * Sets the value for formattingMode. + * Sets the value for classAnnotations. * - *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) - * setFormattingMode(FormattingMode formattingMode)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * - * @param formattingMode the formatting mode, or null to use the global default + *

      Example:

      + * + *
      {@code
      +   * builder.classAnnotations(Set.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param classAnnotations the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder formattingMode(FormattingMode formattingMode) { - this.formattingMode = changedValue(formattingMode); + public GenerationTargetClassDtoBuilder classAnnotations(Set classAnnotations) { + this.classAnnotations = changedValue(classAnnotations); return this; } /** - * Updates the current value of formattingMode in place by applying the given + * Updates the current value of classAnnotations in place by applying the given * operator, instead of reading it out, changing it and setting it again. Useful for adjustments * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in * combination with the With copy-and-modify flow. The value must have been set - * before (directly or via an existing instance). + * before (directly or via an existing instance). For changing multiple elements of a nested DTO, + * prefer the builder-consumer helper {@link #classAnnotations(Consumer)}. * - *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) - * setFormattingMode(FormattingMode formattingMode)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassAnnotations(Set) + * setClassAnnotations(Set classAnnotations)} * - * @param formattingModeUpdater operator applied to the current value; its result becomes the new - * value + *

      Example:

      + * + *
      {@code
      +   * builder.classAnnotations(Set.of(AnnotationDtoBuilder.create().build())).classAnnotationsUpdate(TreeSet::new);
      +   * }
      + * + * @param classAnnotationsUpdater operator applied to the current value; its result becomes the + * new value * @return current instance of builder - * @throws IllegalStateException if formattingMode has not been set yet + * @throws IllegalStateException if classAnnotations has not been set yet */ - public GenerationTargetClassDtoBuilder formattingModeUpdate( - UnaryOperator formattingModeUpdater) { - if (!this.formattingMode.isSet()) { - throw new IllegalStateException("Cannot update 'formattingMode' before it is set"); + public GenerationTargetClassDtoBuilder classAnnotationsUpdate( + UnaryOperator> classAnnotationsUpdater) { + if (!this.classAnnotations.isSet()) { + throw new IllegalStateException("Cannot update 'classAnnotations' before it is set"); } - this.formattingMode = changedValue(formattingModeUpdater.apply(this.formattingMode.value())); + this.classAnnotations = + changedValue(classAnnotationsUpdater.apply(this.classAnnotations.value())); return this; } /** - * Sets the value for superType by invoking the provided supplier. + * Adds a single element to classFields. * - *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) - * setSuperType(TypeName superType)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param superTypeSupplier supplier for superType + *

      Example:

      + * + *
      {@code
      +   * builder.add2ClassFields(ClassFieldDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add * @return current instance of builder */ - public GenerationTargetClassDtoBuilder superType(Supplier superTypeSupplier) { - this.superType = changedValue(superTypeSupplier.get()); + public GenerationTargetClassDtoBuilder add2ClassFields(ClassFieldDto element) { + List newCollection; + if (this.classFields.isSet()) { + newCollection = new ArrayList<>(this.classFields.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.classFields = changedValue(newCollection); return this; } /** - * Sets the value for superType. + * Sets the value for classFields. * - *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) - * setSuperType(TypeName superType)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param superType superType + *

      Example:

      + * + *
      {@code
      +   * builder.classFields(ClassFieldDtoBuilder.create().build(), ClassFieldDtoBuilder.create().build());
      +   * }
      + * + * @param classFields the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder superType(TypeName superType) { - this.superType = changedValue(superType); + public GenerationTargetClassDtoBuilder classFields(ClassFieldDto... classFields) { + this.classFields = changedValue(List.of(classFields)); return this; } /** - * Updates the current value of superType in place by applying the given operator, - * instead of reading it out, changing it and setting it again. Useful for adjustments relative to - * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination - * with the With copy-and-modify flow. The value must have been set before (directly - * or via an existing instance). + * Sets the value for classFields using a builder consumer that produces the value. * - *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) - * setSuperType(TypeName superType)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param superTypeUpdater operator applied to the current value; its result becomes the new value + *

      Example:

      + * + *
      {@code
      +   * builder.classFields(t -> t.add(classFieldDtoBuilder -> classFieldDtoBuilder));
      +   * }
      + * + * @param classFieldsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) * @return current instance of builder - * @throws IllegalStateException if superType has not been set yet */ - public GenerationTargetClassDtoBuilder superTypeUpdate(UnaryOperator superTypeUpdater) { - if (!this.superType.isSet()) { - throw new IllegalStateException("Cannot update 'superType' before it is set"); - } - this.superType = changedValue(superTypeUpdater.apply(this.superType.value())); + public GenerationTargetClassDtoBuilder classFields( + Consumer> + classFieldsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.classFields.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.classFields.value(), ClassFieldDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + ClassFieldDtoBuilder::create); + classFieldsBuilderConsumer.accept(builder); + this.classFields = changedValue(builder.build()); return this; } /** - * Sets the value for typeName by invoking the provided supplier. + * Sets the value for classFields by invoking the provided supplier. * - *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) - * setTypeName(TypeName typeName)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param typeNameSupplier supplier for typeName + *

      Example:

      + * + *
      {@code
      +   * builder.classFields(() -> List.of(ClassFieldDtoBuilder.create().build()));
      +   * }
      + * + * @param classFieldsSupplier supplier for the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder typeName(Supplier typeNameSupplier) { - this.typeName = changedValue(typeNameSupplier.get()); + public GenerationTargetClassDtoBuilder classFields( + Supplier> classFieldsSupplier) { + this.classFields = changedValue(classFieldsSupplier.get()); return this; } /** - * Sets the value for typeName. + * Sets the value for classFields. * - *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) - * setTypeName(TypeName typeName)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param typeName typeName + *

      Example:

      + * + *
      {@code
      +   * builder.classFields(List.of(ClassFieldDtoBuilder.create().build()));
      +   * }
      + * + * @param classFields the replacement collection (not null) * @return current instance of builder */ - public GenerationTargetClassDtoBuilder typeName(TypeName typeName) { - this.typeName = changedValue(typeName); + public GenerationTargetClassDtoBuilder classFields(List classFields) { + this.classFields = changedValue(classFields); return this; } /** - * Updates the current value of typeName in place by applying the given operator, + * Updates the current value of classFields in place by applying the given operator, * instead of reading it out, changing it and setting it again. Useful for adjustments relative to * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination * with the With copy-and-modify flow. The value must have been set before (directly - * or via an existing instance). + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #classFields(Consumer)}. * - *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) - * setTypeName(TypeName typeName)} + *

      Generated from setter {@link GenerationTargetClassDto#setClassFields(List) + * setClassFields(List classFields)} * - * @param typeNameUpdater operator applied to the current value; its result becomes the new value + *

      Example:

      + * + *
      {@code
      +   * builder.classFields(List.of(ClassFieldDtoBuilder.create().build()))
      +   *     .classFieldsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param classFieldsUpdater operator applied to the current value; its result becomes the new + * value * @return current instance of builder - * @throws IllegalStateException if typeName has not been set yet + * @throws IllegalStateException if classFields has not been set yet */ - public GenerationTargetClassDtoBuilder typeNameUpdate(UnaryOperator typeNameUpdater) { - if (!this.typeName.isSet()) { - throw new IllegalStateException("Cannot update 'typeName' before it is set"); + public GenerationTargetClassDtoBuilder classFieldsUpdate( + UnaryOperator> classFieldsUpdater) { + if (!this.classFields.isSet()) { + throw new IllegalStateException("Cannot update 'classFields' before it is set"); } - this.typeName = changedValue(typeNameUpdater.apply(this.typeName.value())); + this.classFields = changedValue(classFieldsUpdater.apply(this.classFields.value())); return this; } /** - * Conditionally applies builder modifications if the condition is true. + * Sets the value for classJavadoc using a builder consumer that produces the value. * - * @param condition the condition to evaluate - * @param yesCondition the consumer to apply if condition is true - * @return this builder instance + *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.classJavadoc(javadocDtoBuilder -> javadocDtoBuilder);
      +   * }
      + * + * @param classJavadocBuilderConsumer consumer providing an instance of a builder for the class + * JavaDoc to set + * @return current instance of builder */ - public GenerationTargetClassDtoBuilder conditional( - BooleanSupplier condition, Consumer yesCondition) { - return conditional(condition, yesCondition, null); + public GenerationTargetClassDtoBuilder classJavadoc( + Consumer classJavadocBuilderConsumer) { + JavadocDtoBuilder builder = + this.classJavadoc.isSet() + ? new JavadocDtoBuilder(this.classJavadoc.value()) + : JavadocDtoBuilder.create(); + classJavadocBuilderConsumer.accept(builder); + this.classJavadoc = changedValue(builder.build()); + return this; } /** - * Conditionally applies builder modifications based on a condition evaluation. + * Sets the value for classJavadoc by invoking the provided supplier. * - * @param condition the condition to evaluate - * @param trueCase the consumer to apply if condition is true - * @param falseCase the consumer to apply if condition is false (can be null) - * @return this builder instance + *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.classJavadoc(JavadocDto::new);
      +   * }
      + * + * @param classJavadocSupplier supplier for the class JavaDoc to set + * @return current instance of builder */ - public GenerationTargetClassDtoBuilder conditional( - BooleanSupplier condition, - Consumer trueCase, - Consumer falseCase) { - if (condition.getAsBoolean()) { - trueCase.accept(this); - } else if (falseCase != null) { - falseCase.accept(this); - } + public GenerationTargetClassDtoBuilder classJavadoc(Supplier classJavadocSupplier) { + this.classJavadoc = changedValue(classJavadocSupplier.get()); return this; } /** - * Builds the configured DTO instance. + * Sets the value for classJavadoc. + * + *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} * *

      Example:

      * *
      {@code
      -   * GenerationTargetClassDto result = builder.build();
      +   * builder.classJavadoc(new JavadocDto());
          * }
      + * + * @param classJavadoc the class JavaDoc to set + * @return current instance of builder */ + public GenerationTargetClassDtoBuilder classJavadoc(JavadocDto classJavadoc) { + this.classJavadoc = changedValue(classJavadoc); + return this; + } + + /** + * Updates the current value of classJavadoc in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple values of a nested DTO, prefer the + * builder-consumer helper {@link #classJavadoc(Consumer)}. + * + *

      Generated from setter {@link GenerationTargetClassDto#setClassJavadoc(JavadocDto) + * setClassJavadoc(JavadocDto classJavadoc)} + * + * @param classJavadocUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if classJavadoc has not been set yet + */ + public GenerationTargetClassDtoBuilder classJavadocUpdate( + UnaryOperator classJavadocUpdater) { + if (!this.classJavadoc.isSet()) { + throw new IllegalStateException("Cannot update 'classJavadoc' before it is set"); + } + this.classJavadoc = changedValue(classJavadocUpdater.apply(this.classJavadoc.value())); + return this; + } + + /** + * Adds a single element to constructors. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Constructors(ConstructorDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2Constructors(ConstructorDto element) { + List newCollection; + if (this.constructors.isSet()) { + newCollection = new ArrayList<>(this.constructors.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.constructors = changedValue(newCollection); + return this; + } + + /** + * Sets the value for constructors. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.constructors(ConstructorDtoBuilder.create().build(), ConstructorDtoBuilder.create().build());
      +   * }
      + * + * @param constructors the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder constructors(ConstructorDto... constructors) { + this.constructors = changedValue(List.of(constructors)); + return this; + } + + /** + * Sets the value for constructors using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.constructors(t -> t.add(constructorDtoBuilder -> constructorDtoBuilder));
      +   * }
      + * + * @param constructorsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder constructors( + Consumer> + constructorsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.constructors.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.constructors.value(), ConstructorDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + ConstructorDtoBuilder::create); + constructorsBuilderConsumer.accept(builder); + this.constructors = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for constructors by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.constructors(() -> List.of(ConstructorDtoBuilder.create().build()));
      +   * }
      + * + * @param constructorsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder constructors( + Supplier> constructorsSupplier) { + this.constructors = changedValue(constructorsSupplier.get()); + return this; + } + + /** + * Sets the value for constructors. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.constructors(List.of(ConstructorDtoBuilder.create().build()));
      +   * }
      + * + * @param constructors the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder constructors(List constructors) { + this.constructors = changedValue(constructors); + return this; + } + + /** + * Updates the current value of constructors in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #constructors(Consumer)}. + * + *

      Generated from setter {@link GenerationTargetClassDto#setConstructors(List) + * setConstructors(List constructors)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.constructors(List.of(ConstructorDtoBuilder.create().build()))
      +   *     .constructorsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param constructorsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if constructors has not been set yet + */ + public GenerationTargetClassDtoBuilder constructorsUpdate( + UnaryOperator> constructorsUpdater) { + if (!this.constructors.isSet()) { + throw new IllegalStateException("Cannot update 'constructors' before it is set"); + } + this.constructors = changedValue(constructorsUpdater.apply(this.constructors.value())); + return this; + } + + /** + * Sets the value for formattingMode by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingModeSupplier supplier for the formatting mode, or null to use the global + * default + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder formattingMode( + Supplier formattingModeSupplier) { + this.formattingMode = changedValue(formattingModeSupplier.get()); + return this; + } + + /** + * Sets the value for formattingMode. + * + *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingMode the formatting mode, or null to use the global default + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder formattingMode(FormattingMode formattingMode) { + this.formattingMode = changedValue(formattingMode); + return this; + } + + /** + * Updates the current value of formattingMode in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link GenerationTargetClassDto#setFormattingMode(FormattingMode) + * setFormattingMode(FormattingMode formattingMode)} + * + * @param formattingModeUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if formattingMode has not been set yet + */ + public GenerationTargetClassDtoBuilder formattingModeUpdate( + UnaryOperator formattingModeUpdater) { + if (!this.formattingMode.isSet()) { + throw new IllegalStateException("Cannot update 'formattingMode' before it is set"); + } + this.formattingMode = changedValue(formattingModeUpdater.apply(this.formattingMode.value())); + return this; + } + + /** + * Adds a single element to generics. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Generics(GenericParameterDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2Generics(GenericParameterDto element) { + List newCollection; + if (this.generics.isSet()) { + newCollection = new ArrayList<>(this.generics.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.generics = changedValue(newCollection); + return this; + } + + /** + * Sets the value for generics. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.generics(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build());
      +   * }
      + * + * @param generics the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder generics(GenericParameterDto... generics) { + this.generics = changedValue(List.of(generics)); + return this; + } + + /** + * Sets the value for generics using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.generics(t -> t.add(genericParameterDtoBuilder -> genericParameterDtoBuilder));
      +   * }
      + * + * @param genericsBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder generics( + Consumer> + genericsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.generics.isSet() + ? new ArrayListBuilderWithElementBuilders< + GenericParameterDto, GenericParameterDtoBuilder>( + this.generics.value(), GenericParameterDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders< + GenericParameterDto, GenericParameterDtoBuilder>( + GenericParameterDtoBuilder::create); + genericsBuilderConsumer.accept(builder); + this.generics = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for generics by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.generics(() -> List.of(GenericParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param genericsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder generics( + Supplier> genericsSupplier) { + this.generics = changedValue(genericsSupplier.get()); + return this; + } + + /** + * Sets the value for generics. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.generics(List.of(GenericParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param generics the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder generics(List generics) { + this.generics = changedValue(generics); + return this; + } + + /** + * Updates the current value of generics in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #generics(Consumer)}. + * + *

      Generated from setter {@link GenerationTargetClassDto#setGenerics(List) + * setGenerics(List generics)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.generics(List.of(GenericParameterDtoBuilder.create().build()))
      +   *     .genericsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param genericsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if generics has not been set yet + */ + public GenerationTargetClassDtoBuilder genericsUpdate( + UnaryOperator> genericsUpdater) { + if (!this.generics.isSet()) { + throw new IllegalStateException("Cannot update 'generics' before it is set"); + } + this.generics = changedValue(genericsUpdater.apply(this.generics.value())); + return this; + } + + /** + * Adds a single element to imports. + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2Imports(ImportStatement element) { + Set newCollection; + if (this.imports.isSet()) { + newCollection = new HashSet<>(this.imports.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.imports = changedValue(newCollection); + return this; + } + + /** + * Sets the value for imports. + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + * @param imports the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder imports(ImportStatement... imports) { + this.imports = changedValue(Set.of(imports)); + return this; + } + + /** + * Sets the value for imports using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + * @param importsBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder imports( + Consumer> importsBuilderConsumer) { + HashSetBuilder builder = + this.imports.isSet() + ? new HashSetBuilder(this.imports.value()) + : new HashSetBuilder(); + importsBuilderConsumer.accept(builder); + this.imports = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for imports by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + * @param importsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder imports(Supplier> importsSupplier) { + this.imports = changedValue(importsSupplier.get()); + return this; + } + + /** + * Sets the value for imports. + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + * @param imports the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder imports(Set imports) { + this.imports = changedValue(imports); + return this; + } + + /** + * Updates the current value of imports in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link GenerationTargetClassDto#setImports(Set) + * setImports(Set imports)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.importsUpdate(TreeSet::new);
      +   * }
      + * + * @param importsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if imports has not been set yet + */ + public GenerationTargetClassDtoBuilder importsUpdate( + UnaryOperator> importsUpdater) { + if (!this.imports.isSet()) { + throw new IllegalStateException("Cannot update 'imports' before it is set"); + } + this.imports = changedValue(importsUpdater.apply(this.imports.value())); + return this; + } + + /** + * Adds a single element to interfaces. + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2Interfaces(InterfaceName element) { + Set newCollection; + if (this.interfaces.isSet()) { + newCollection = new HashSet<>(this.interfaces.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.interfaces = changedValue(newCollection); + return this; + } + + /** + * Sets the value for interfaces. + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + * @param interfaces the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder interfaces(InterfaceName... interfaces) { + this.interfaces = changedValue(Set.of(interfaces)); + return this; + } + + /** + * Sets the value for interfaces using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + * @param interfacesBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder interfaces( + Consumer> interfacesBuilderConsumer) { + HashSetBuilder builder = + this.interfaces.isSet() + ? new HashSetBuilder(this.interfaces.value()) + : new HashSetBuilder(); + interfacesBuilderConsumer.accept(builder); + this.interfaces = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for interfaces by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + * @param interfacesSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder interfaces( + Supplier> interfacesSupplier) { + this.interfaces = changedValue(interfacesSupplier.get()); + return this; + } + + /** + * Sets the value for interfaces. + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + * @param interfaces the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder interfaces(Set interfaces) { + this.interfaces = changedValue(interfaces); + return this; + } + + /** + * Updates the current value of interfaces in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link GenerationTargetClassDto#setInterfaces(Set) + * setInterfaces(Set interfaces)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.interfacesUpdate(TreeSet::new);
      +   * }
      + * + * @param interfacesUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if interfaces has not been set yet + */ + public GenerationTargetClassDtoBuilder interfacesUpdate( + UnaryOperator> interfacesUpdater) { + if (!this.interfaces.isSet()) { + throw new IllegalStateException("Cannot update 'interfaces' before it is set"); + } + this.interfaces = changedValue(interfacesUpdater.apply(this.interfaces.value())); + return this; + } + + /** + * Adds a single element to methods. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Methods(MethodDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2Methods(MethodDto element) { + List newCollection; + if (this.methods.isSet()) { + newCollection = new ArrayList<>(this.methods.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.methods = changedValue(newCollection); + return this; + } + + /** + * Sets the value for methods. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build());
      +   * }
      + * + * @param methods the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder methods(MethodDto... methods) { + this.methods = changedValue(List.of(methods)); + return this; + } + + /** + * Sets the value for methods using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(t -> t.add(methodDtoBuilder -> methodDtoBuilder));
      +   * }
      + * + * @param methodsBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder methods( + Consumer> + methodsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.methods.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.methods.value(), MethodDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + MethodDtoBuilder::create); + methodsBuilderConsumer.accept(builder); + this.methods = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for methods by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(() -> List.of(MethodDtoBuilder.create().build()));
      +   * }
      + * + * @param methodsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder methods(Supplier> methodsSupplier) { + this.methods = changedValue(methodsSupplier.get()); + return this; + } + + /** + * Sets the value for methods. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(List.of(MethodDtoBuilder.create().build()));
      +   * }
      + * + * @param methods the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder methods(List methods) { + this.methods = changedValue(methods); + return this; + } + + /** + * Updates the current value of methods in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #methods(Consumer)}. + * + *

      Generated from setter {@link GenerationTargetClassDto#setMethods(List) + * setMethods(List methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(List.of(MethodDtoBuilder.create().build())).methodsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param methodsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if methods has not been set yet + */ + public GenerationTargetClassDtoBuilder methodsUpdate( + UnaryOperator> methodsUpdater) { + if (!this.methods.isSet()) { + throw new IllegalStateException("Cannot update 'methods' before it is set"); + } + this.methods = changedValue(methodsUpdater.apply(this.methods.value())); + return this; + } + + /** + * Adds a single element to nestedTypes. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2NestedTypes(NestedTypeDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder add2NestedTypes(NestedTypeDto element) { + List newCollection; + if (this.nestedTypes.isSet()) { + newCollection = new ArrayList<>(this.nestedTypes.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.nestedTypes = changedValue(newCollection); + return this; + } + + /** + * Sets the value for nestedTypes. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.nestedTypes(NestedTypeDtoBuilder.create().build(), NestedTypeDtoBuilder.create().build());
      +   * }
      + * + * @param nestedTypes the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder nestedTypes(NestedTypeDto... nestedTypes) { + this.nestedTypes = changedValue(List.of(nestedTypes)); + return this; + } + + /** + * Sets the value for nestedTypes using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.nestedTypes(t -> t.add(nestedTypeDtoBuilder -> nestedTypeDtoBuilder));
      +   * }
      + * + * @param nestedTypesBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder nestedTypes( + Consumer> + nestedTypesBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.nestedTypes.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.nestedTypes.value(), NestedTypeDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + NestedTypeDtoBuilder::create); + nestedTypesBuilderConsumer.accept(builder); + this.nestedTypes = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for nestedTypes by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.nestedTypes(() -> List.of(NestedTypeDtoBuilder.create().build()));
      +   * }
      + * + * @param nestedTypesSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder nestedTypes( + Supplier> nestedTypesSupplier) { + this.nestedTypes = changedValue(nestedTypesSupplier.get()); + return this; + } + + /** + * Sets the value for nestedTypes. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.nestedTypes(List.of(NestedTypeDtoBuilder.create().build()));
      +   * }
      + * + * @param nestedTypes the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder nestedTypes(List nestedTypes) { + this.nestedTypes = changedValue(nestedTypes); + return this; + } + + /** + * Updates the current value of nestedTypes in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #nestedTypes(Consumer)}. + * + *

      Generated from setter {@link GenerationTargetClassDto#setNestedTypes(List) + * setNestedTypes(List nestedTypes)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.nestedTypes(List.of(NestedTypeDtoBuilder.create().build()))
      +   *     .nestedTypesUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param nestedTypesUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if nestedTypes has not been set yet + */ + public GenerationTargetClassDtoBuilder nestedTypesUpdate( + UnaryOperator> nestedTypesUpdater) { + if (!this.nestedTypes.isSet()) { + throw new IllegalStateException("Cannot update 'nestedTypes' before it is set"); + } + this.nestedTypes = changedValue(nestedTypesUpdater.apply(this.nestedTypes.value())); + return this; + } + + /** + * Sets the value for superType by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superTypeSupplier supplier for superType + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder superType(Supplier superTypeSupplier) { + this.superType = changedValue(superTypeSupplier.get()); + return this; + } + + /** + * Sets the value for superType. + * + *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superType superType + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder superType(TypeName superType) { + this.superType = changedValue(superType); + return this; + } + + /** + * Updates the current value of superType in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link GenerationTargetClassDto#setSuperType(TypeName) + * setSuperType(TypeName superType)} + * + * @param superTypeUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if superType has not been set yet + */ + public GenerationTargetClassDtoBuilder superTypeUpdate(UnaryOperator superTypeUpdater) { + if (!this.superType.isSet()) { + throw new IllegalStateException("Cannot update 'superType' before it is set"); + } + this.superType = changedValue(superTypeUpdater.apply(this.superType.value())); + return this; + } + + /** + * Sets the value for typeName by invoking the provided supplier. + * + *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeNameSupplier supplier for typeName + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder typeName(Supplier typeNameSupplier) { + this.typeName = changedValue(typeNameSupplier.get()); + return this; + } + + /** + * Sets the value for typeName. + * + *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeName typeName + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder typeName(TypeName typeName) { + this.typeName = changedValue(typeName); + return this; + } + + /** + * Updates the current value of typeName in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link GenerationTargetClassDto#setTypeName(TypeName) + * setTypeName(TypeName typeName)} + * + * @param typeNameUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if typeName has not been set yet + */ + public GenerationTargetClassDtoBuilder typeNameUpdate(UnaryOperator typeNameUpdater) { + if (!this.typeName.isSet()) { + throw new IllegalStateException("Cannot update 'typeName' before it is set"); + } + this.typeName = changedValue(typeNameUpdater.apply(this.typeName.value())); + return this; + } + + /** + * Conditionally applies builder modifications if the condition is true. + * + * @param condition the condition to evaluate + * @param yesCondition the consumer to apply if condition is true + * @return this builder instance + */ + public GenerationTargetClassDtoBuilder conditional( + BooleanSupplier condition, Consumer yesCondition) { + return conditional(condition, yesCondition, null); + } + + /** + * Conditionally applies builder modifications based on a condition evaluation. + * + * @param condition the condition to evaluate + * @param trueCase the consumer to apply if condition is true + * @param falseCase the consumer to apply if condition is false (can be null) + * @return this builder instance + */ + public GenerationTargetClassDtoBuilder conditional( + BooleanSupplier condition, + Consumer trueCase, + Consumer falseCase) { + if (condition.getAsBoolean()) { + trueCase.accept(this); + } else if (falseCase != null) { + falseCase.accept(this); + } + return this; + } + + /** + * Builds the configured DTO instance. + * + *

      Example:

      + * + *
      {@code
      +   * GenerationTargetClassDto result = builder.build();
      +   * }
      + */ + @Override public GenerationTargetClassDto build() { GenerationTargetClassDto result = new GenerationTargetClassDto(); this.classAccessModifier.ifSet(result::setClassAccessModifier); + this.classAnnotations.ifSet(result::setClassAnnotations); + this.classFields.ifSet(result::setClassFields); this.classJavadoc.ifSet(result::setClassJavadoc); + this.constructors.ifSet(result::setConstructors); this.formattingMode.ifSet(result::setFormattingMode); + this.generics.ifSet(result::setGenerics); + this.imports.ifSet(result::setImports); + this.interfaces.ifSet(result::setInterfaces); + this.methods.ifSet(result::setMethods); + this.nestedTypes.ifSet(result::setNestedTypes); this.superType.ifSet(result::setSuperType); this.typeName.ifSet(result::setTypeName); return result; @@ -475,8 +1704,16 @@ public GenerationTargetClassDto build() { public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) .append("classAccessModifier", this.classAccessModifier) + .append("classAnnotations", this.classAnnotations) + .append("classFields", this.classFields) .append("classJavadoc", this.classJavadoc) + .append("constructors", this.constructors) .append("formattingMode", this.formattingMode) + .append("generics", this.generics) + .append("imports", this.imports) + .append("interfaces", this.interfaces) + .append("methods", this.methods) + .append("nestedTypes", this.nestedTypes) .append("superType", this.superType) .append("typeName", this.typeName) .toString(); diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java index 26df3c15..7a0fc9e3 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java @@ -21,18 +21,29 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.javadoc; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.method.MethodCodePlaceholder; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.builders.HashSetBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -48,16 +59,25 @@ * *
      {@code
        * JavadocCodeBlockDto result = JavadocCodeBlockDtoBuilder.create()
      - *     .codeFormat("example value")
      + *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
      + *     .codeBlockImportsUpdate(TreeSet::new)
      + *     .codeFormat("example codeFormat")
        *     .codeFormat("Hello %s", "World")
      - *     .codeFormat(() -> "example value")
      + *     .codeFormat(() -> "example codeFormat")
        *     .codeFormat(sb -> sb.append("text"))
        *     .codeFormatUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class JavadocCodeBlockDtoBuilder { +@BuilderImplementation(forClass = JavadocCodeBlockDto.class) +public class JavadocCodeBlockDtoBuilder implements IBuilderBase { + + /** Tracked value for codeArguments: the replacement collection (not null). */ + private TrackedValue>> codeArguments = unsetValue(); + + /** Tracked value for codeBlockImports: the replacement collection (not null). */ + private TrackedValue> codeBlockImports = unsetValue(); /** Tracked value for codeFormat: Codeformat. */ private TrackedValue codeFormat = unsetValue(); @@ -75,6 +95,8 @@ public JavadocCodeBlockDtoBuilder() {} * @param instance object instance for initialisiation */ public JavadocCodeBlockDtoBuilder(JavadocCodeBlockDto instance) { + this.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); this.codeFormat = initialValue(instance.getCodeFormat()); } @@ -93,6 +115,238 @@ public static JavadocCodeBlockDtoBuilder create() { return new JavadocCodeBlockDtoBuilder(); } + /** + * Adds a single element to codeArguments. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param element the element to add + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder add2CodeArguments(MethodCodePlaceholder element) { + List> newCollection; + if (this.codeArguments.isSet()) { + newCollection = new ArrayList<>(this.codeArguments.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.codeArguments = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeArguments using a builder consumer that produces the value. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeArguments( + Consumer>> codeArgumentsBuilderConsumer) { + ArrayListBuilder> builder = + this.codeArguments.isSet() + ? new ArrayListBuilder>(this.codeArguments.value()) + : new ArrayListBuilder>(); + codeArgumentsBuilderConsumer.accept(builder); + this.codeArguments = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeArguments by invoking the provided supplier. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeArguments( + Supplier>> codeArgumentsSupplier) { + this.codeArguments = changedValue(codeArgumentsSupplier.get()); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeArguments(MethodCodePlaceholder... codeArguments) { + this.codeArguments = changedValue(List.of(codeArguments)); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeArguments(List> codeArguments) { + this.codeArguments = changedValue(codeArguments); + return this; + } + + /** + * Updates the current value of codeArguments in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeArgumentsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param codeArgumentsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeArguments has not been set yet + */ + public JavadocCodeBlockDtoBuilder codeArgumentsUpdate( + UnaryOperator>> codeArgumentsUpdater) { + if (!this.codeArguments.isSet()) { + throw new IllegalStateException("Cannot update 'codeArguments' before it is set"); + } + this.codeArguments = changedValue(codeArgumentsUpdater.apply(this.codeArguments.value())); + return this; + } + + /** + * Adds a single element to codeBlockImports. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param element the element to add + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder add2CodeBlockImports(ImportStatement element) { + Set newCollection; + if (this.codeBlockImports.isSet()) { + newCollection = new HashSet<>(this.codeBlockImports.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.codeBlockImports = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeBlockImports(ImportStatement... codeBlockImports) { + this.codeBlockImports = changedValue(Set.of(codeBlockImports)); + return this; + } + + /** + * Sets the value for codeBlockImports using a builder consumer that produces the + * value. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeBlockImports( + Consumer> codeBlockImportsBuilderConsumer) { + HashSetBuilder builder = + this.codeBlockImports.isSet() + ? new HashSetBuilder(this.codeBlockImports.value()) + : new HashSetBuilder(); + codeBlockImportsBuilderConsumer.accept(builder); + this.codeBlockImports = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeBlockImports by invoking the provided supplier. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeBlockImports( + Supplier> codeBlockImportsSupplier) { + this.codeBlockImports = changedValue(codeBlockImportsSupplier.get()); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public JavadocCodeBlockDtoBuilder codeBlockImports(Set codeBlockImports) { + this.codeBlockImports = changedValue(codeBlockImports); + return this; + } + + /** + * Updates the current value of codeBlockImports in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link JavadocCodeBlockDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeBlockImportsUpdate(TreeSet::new);
      +   * }
      + * + * @param codeBlockImportsUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if codeBlockImports has not been set yet + */ + public JavadocCodeBlockDtoBuilder codeBlockImportsUpdate( + UnaryOperator> codeBlockImportsUpdater) { + if (!this.codeBlockImports.isSet()) { + throw new IllegalStateException("Cannot update 'codeBlockImports' before it is set"); + } + this.codeBlockImports = + changedValue(codeBlockImportsUpdater.apply(this.codeBlockImports.value())); + return this; + } + /** * Sets the value for codeFormat by executing the provided consumer. * @@ -125,7 +379,7 @@ public JavadocCodeBlockDtoBuilder codeFormat( *

      Example:

      * *
      {@code
      -   * builder.codeFormat(() -> "example value");
      +   * builder.codeFormat(() -> "example codeFormat");
          * }
      * * @param codeFormatSupplier supplier for Codeformat @@ -167,7 +421,7 @@ public JavadocCodeBlockDtoBuilder codeFormat(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value");
      +   * builder.codeFormat("example codeFormat");
          * }
      * * @param codeFormat Codeformat @@ -191,7 +445,7 @@ public JavadocCodeBlockDtoBuilder codeFormat(String codeFormat) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
      +   * builder.codeFormat("example codeFormat").codeFormatUpdate(String::trim);
          * }
      * * @param codeFormatUpdater operator applied to the current value; its result becomes the new @@ -248,8 +502,11 @@ public JavadocCodeBlockDtoBuilder conditional( * JavadocCodeBlockDto result = builder.build(); * } */ + @Override public JavadocCodeBlockDto build() { JavadocCodeBlockDto result = new JavadocCodeBlockDto(); + this.codeArguments.ifSet(result::setCodeArguments); + this.codeBlockImports.ifSet(result::setCodeBlockImports); this.codeFormat.ifSet(result::setCodeFormat); return result; } @@ -262,6 +519,8 @@ public JavadocCodeBlockDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) .append("codeFormat", this.codeFormat) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java index 51cb2224..76aaf6eb 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java @@ -47,6 +47,18 @@ */ public class JavadocDto { + /** + * Replaces tags with a defensive copy; the DTO retains its own mutable collection. + * + * @param tags the replacement collection (not null) + * @throws NullPointerException if tags is null + */ + public void setTags(List tags) { + List copy = new ArrayList<>(tags); + this.tags.clear(); + this.tags.addAll(copy); + } + /** The main description text (everything before the first tag). */ private String description; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java index 7853d6a3..fddd50d0 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java @@ -21,12 +21,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.javadoc; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BooleanSupplier; @@ -35,7 +37,9 @@ import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -51,19 +55,21 @@ * *
      {@code
        * JavadocDto result = JavadocDtoBuilder.create()
      - *     .format("example value")
      + *     .format("example format")
        *     .format("Hello %s", "World")
      - *     .format(() -> "example value")
      + *     .format(() -> "example format")
        *     .format(sb -> sb.append("text"))
        *     .formatUpdate(String::trim)
        *     .exampleUsageCodeBlock(new JavadocCodeBlockDto())
        *     .exampleUsageCodeBlock(JavadocCodeBlockDto::new)
        *     .exampleUsageCodeBlock(javadocCodeBlockDtoBuilder -> javadocCodeBlockDtoBuilder)
      + *     .tagsUpdate(list -> list.stream().sorted().toList())
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class JavadocDtoBuilder { +@BuilderImplementation(forClass = JavadocDto.class) +public class JavadocDtoBuilder implements IBuilderBase { /** Tracked value for format: format. */ private TrackedValue format = unsetValue(); @@ -77,6 +83,9 @@ public class JavadocDtoBuilder { */ private TrackedValue exampleUsageCodeBlock = unsetValue(); + /** Tracked value for tags: the replacement collection (not null). */ + private TrackedValue> tags = unsetValue(); + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.javadoc.JavadocDto}. */ public JavadocDtoBuilder() {} @@ -88,6 +97,7 @@ public JavadocDtoBuilder() {} */ public JavadocDtoBuilder(JavadocDto instance) { this.exampleUsageCodeBlock = initialValue(instance.getExampleUsageCodeBlock()); + this.tags = initialValue(instance.getTags()); } /** @@ -317,7 +327,7 @@ public JavadocDtoBuilder format(Consumer formatStringBuilderConsu *

      Example:

      * *
      {@code
      -   * builder.format(() -> "example value");
      +   * builder.format(() -> "example format");
          * }
      * * @param formatSupplier supplier for format @@ -359,7 +369,7 @@ public JavadocDtoBuilder format(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.format("example value");
      +   * builder.format("example format");
          * }
      * * @param format format @@ -383,7 +393,7 @@ public JavadocDtoBuilder format(String format) { *

      Example:

      * *
      {@code
      -   * builder.format("example value").formatUpdate(String::trim);
      +   * builder.format("example format").formatUpdate(String::trim);
          * }
      * * @param formatUpdater operator applied to the current value; its result becomes the new value @@ -398,6 +408,111 @@ public JavadocDtoBuilder formatUpdate(UnaryOperator formatUpdater) { return this; } + /** + * Adds a single element to tags. + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + * @param element the element to add + * @return current instance of builder + */ + public JavadocDtoBuilder add2Tags(JavadocTagDto element) { + List newCollection; + if (this.tags.isSet()) { + newCollection = new ArrayList<>(this.tags.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.tags = changedValue(newCollection); + return this; + } + + /** + * Sets the value for tags. + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + * @param tags the replacement collection (not null) + * @return current instance of builder + */ + public JavadocDtoBuilder tags(JavadocTagDto... tags) { + this.tags = changedValue(List.of(tags)); + return this; + } + + /** + * Sets the value for tags using a builder consumer that produces the value. + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + * @param tagsBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public JavadocDtoBuilder tags(Consumer> tagsBuilderConsumer) { + ArrayListBuilder builder = + this.tags.isSet() + ? new ArrayListBuilder(this.tags.value()) + : new ArrayListBuilder(); + tagsBuilderConsumer.accept(builder); + this.tags = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for tags by invoking the provided supplier. + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + * @param tagsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public JavadocDtoBuilder tags(Supplier> tagsSupplier) { + this.tags = changedValue(tagsSupplier.get()); + return this; + } + + /** + * Sets the value for tags. + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + * @param tags the replacement collection (not null) + * @return current instance of builder + */ + public JavadocDtoBuilder tags(List tags) { + this.tags = changedValue(tags); + return this; + } + + /** + * Updates the current value of tags in place by applying the given operator, instead + * of reading it out, changing it and setting it again. Useful for adjustments relative to the + * current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination with + * the With copy-and-modify flow. The value must have been set before (directly or + * via an existing instance). + * + *

      Generated from setter {@link JavadocDto#setTags(List) setTags(List tags)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.tagsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param tagsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if tags has not been set yet + */ + public JavadocDtoBuilder tagsUpdate(UnaryOperator> tagsUpdater) { + if (!this.tags.isSet()) { + throw new IllegalStateException("Cannot update 'tags' before it is set"); + } + this.tags = changedValue(tagsUpdater.apply(this.tags.value())); + return this; + } + /** * Conditionally applies builder modifications if the condition is true. * @@ -439,9 +554,11 @@ public JavadocDtoBuilder conditional( * JavadocDto result = builder.build(); * } */ + @Override public JavadocDto build() { JavadocDto result = new JavadocDto(this.format.value(), this.args.value()); this.exampleUsageCodeBlock.ifSet(result::setExampleUsageCodeBlock); + this.tags.ifSet(result::setTags); return result; } @@ -456,6 +573,7 @@ public String toString() { .append("format", this.format) .append("args", this.args) .append("exampleUsageCodeBlock", this.exampleUsageCodeBlock) + .append("tags", this.tags) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java index 2b45684b..5fc506b5 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java @@ -46,6 +46,31 @@ * code generation. */ public class CodeTemplateDto { + + /** + * Replaces codeArguments with a defensive copy; the DTO retains its own mutable collection. + * + * @param codeArguments the replacement collection (not null) + * @throws NullPointerException if codeArguments is null + */ + public void setCodeArguments(List> codeArguments) { + List> copy = new ArrayList<>(codeArguments); + this.codeArguments.clear(); + this.codeArguments.addAll(copy); + } + + /** + * Replaces codeBlockImports with a defensive copy; the DTO retains its own mutable collection. + * + * @param codeBlockImports the replacement collection (not null) + * @throws NullPointerException if codeBlockImports is null + */ + public void setCodeBlockImports(Set codeBlockImports) { + Set copy = new LinkedHashSet<>(codeBlockImports); + this.codeBlockImports.clear(); + this.codeBlockImports.addAll(copy); + } + /** Format of code. Holding placeholder for dynamic values. */ private String codeFormat; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java index 28b17ee8..246be1f6 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java @@ -21,18 +21,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.method; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.builders.HashSetBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -48,16 +58,25 @@ * *
      {@code
        * CodeTemplateDto result = CodeTemplateDtoBuilder.create()
      - *     .codeFormat("example value")
      + *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
      + *     .codeBlockImportsUpdate(TreeSet::new)
      + *     .codeFormat("example codeFormat")
        *     .codeFormat("Hello %s", "World")
      - *     .codeFormat(() -> "example value")
      + *     .codeFormat(() -> "example codeFormat")
        *     .codeFormat(sb -> sb.append("text"))
        *     .codeFormatUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class CodeTemplateDtoBuilder { +@BuilderImplementation(forClass = CodeTemplateDto.class) +public class CodeTemplateDtoBuilder implements IBuilderBase { + + /** Tracked value for codeArguments: the replacement collection (not null). */ + private TrackedValue>> codeArguments = unsetValue(); + + /** Tracked value for codeBlockImports: the replacement collection (not null). */ + private TrackedValue> codeBlockImports = unsetValue(); /** Tracked value for codeFormat: Codeformat. */ private TrackedValue codeFormat = unsetValue(); @@ -74,6 +93,8 @@ public CodeTemplateDtoBuilder() {} * @param instance object instance for initialisiation */ public CodeTemplateDtoBuilder(CodeTemplateDto instance) { + this.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); this.codeFormat = initialValue(instance.getCodeFormat()); } @@ -92,6 +113,238 @@ public static CodeTemplateDtoBuilder create() { return new CodeTemplateDtoBuilder(); } + /** + * Adds a single element to codeArguments. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param element the element to add + * @return current instance of builder + */ + public CodeTemplateDtoBuilder add2CodeArguments(MethodCodePlaceholder element) { + List> newCollection; + if (this.codeArguments.isSet()) { + newCollection = new ArrayList<>(this.codeArguments.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.codeArguments = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeArguments using a builder consumer that produces the value. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeArguments( + Consumer>> codeArgumentsBuilderConsumer) { + ArrayListBuilder> builder = + this.codeArguments.isSet() + ? new ArrayListBuilder>(this.codeArguments.value()) + : new ArrayListBuilder>(); + codeArgumentsBuilderConsumer.accept(builder); + this.codeArguments = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeArguments by invoking the provided supplier. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeArguments( + Supplier>> codeArgumentsSupplier) { + this.codeArguments = changedValue(codeArgumentsSupplier.get()); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeArguments(MethodCodePlaceholder... codeArguments) { + this.codeArguments = changedValue(List.of(codeArguments)); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeArguments(List> codeArguments) { + this.codeArguments = changedValue(codeArguments); + return this; + } + + /** + * Updates the current value of codeArguments in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link CodeTemplateDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeArgumentsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param codeArgumentsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeArguments has not been set yet + */ + public CodeTemplateDtoBuilder codeArgumentsUpdate( + UnaryOperator>> codeArgumentsUpdater) { + if (!this.codeArguments.isSet()) { + throw new IllegalStateException("Cannot update 'codeArguments' before it is set"); + } + this.codeArguments = changedValue(codeArgumentsUpdater.apply(this.codeArguments.value())); + return this; + } + + /** + * Adds a single element to codeBlockImports. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param element the element to add + * @return current instance of builder + */ + public CodeTemplateDtoBuilder add2CodeBlockImports(ImportStatement element) { + Set newCollection; + if (this.codeBlockImports.isSet()) { + newCollection = new HashSet<>(this.codeBlockImports.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.codeBlockImports = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeBlockImports(ImportStatement... codeBlockImports) { + this.codeBlockImports = changedValue(Set.of(codeBlockImports)); + return this; + } + + /** + * Sets the value for codeBlockImports using a builder consumer that produces the + * value. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeBlockImports( + Consumer> codeBlockImportsBuilderConsumer) { + HashSetBuilder builder = + this.codeBlockImports.isSet() + ? new HashSetBuilder(this.codeBlockImports.value()) + : new HashSetBuilder(); + codeBlockImportsBuilderConsumer.accept(builder); + this.codeBlockImports = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeBlockImports by invoking the provided supplier. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeBlockImports( + Supplier> codeBlockImportsSupplier) { + this.codeBlockImports = changedValue(codeBlockImportsSupplier.get()); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public CodeTemplateDtoBuilder codeBlockImports(Set codeBlockImports) { + this.codeBlockImports = changedValue(codeBlockImports); + return this; + } + + /** + * Updates the current value of codeBlockImports in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link CodeTemplateDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeBlockImportsUpdate(TreeSet::new);
      +   * }
      + * + * @param codeBlockImportsUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if codeBlockImports has not been set yet + */ + public CodeTemplateDtoBuilder codeBlockImportsUpdate( + UnaryOperator> codeBlockImportsUpdater) { + if (!this.codeBlockImports.isSet()) { + throw new IllegalStateException("Cannot update 'codeBlockImports' before it is set"); + } + this.codeBlockImports = + changedValue(codeBlockImportsUpdater.apply(this.codeBlockImports.value())); + return this; + } + /** * Sets the value for codeFormat by executing the provided consumer. * @@ -124,7 +377,7 @@ public CodeTemplateDtoBuilder codeFormat( *

      Example:

      * *
      {@code
      -   * builder.codeFormat(() -> "example value");
      +   * builder.codeFormat(() -> "example codeFormat");
          * }
      * * @param codeFormatSupplier supplier for Codeformat @@ -166,7 +419,7 @@ public CodeTemplateDtoBuilder codeFormat(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value");
      +   * builder.codeFormat("example codeFormat");
          * }
      * * @param codeFormat Codeformat @@ -190,7 +443,7 @@ public CodeTemplateDtoBuilder codeFormat(String codeFormat) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
      +   * builder.codeFormat("example codeFormat").codeFormatUpdate(String::trim);
          * }
      * * @param codeFormatUpdater operator applied to the current value; its result becomes the new @@ -247,8 +500,11 @@ public CodeTemplateDtoBuilder conditional( * CodeTemplateDto result = builder.build(); * } */ + @Override public CodeTemplateDto build() { CodeTemplateDto result = new CodeTemplateDto(); + this.codeArguments.ifSet(result::setCodeArguments); + this.codeBlockImports.ifSet(result::setCodeBlockImports); this.codeFormat.ifSet(result::setCodeFormat); return result; } @@ -261,6 +517,8 @@ public CodeTemplateDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) .append("codeFormat", this.codeFormat) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDto.java index 936d453f..0aad92c8 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDto.java @@ -39,6 +39,31 @@ *

      This DTO contains all information needed to render a constructor in the generated class. */ public class ConstructorDto { + + /** + * Replaces parameters with a defensive copy; the DTO retains its own mutable collection. + * + * @param parameters the replacement collection (not null) + * @throws NullPointerException if parameters is null + */ + public void setParameters(List parameters) { + List copy = new ArrayList<>(parameters); + this.parameters.clear(); + this.parameters.addAll(copy); + } + + /** + * Replaces annotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param annotations the replacement collection (not null) + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + List copy = new ArrayList<>(annotations); + this.annotations.clear(); + this.annotations.addAll(copy); + } + /** Constructor parameters. */ private final LinkedList parameters = new LinkedList<>(); diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java index fbb34a67..19a97b90 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java @@ -21,12 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.method; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -34,8 +37,13 @@ import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -51,17 +59,33 @@ * *

      {@code
        * ConstructorDto result = ConstructorDtoBuilder.create()
      + *     .annotations(List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(() -> List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder))
      + *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
      + *     .annotationsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Annotations(AnnotationDtoBuilder.create().build())
        *     .javadoc(new JavadocDto())
        *     .javadoc(JavadocDto::new)
        *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
        *     .methodCodeDto(new MethodCodeDto())
        *     .methodCodeDto(MethodCodeDto::new)
        *     .methodCodeDto(methodCodeDtoBuilder -> methodCodeDtoBuilder)
      + *     .parameters(List.of(MethodParameterDtoBuilder.create().build()))
      + *     .parameters(() -> List.of(MethodParameterDtoBuilder.create().build()))
      + *     .parameters(t -> t.add(methodParameterDtoBuilder -> methodParameterDtoBuilder))
      + *     .parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build())
      + *     .parametersUpdate(list -> list.stream().sorted().toList())
      + *     .add2Parameters(MethodParameterDtoBuilder.create().build())
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class ConstructorDtoBuilder { +@BuilderImplementation(forClass = ConstructorDto.class) +public class ConstructorDtoBuilder implements IBuilderBase { + + /** Tracked value for annotations: the replacement collection (not null). */ + private TrackedValue> annotations = unsetValue(); /** Tracked value for javadoc: javadoc. */ private TrackedValue javadoc = unsetValue(); @@ -69,6 +93,9 @@ public class ConstructorDtoBuilder { /** Tracked value for methodCodeDto: the method code DTO. */ private TrackedValue methodCodeDto = unsetValue(); + /** Tracked value for parameters: the replacement collection (not null). */ + private TrackedValue> parameters = unsetValue(); + /** Tracked value for visibility: visibility. */ private TrackedValue visibility = unsetValue(); @@ -84,8 +111,10 @@ public ConstructorDtoBuilder() {} * @param instance object instance for initialisiation */ public ConstructorDtoBuilder(ConstructorDto instance) { + this.annotations = initialValue(instance.getAnnotations()); this.javadoc = initialValue(instance.getJavadoc()); this.methodCodeDto = initialValue(instance.getMethodCodeDto()); + this.parameters = initialValue(instance.getParameters()); this.visibility = initialValue(instance.getVisibility()); } @@ -104,6 +133,155 @@ public static ConstructorDtoBuilder create() { return new ConstructorDtoBuilder(); } + /** + * Adds a single element to annotations. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public ConstructorDtoBuilder add2Annotations(AnnotationDto element) { + List newCollection; + if (this.annotations.isSet()) { + newCollection = new ArrayList<>(this.annotations.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.annotations = changedValue(newCollection); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder annotations(AnnotationDto... annotations) { + this.annotations = changedValue(List.of(annotations)); + return this; + } + + /** + * Sets the value for annotations using a builder consumer that produces the value. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
      +   * }
      + * + * @param annotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder annotations( + Consumer> + annotationsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.annotations.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.annotations.value(), AnnotationDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + AnnotationDtoBuilder::create); + annotationsBuilderConsumer.accept(builder); + this.annotations = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(() -> List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotationsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder annotations(Supplier> annotationsSupplier) { + this.annotations = changedValue(annotationsSupplier.get()); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Updates the current value of annotations in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #annotations(Consumer)}. + * + *

      Generated from setter {@link ConstructorDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()))
      +   *     .annotationsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param annotationsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if annotations has not been set yet + */ + public ConstructorDtoBuilder annotationsUpdate( + UnaryOperator> annotationsUpdater) { + if (!this.annotations.isSet()) { + throw new IllegalStateException("Cannot update 'annotations' before it is set"); + } + this.annotations = changedValue(annotationsUpdater.apply(this.annotations.value())); + return this; + } + /** * Sets the value for javadoc using a builder consumer that produces the value. * @@ -284,6 +462,156 @@ public ConstructorDtoBuilder methodCodeDtoUpdate( return this; } + /** + * Adds a single element to parameters. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Parameters(MethodParameterDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public ConstructorDtoBuilder add2Parameters(MethodParameterDto element) { + List newCollection; + if (this.parameters.isSet()) { + newCollection = new ArrayList<>(this.parameters.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.parameters = changedValue(newCollection); + return this; + } + + /** + * Sets the value for parameters. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build());
      +   * }
      + * + * @param parameters the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder parameters(MethodParameterDto... parameters) { + this.parameters = changedValue(List.of(parameters)); + return this; + } + + /** + * Sets the value for parameters using a builder consumer that produces the value. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(t -> t.add(methodParameterDtoBuilder -> methodParameterDtoBuilder));
      +   * }
      + * + * @param parametersBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder parameters( + Consumer> + parametersBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.parameters.isSet() + ? new ArrayListBuilderWithElementBuilders< + MethodParameterDto, MethodParameterDtoBuilder>( + this.parameters.value(), MethodParameterDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders< + MethodParameterDto, MethodParameterDtoBuilder>(MethodParameterDtoBuilder::create); + parametersBuilderConsumer.accept(builder); + this.parameters = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for parameters by invoking the provided supplier. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(() -> List.of(MethodParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param parametersSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder parameters(Supplier> parametersSupplier) { + this.parameters = changedValue(parametersSupplier.get()); + return this; + } + + /** + * Sets the value for parameters. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(List.of(MethodParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param parameters the replacement collection (not null) + * @return current instance of builder + */ + public ConstructorDtoBuilder parameters(List parameters) { + this.parameters = changedValue(parameters); + return this; + } + + /** + * Updates the current value of parameters in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #parameters(Consumer)}. + * + *

      Generated from setter {@link ConstructorDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(List.of(MethodParameterDtoBuilder.create().build()))
      +   *     .parametersUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param parametersUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if parameters has not been set yet + */ + public ConstructorDtoBuilder parametersUpdate( + UnaryOperator> parametersUpdater) { + if (!this.parameters.isSet()) { + throw new IllegalStateException("Cannot update 'parameters' before it is set"); + } + this.parameters = changedValue(parametersUpdater.apply(this.parameters.value())); + return this; + } + /** * Sets the value for visibility by invoking the provided supplier. * @@ -376,10 +704,13 @@ public ConstructorDtoBuilder conditional( * ConstructorDto result = builder.build(); * } */ + @Override public ConstructorDto build() { ConstructorDto result = new ConstructorDto(); + this.annotations.ifSet(result::setAnnotations); this.javadoc.ifSet(result::setJavadoc); this.methodCodeDto.ifSet(result::setMethodCodeDto); + this.parameters.ifSet(result::setParameters); this.visibility.ifSet(result::setVisibility); return result; } @@ -392,8 +723,10 @@ public ConstructorDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("annotations", this.annotations) .append("javadoc", this.javadoc) .append("methodCodeDto", this.methodCodeDto) + .append("parameters", this.parameters) .append("visibility", this.visibility) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java index d1e08613..4363c1d5 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java @@ -21,18 +21,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.method; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.builders.HashSetBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -48,16 +58,25 @@ * *
      {@code
        * MethodCodeDto result = MethodCodeDtoBuilder.create()
      - *     .codeFormat("example value")
      + *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
      + *     .codeBlockImportsUpdate(TreeSet::new)
      + *     .codeFormat("example codeFormat")
        *     .codeFormat("Hello %s", "World")
      - *     .codeFormat(() -> "example value")
      + *     .codeFormat(() -> "example codeFormat")
        *     .codeFormat(sb -> sb.append("text"))
        *     .codeFormatUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class MethodCodeDtoBuilder { +@BuilderImplementation(forClass = MethodCodeDto.class) +public class MethodCodeDtoBuilder implements IBuilderBase { + + /** Tracked value for codeArguments: the replacement collection (not null). */ + private TrackedValue>> codeArguments = unsetValue(); + + /** Tracked value for codeBlockImports: the replacement collection (not null). */ + private TrackedValue> codeBlockImports = unsetValue(); /** Tracked value for codeFormat: Codeformat. */ private TrackedValue codeFormat = unsetValue(); @@ -74,6 +93,8 @@ public MethodCodeDtoBuilder() {} * @param instance object instance for initialisiation */ public MethodCodeDtoBuilder(MethodCodeDto instance) { + this.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); this.codeFormat = initialValue(instance.getCodeFormat()); } @@ -92,6 +113,238 @@ public static MethodCodeDtoBuilder create() { return new MethodCodeDtoBuilder(); } + /** + * Adds a single element to codeArguments. + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param element the element to add + * @return current instance of builder + */ + public MethodCodeDtoBuilder add2CodeArguments(MethodCodePlaceholder element) { + List> newCollection; + if (this.codeArguments.isSet()) { + newCollection = new ArrayList<>(this.codeArguments.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.codeArguments = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeArguments using a builder consumer that produces the value. + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeArguments( + Consumer>> codeArgumentsBuilderConsumer) { + ArrayListBuilder> builder = + this.codeArguments.isSet() + ? new ArrayListBuilder>(this.codeArguments.value()) + : new ArrayListBuilder>(); + codeArgumentsBuilderConsumer.accept(builder); + this.codeArguments = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeArguments by invoking the provided supplier. + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArgumentsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeArguments( + Supplier>> codeArgumentsSupplier) { + this.codeArguments = changedValue(codeArgumentsSupplier.get()); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeArguments(MethodCodePlaceholder... codeArguments) { + this.codeArguments = changedValue(List.of(codeArguments)); + return this; + } + + /** + * Sets the value for codeArguments. + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + * @param codeArguments the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeArguments(List> codeArguments) { + this.codeArguments = changedValue(codeArguments); + return this; + } + + /** + * Updates the current value of codeArguments in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link MethodCodeDto#setCodeArguments(List) + * setCodeArguments(List> codeArguments)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeArgumentsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param codeArgumentsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if codeArguments has not been set yet + */ + public MethodCodeDtoBuilder codeArgumentsUpdate( + UnaryOperator>> codeArgumentsUpdater) { + if (!this.codeArguments.isSet()) { + throw new IllegalStateException("Cannot update 'codeArguments' before it is set"); + } + this.codeArguments = changedValue(codeArgumentsUpdater.apply(this.codeArguments.value())); + return this; + } + + /** + * Adds a single element to codeBlockImports. + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param element the element to add + * @return current instance of builder + */ + public MethodCodeDtoBuilder add2CodeBlockImports(ImportStatement element) { + Set newCollection; + if (this.codeBlockImports.isSet()) { + newCollection = new HashSet<>(this.codeBlockImports.value()); + } else { + newCollection = new HashSet<>(); + } + newCollection.add(element); + this.codeBlockImports = changedValue(newCollection); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeBlockImports(ImportStatement... codeBlockImports) { + this.codeBlockImports = changedValue(Set.of(codeBlockImports)); + return this; + } + + /** + * Sets the value for codeBlockImports using a builder consumer that produces the + * value. + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeBlockImports( + Consumer> codeBlockImportsBuilderConsumer) { + HashSetBuilder builder = + this.codeBlockImports.isSet() + ? new HashSetBuilder(this.codeBlockImports.value()) + : new HashSetBuilder(); + codeBlockImportsBuilderConsumer.accept(builder); + this.codeBlockImports = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for codeBlockImports by invoking the provided supplier. + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImportsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeBlockImports( + Supplier> codeBlockImportsSupplier) { + this.codeBlockImports = changedValue(codeBlockImportsSupplier.get()); + return this; + } + + /** + * Sets the value for codeBlockImports. + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + * @param codeBlockImports the replacement collection (not null) + * @return current instance of builder + */ + public MethodCodeDtoBuilder codeBlockImports(Set codeBlockImports) { + this.codeBlockImports = changedValue(codeBlockImports); + return this; + } + + /** + * Updates the current value of codeBlockImports in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). + * + *

      Generated from setter {@link MethodCodeDto#setCodeBlockImports(Set) + * setCodeBlockImports(Set codeBlockImports)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.codeBlockImportsUpdate(TreeSet::new);
      +   * }
      + * + * @param codeBlockImportsUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if codeBlockImports has not been set yet + */ + public MethodCodeDtoBuilder codeBlockImportsUpdate( + UnaryOperator> codeBlockImportsUpdater) { + if (!this.codeBlockImports.isSet()) { + throw new IllegalStateException("Cannot update 'codeBlockImports' before it is set"); + } + this.codeBlockImports = + changedValue(codeBlockImportsUpdater.apply(this.codeBlockImports.value())); + return this; + } + /** * Sets the value for codeFormat by executing the provided consumer. * @@ -123,7 +376,7 @@ public MethodCodeDtoBuilder codeFormat(Consumer codeFormatStringB *

      Example:

      * *
      {@code
      -   * builder.codeFormat(() -> "example value");
      +   * builder.codeFormat(() -> "example codeFormat");
          * }
      * * @param codeFormatSupplier supplier for Codeformat @@ -165,7 +418,7 @@ public MethodCodeDtoBuilder codeFormat(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value");
      +   * builder.codeFormat("example codeFormat");
          * }
      * * @param codeFormat Codeformat @@ -189,7 +442,7 @@ public MethodCodeDtoBuilder codeFormat(String codeFormat) { *

      Example:

      * *
      {@code
      -   * builder.codeFormat("example value").codeFormatUpdate(String::trim);
      +   * builder.codeFormat("example codeFormat").codeFormatUpdate(String::trim);
          * }
      * * @param codeFormatUpdater operator applied to the current value; its result becomes the new @@ -246,8 +499,11 @@ public MethodCodeDtoBuilder conditional( * MethodCodeDto result = builder.build(); * } */ + @Override public MethodCodeDto build() { MethodCodeDto result = new MethodCodeDto(); + this.codeArguments.ifSet(result::setCodeArguments); + this.codeBlockImports.ifSet(result::setCodeBlockImports); this.codeFormat.ifSet(result::setCodeFormat); return result; } @@ -260,6 +516,8 @@ public MethodCodeDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) .append("codeFormat", this.codeFormat) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDto.java index cb6c456a..545875f9 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDto.java @@ -28,6 +28,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.javahelpers.codegen.enums.AccessModifier; @@ -44,6 +45,43 @@ * information. */ public class MethodDto { + + /** + * Replaces parameters with a defensive copy; the DTO retains its own mutable collection. + * + * @param parameters the replacement collection (not null) + * @throws NullPointerException if parameters is null + */ + public void setParameters(List parameters) { + List copy = new ArrayList<>(parameters); + this.parameters.clear(); + this.parameters.addAll(copy); + } + + /** + * Replaces genericParameters with a defensive copy; the DTO retains its own mutable collection. + * + * @param genericParameters the replacement collection (not null) + * @throws NullPointerException if genericParameters is null + */ + public void setGenericParameters(List genericParameters) { + List copy = new ArrayList<>(genericParameters); + this.genericParameters.clear(); + this.genericParameters.addAll(copy); + } + + /** + * Replaces annotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param annotations the replacement collection (not null) + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + List copy = new ArrayList<>(annotations); + this.annotations.clear(); + this.annotations.addAll(copy); + } + /** Access modifier for method. */ private Optional modifier = Optional.empty(); @@ -126,6 +164,19 @@ public MethodCodeDto getMethodCodeDto() { return methodCodeDto; } + /** + * Copies the structured method body into this DTO's own code template. + * + * @param code the structured method body (not null) + * @throws NullPointerException if code is null + */ + public void setMethodCodeDto(MethodCodeDto code) { + Objects.requireNonNull(code, "code"); + methodCodeDto.setCodeFormat(code.getCodeFormat()); + methodCodeDto.setCodeArguments(code.getCodeArguments()); + methodCodeDto.setCodeBlockImports(code.getCodeBlockImports()); + } + /** * Checks if the method has a code block. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java index 73833953..c61ad011 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java @@ -21,12 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.method; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -34,9 +37,16 @@ import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -52,27 +62,49 @@ * *
      {@code
        * MethodDto result = MethodDtoBuilder.create()
      - *     .methodName("example value")
      + *     .methodName("example methodName")
        *     .methodName("Hello %s", "World")
      - *     .methodName(() -> "example value")
      + *     .methodName(() -> "example methodName")
        *     .methodName(sb -> sb.append("text"))
        *     .methodNameUpdate(String::trim)
      - *     .code("example value")
      + *     .annotations(List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(() -> List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder))
      + *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
      + *     .annotationsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Annotations(AnnotationDtoBuilder.create().build())
      + *     .code("example code")
        *     .code("Hello %s", "World")
      - *     .code(() -> "example value")
      + *     .code(() -> "example code")
        *     .code(sb -> sb.append("text"))
        *     .codeUpdate(String::trim)
      - *     .isStatic(true)
      - *     .isStatic(() -> true)
      - *     .isStaticUpdate(value -> !value)
      + *     .genericParameters(List.of(GenericParameterDtoBuilder.create().build()))
      + *     .genericParameters(() -> List.of(GenericParameterDtoBuilder.create().build()))
      + *     .genericParameters(t -> t.add(genericParameterDtoBuilder -> genericParameterDtoBuilder))
      + *     .genericParameters(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build())
      + *     .genericParametersUpdate(list -> list.stream().sorted().toList())
      + *     .add2GenericParameters(GenericParameterDtoBuilder.create().build())
        *     .javadoc(new JavadocDto())
        *     .javadoc(JavadocDto::new)
        *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
      + *     .methodCodeDto(new MethodCodeDto())
      + *     .methodCodeDto(MethodCodeDto::new)
      + *     .methodCodeDto(methodCodeDtoBuilder -> methodCodeDtoBuilder)
      + *     .parameters(List.of(MethodParameterDtoBuilder.create().build()))
      + *     .parameters(() -> List.of(MethodParameterDtoBuilder.create().build()))
      + *     .parameters(t -> t.add(methodParameterDtoBuilder -> methodParameterDtoBuilder))
      + *     .parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build())
      + *     .parametersUpdate(list -> list.stream().sorted().toList())
      + *     .add2Parameters(MethodParameterDtoBuilder.create().build())
      + *     .isStatic(true)
      + *     .isStatic(() -> true)
      + *     .isStaticUpdate(value -> !value)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class MethodDtoBuilder { +@BuilderImplementation(forClass = MethodDto.class) +public class MethodDtoBuilder implements IBuilderBase { /** Tracked value for methodName: methodName. */ private TrackedValue methodName = unsetValue(); @@ -80,20 +112,32 @@ public class MethodDtoBuilder { /** Tracked value for returnType: returnType. */ private TrackedValue returnType = unsetValue(); + /** Tracked value for annotations: the replacement collection (not null). */ + private TrackedValue> annotations = unsetValue(); + /** Tracked value for code: Codeformat with placeholders. */ private TrackedValue code = unsetValue(); - /** - * Tracked value for isStatic: true if the method should be static, false otherwise. - */ - private TrackedValue isStatic = unsetValue(); + /** Tracked value for genericParameters: the replacement collection (not null). */ + private TrackedValue> genericParameters = unsetValue(); /** Tracked value for javadoc: the Javadoc comment. */ private TrackedValue javadoc = unsetValue(); + /** Tracked value for methodCodeDto: the structured method body (not null). */ + private TrackedValue methodCodeDto = unsetValue(); + /** Tracked value for modifier: access modifier of type {@code AccessModifier}. */ private TrackedValue modifier = unsetValue(); + /** Tracked value for parameters: the replacement collection (not null). */ + private TrackedValue> parameters = unsetValue(); + + /** + * Tracked value for isStatic: true if the method should be static, false otherwise. + */ + private TrackedValue isStatic = unsetValue(); + /** Empty constructor of builder for {@code org.javahelpers.codegen.model.method.MethodDto}. */ public MethodDtoBuilder() {} @@ -106,8 +150,12 @@ public MethodDtoBuilder() {} public MethodDtoBuilder(MethodDto instance) { this.methodName = initialValue(instance.getMethodName()); this.returnType = initialValue(instance.getReturnType()); - this.isStatic = initialValue(instance.isStatic()); + this.annotations = initialValue(instance.getAnnotations()); + this.genericParameters = initialValue(instance.getGenericParameters()); this.javadoc = initialValue(instance.getJavadoc()); + this.methodCodeDto = initialValue(instance.getMethodCodeDto()); + this.parameters = initialValue(instance.getParameters()); + this.isStatic = initialValue(instance.isStatic()); } /** @@ -125,6 +173,154 @@ public static MethodDtoBuilder create() { return new MethodDtoBuilder(); } + /** + * Adds a single element to annotations. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public MethodDtoBuilder add2Annotations(AnnotationDto element) { + List newCollection; + if (this.annotations.isSet()) { + newCollection = new ArrayList<>(this.annotations.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.annotations = changedValue(newCollection); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder annotations(AnnotationDto... annotations) { + this.annotations = changedValue(List.of(annotations)); + return this; + } + + /** + * Sets the value for annotations using a builder consumer that produces the value. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
      +   * }
      + * + * @param annotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder annotations( + Consumer> + annotationsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.annotations.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.annotations.value(), AnnotationDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + AnnotationDtoBuilder::create); + annotationsBuilderConsumer.accept(builder); + this.annotations = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(() -> List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotationsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder annotations(Supplier> annotationsSupplier) { + this.annotations = changedValue(annotationsSupplier.get()); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Updates the current value of annotations in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #annotations(Consumer)}. + * + *

      Generated from setter {@link MethodDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()))
      +   *     .annotationsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param annotationsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if annotations has not been set yet + */ + public MethodDtoBuilder annotationsUpdate(UnaryOperator> annotationsUpdater) { + if (!this.annotations.isSet()) { + throw new IllegalStateException("Cannot update 'annotations' before it is set"); + } + this.annotations = changedValue(annotationsUpdater.apply(this.annotations.value())); + return this; + } + /** * Sets the value for code by executing the provided consumer. * @@ -154,7 +350,7 @@ public MethodDtoBuilder code(Consumer codeStringBuilderConsumer) *

      Example:

      * *
      {@code
      -   * builder.code(() -> "example value");
      +   * builder.code(() -> "example code");
          * }
      * * @param codeSupplier supplier for Codeformat with placeholders @@ -194,7 +390,7 @@ public MethodDtoBuilder code(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.code("example value");
      +   * builder.code("example code");
          * }
      * * @param code Codeformat with placeholders @@ -217,7 +413,7 @@ public MethodDtoBuilder code(String code) { *

      Example:

      * *
      {@code
      -   * builder.code("example value").codeUpdate(String::trim);
      +   * builder.code("example code").codeUpdate(String::trim);
          * }
      * * @param codeUpdater operator applied to the current value; its result becomes the new value @@ -232,6 +428,160 @@ public MethodDtoBuilder codeUpdate(UnaryOperator codeUpdater) { return this; } + /** + * Adds a single element to genericParameters. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2GenericParameters(GenericParameterDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public MethodDtoBuilder add2GenericParameters(GenericParameterDto element) { + List newCollection; + if (this.genericParameters.isSet()) { + newCollection = new ArrayList<>(this.genericParameters.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.genericParameters = changedValue(newCollection); + return this; + } + + /** + * Sets the value for genericParameters. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.genericParameters(GenericParameterDtoBuilder.create().build(), GenericParameterDtoBuilder.create().build());
      +   * }
      + * + * @param genericParameters the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder genericParameters(GenericParameterDto... genericParameters) { + this.genericParameters = changedValue(List.of(genericParameters)); + return this; + } + + /** + * Sets the value for genericParameters using a builder consumer that produces the + * value. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.genericParameters(t -> t.add(genericParameterDtoBuilder -> genericParameterDtoBuilder));
      +   * }
      + * + * @param genericParametersBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder genericParameters( + Consumer> + genericParametersBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.genericParameters.isSet() + ? new ArrayListBuilderWithElementBuilders< + GenericParameterDto, GenericParameterDtoBuilder>( + this.genericParameters.value(), GenericParameterDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders< + GenericParameterDto, GenericParameterDtoBuilder>( + GenericParameterDtoBuilder::create); + genericParametersBuilderConsumer.accept(builder); + this.genericParameters = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for genericParameters by invoking the provided supplier. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.genericParameters(() -> List.of(GenericParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param genericParametersSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder genericParameters( + Supplier> genericParametersSupplier) { + this.genericParameters = changedValue(genericParametersSupplier.get()); + return this; + } + + /** + * Sets the value for genericParameters. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.genericParameters(List.of(GenericParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param genericParameters the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder genericParameters(List genericParameters) { + this.genericParameters = changedValue(genericParameters); + return this; + } + + /** + * Updates the current value of genericParameters in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). For changing multiple elements of a nested DTO, + * prefer the builder-consumer helper {@link #genericParameters(Consumer)}. + * + *

      Generated from setter {@link MethodDto#setGenericParameters(List) + * setGenericParameters(List genericParameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.genericParameters(List.of(GenericParameterDtoBuilder.create().build()))
      +   *     .genericParametersUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param genericParametersUpdater operator applied to the current value; its result becomes the + * new value + * @return current instance of builder + * @throws IllegalStateException if genericParameters has not been set yet + */ + public MethodDtoBuilder genericParametersUpdate( + UnaryOperator> genericParametersUpdater) { + if (!this.genericParameters.isSet()) { + throw new IllegalStateException("Cannot update 'genericParameters' before it is set"); + } + this.genericParameters = + changedValue(genericParametersUpdater.apply(this.genericParameters.value())); + return this; + } + /** * Sets the value for isStatic by invoking the provided supplier. * @@ -386,6 +736,97 @@ public MethodDtoBuilder javadocUpdate(UnaryOperator javadocUpdater) return this; } + /** + * Sets the value for methodCodeDto using a builder consumer that produces the value. + * + *

      Generated from setter {@link MethodDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methodCodeDto(methodCodeDtoBuilder -> methodCodeDtoBuilder);
      +   * }
      + * + * @param methodCodeDtoBuilderConsumer consumer providing an instance of a builder for the + * structured method body (not null) + * @return current instance of builder + */ + public MethodDtoBuilder methodCodeDto( + Consumer methodCodeDtoBuilderConsumer) { + MethodCodeDtoBuilder builder = + this.methodCodeDto.isSet() + ? new MethodCodeDtoBuilder(this.methodCodeDto.value()) + : MethodCodeDtoBuilder.create(); + methodCodeDtoBuilderConsumer.accept(builder); + this.methodCodeDto = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for methodCodeDto by invoking the provided supplier. + * + *

      Generated from setter {@link MethodDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methodCodeDto(MethodCodeDto::new);
      +   * }
      + * + * @param methodCodeDtoSupplier supplier for the structured method body (not null) + * @return current instance of builder + */ + public MethodDtoBuilder methodCodeDto(Supplier methodCodeDtoSupplier) { + this.methodCodeDto = changedValue(methodCodeDtoSupplier.get()); + return this; + } + + /** + * Sets the value for methodCodeDto. + * + *

      Generated from setter {@link MethodDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methodCodeDto(new MethodCodeDto());
      +   * }
      + * + * @param methodCodeDto the structured method body (not null) + * @return current instance of builder + */ + public MethodDtoBuilder methodCodeDto(MethodCodeDto methodCodeDto) { + this.methodCodeDto = changedValue(methodCodeDto); + return this; + } + + /** + * Updates the current value of methodCodeDto in place by applying the given + * operator, instead of reading it out, changing it and setting it again. Useful for adjustments + * relative to the current value, e.g. trimming, upper-casing, clamping or incrementing, and in + * combination with the With copy-and-modify flow. The value must have been set + * before (directly or via an existing instance). For changing multiple values of a nested DTO, + * prefer the builder-consumer helper {@link #methodCodeDto(Consumer)}. + * + *

      Generated from setter {@link MethodDto#setMethodCodeDto(MethodCodeDto) + * setMethodCodeDto(MethodCodeDto methodCodeDto)} + * + * @param methodCodeDtoUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if methodCodeDto has not been set yet + */ + public MethodDtoBuilder methodCodeDtoUpdate(UnaryOperator methodCodeDtoUpdater) { + if (!this.methodCodeDto.isSet()) { + throw new IllegalStateException("Cannot update 'methodCodeDto' before it is set"); + } + this.methodCodeDto = changedValue(methodCodeDtoUpdater.apply(this.methodCodeDto.value())); + return this; + } + /** * Sets the value for methodName by executing the provided consumer. * @@ -417,7 +858,7 @@ public MethodDtoBuilder methodName(Consumer methodNameStringBuild *

      Example:

      * *
      {@code
      -   * builder.methodName(() -> "example value");
      +   * builder.methodName(() -> "example methodName");
          * }
      * * @param methodNameSupplier supplier for methodName @@ -459,7 +900,7 @@ public MethodDtoBuilder methodName(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.methodName("example value");
      +   * builder.methodName("example methodName");
          * }
      * * @param methodName methodName @@ -483,7 +924,7 @@ public MethodDtoBuilder methodName(String methodName) { *

      Example:

      * *
      {@code
      -   * builder.methodName("example value").methodNameUpdate(String::trim);
      +   * builder.methodName("example methodName").methodNameUpdate(String::trim);
          * }
      * * @param methodNameUpdater operator applied to the current value; its result becomes the new @@ -549,6 +990,156 @@ public MethodDtoBuilder modifierUpdate(UnaryOperator modifierUpd return this; } + /** + * Adds a single element to parameters. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Parameters(MethodParameterDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public MethodDtoBuilder add2Parameters(MethodParameterDto element) { + List newCollection; + if (this.parameters.isSet()) { + newCollection = new ArrayList<>(this.parameters.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.parameters = changedValue(newCollection); + return this; + } + + /** + * Sets the value for parameters. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(MethodParameterDtoBuilder.create().build(), MethodParameterDtoBuilder.create().build());
      +   * }
      + * + * @param parameters the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder parameters(MethodParameterDto... parameters) { + this.parameters = changedValue(List.of(parameters)); + return this; + } + + /** + * Sets the value for parameters using a builder consumer that produces the value. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(t -> t.add(methodParameterDtoBuilder -> methodParameterDtoBuilder));
      +   * }
      + * + * @param parametersBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder parameters( + Consumer> + parametersBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.parameters.isSet() + ? new ArrayListBuilderWithElementBuilders< + MethodParameterDto, MethodParameterDtoBuilder>( + this.parameters.value(), MethodParameterDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders< + MethodParameterDto, MethodParameterDtoBuilder>(MethodParameterDtoBuilder::create); + parametersBuilderConsumer.accept(builder); + this.parameters = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for parameters by invoking the provided supplier. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(() -> List.of(MethodParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param parametersSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder parameters(Supplier> parametersSupplier) { + this.parameters = changedValue(parametersSupplier.get()); + return this; + } + + /** + * Sets the value for parameters. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(List.of(MethodParameterDtoBuilder.create().build()));
      +   * }
      + * + * @param parameters the replacement collection (not null) + * @return current instance of builder + */ + public MethodDtoBuilder parameters(List parameters) { + this.parameters = changedValue(parameters); + return this; + } + + /** + * Updates the current value of parameters in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #parameters(Consumer)}. + * + *

      Generated from setter {@link MethodDto#setParameters(List) + * setParameters(List parameters)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.parameters(List.of(MethodParameterDtoBuilder.create().build()))
      +   *     .parametersUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param parametersUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if parameters has not been set yet + */ + public MethodDtoBuilder parametersUpdate( + UnaryOperator> parametersUpdater) { + if (!this.parameters.isSet()) { + throw new IllegalStateException("Cannot update 'parameters' before it is set"); + } + this.parameters = changedValue(parametersUpdater.apply(this.parameters.value())); + return this; + } + /** * Sets the value for returnType by invoking the provided supplier. * @@ -641,16 +1232,21 @@ public MethodDtoBuilder conditional( * MethodDto result = builder.build(); * } */ + @Override public MethodDto build() { if (this.isStatic.isSet() && this.isStatic.value() == null) { throw new IllegalStateException( "Field 'isStatic' is marked as non-null but null value was provided"); } MethodDto result = new MethodDto(this.methodName.value(), this.returnType.value()); + this.annotations.ifSet(result::setAnnotations); this.code.ifSet(result::setCode); - this.isStatic.ifSet(result::setStatic); + this.genericParameters.ifSet(result::setGenericParameters); this.javadoc.ifSet(result::setJavadoc); + this.methodCodeDto.ifSet(result::setMethodCodeDto); this.modifier.ifSet(result::setModifier); + this.parameters.ifSet(result::setParameters); + this.isStatic.ifSet(result::setStatic); return result; } @@ -664,10 +1260,14 @@ public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) .append("methodName", this.methodName) .append("returnType", this.returnType) + .append("annotations", this.annotations) .append("code", this.code) - .append("isStatic", this.isStatic) + .append("genericParameters", this.genericParameters) .append("javadoc", this.javadoc) + .append("methodCodeDto", this.methodCodeDto) .append("modifier", this.modifier) + .append("parameters", this.parameters) + .append("isStatic", this.isStatic) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDto.java index dcd3d669..c02d4395 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDto.java @@ -31,6 +31,19 @@ /** MethodParameterDto contains all information for generating parameters in method headers. */ public class MethodParameterDto { + + /** + * Replaces annotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param annotations the replacement collection (not null) + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + List copy = new ArrayList<>(annotations); + this.annotations.clear(); + this.annotations.addAll(copy); + } + /** Name of parameter. */ private String parameterName; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java index 3f079d0e..79d30dab 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java @@ -21,19 +21,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.method; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -49,16 +57,26 @@ * *
      {@code
        * MethodParameterDto result = MethodParameterDtoBuilder.create()
      - *     .parameterName("example value")
      + *     .annotations(List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(() -> List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder))
      + *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
      + *     .annotationsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Annotations(AnnotationDtoBuilder.create().build())
      + *     .parameterName("example parameterName")
        *     .parameterName("Hello %s", "World")
      - *     .parameterName(() -> "example value")
      + *     .parameterName(() -> "example parameterName")
        *     .parameterName(sb -> sb.append("text"))
        *     .parameterNameUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class MethodParameterDtoBuilder { +@BuilderImplementation(forClass = MethodParameterDto.class) +public class MethodParameterDtoBuilder implements IBuilderBase { + + /** Tracked value for annotations: the replacement collection (not null). */ + private TrackedValue> annotations = unsetValue(); /** Tracked value for parameterName: parameter name. */ private TrackedValue parameterName = unsetValue(); @@ -79,6 +97,7 @@ public MethodParameterDtoBuilder() {} * @param instance object instance for initialisiation */ public MethodParameterDtoBuilder(MethodParameterDto instance) { + this.annotations = initialValue(instance.getAnnotations()); this.parameterName = initialValue(instance.getParameterName()); } @@ -97,6 +116,155 @@ public static MethodParameterDtoBuilder create() { return new MethodParameterDtoBuilder(); } + /** + * Adds a single element to annotations. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public MethodParameterDtoBuilder add2Annotations(AnnotationDto element) { + List newCollection; + if (this.annotations.isSet()) { + newCollection = new ArrayList<>(this.annotations.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.annotations = changedValue(newCollection); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder annotations(AnnotationDto... annotations) { + this.annotations = changedValue(List.of(annotations)); + return this; + } + + /** + * Sets the value for annotations using a builder consumer that produces the value. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
      +   * }
      + * + * @param annotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder annotations( + Consumer> + annotationsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.annotations.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.annotations.value(), AnnotationDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + AnnotationDtoBuilder::create); + annotationsBuilderConsumer.accept(builder); + this.annotations = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(() -> List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotationsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder annotations(Supplier> annotationsSupplier) { + this.annotations = changedValue(annotationsSupplier.get()); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public MethodParameterDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Updates the current value of annotations in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #annotations(Consumer)}. + * + *

      Generated from setter {@link MethodParameterDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()))
      +   *     .annotationsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param annotationsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if annotations has not been set yet + */ + public MethodParameterDtoBuilder annotationsUpdate( + UnaryOperator> annotationsUpdater) { + if (!this.annotations.isSet()) { + throw new IllegalStateException("Cannot update 'annotations' before it is set"); + } + this.annotations = changedValue(annotationsUpdater.apply(this.annotations.value())); + return this; + } + /** * Sets the value for parameterName by executing the provided consumer. * @@ -129,7 +297,7 @@ public MethodParameterDtoBuilder parameterName( *

      Example:

      * *
      {@code
      -   * builder.parameterName(() -> "example value");
      +   * builder.parameterName(() -> "example parameterName");
          * }
      * * @param parameterNameSupplier supplier for parameter name @@ -171,7 +339,7 @@ public MethodParameterDtoBuilder parameterName(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.parameterName("example value");
      +   * builder.parameterName("example parameterName");
          * }
      * * @param parameterName parameter name @@ -195,7 +363,7 @@ public MethodParameterDtoBuilder parameterName(String parameterName) { *

      Example:

      * *
      {@code
      -   * builder.parameterName("example value").parameterNameUpdate(String::trim);
      +   * builder.parameterName("example parameterName").parameterNameUpdate(String::trim);
          * }
      * * @param parameterNameUpdater operator applied to the current value; its result becomes the new @@ -305,8 +473,10 @@ public MethodParameterDtoBuilder conditional( * MethodParameterDto result = builder.build(); * } */ + @Override public MethodParameterDto build() { MethodParameterDto result = new MethodParameterDto(); + this.annotations.ifSet(result::setAnnotations); this.parameterName.ifSet(result::setParameterName); this.parameterTypeName.ifSet(result::setParameterTypeName); return result; @@ -320,6 +490,7 @@ public MethodParameterDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("annotations", this.annotations) .append("parameterName", this.parameterName) .append("parameterTypeName", this.parameterTypeName) .toString(); diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDto.java index d6b4565a..350c5c96 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDto.java @@ -24,11 +24,25 @@ package org.javahelpers.codegen.model.type; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** Represents a generic type parameter (e.g., {@code T extends Number & Comparable}). */ public class GenericParameterDto { + + /** + * Replaces upperBounds with a defensive copy; the DTO retains its own mutable collection. + * + * @param upperBounds the replacement collection (not null) + * @throws NullPointerException if upperBounds is null + */ + public void setUpperBounds(List upperBounds) { + List copy = new ArrayList<>(upperBounds); + this.upperBounds.clear(); + this.upperBounds.addAll(copy); + } + /** The name of the generic parameter (e.g., "T"). */ private String name; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java index 82d0a1b1..12829199 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java @@ -21,18 +21,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.type; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilder; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -48,20 +54,25 @@ * *
      {@code
        * GenericParameterDto result = GenericParameterDtoBuilder.create()
      - *     .name("example value")
      + *     .name("example name")
        *     .name("Hello %s", "World")
      - *     .name(() -> "example value")
      + *     .name(() -> "example name")
        *     .name(sb -> sb.append("text"))
        *     .nameUpdate(String::trim)
      + *     .upperBoundsUpdate(list -> list.stream().sorted().toList())
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class GenericParameterDtoBuilder { +@BuilderImplementation(forClass = GenericParameterDto.class) +public class GenericParameterDtoBuilder implements IBuilderBase { /** Tracked value for name: the name to set (e.g., "T", "K", "V"). */ private TrackedValue name = unsetValue(); + /** Tracked value for upperBounds: the replacement collection (not null). */ + private TrackedValue> upperBounds = unsetValue(); + /** * Empty constructor of builder for {@code * org.javahelpers.codegen.model.type.GenericParameterDto}. @@ -76,6 +87,7 @@ public GenericParameterDtoBuilder() {} */ public GenericParameterDtoBuilder(GenericParameterDto instance) { this.name = initialValue(instance.getName()); + this.upperBounds = initialValue(instance.getUpperBounds()); } /** @@ -123,7 +135,7 @@ public GenericParameterDtoBuilder name(Consumer nameStringBuilder *

      Example:

      * *
      {@code
      -   * builder.name(() -> "example value");
      +   * builder.name(() -> "example name");
          * }
      * * @param nameSupplier supplier for the name to set (e.g., "T", "K", "V") @@ -163,7 +175,7 @@ public GenericParameterDtoBuilder name(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.name("example value");
      +   * builder.name("example name");
          * }
      * * @param name the name to set (e.g., "T", "K", "V") @@ -186,7 +198,7 @@ public GenericParameterDtoBuilder name(String name) { *

      Example:

      * *
      {@code
      -   * builder.name("example value").nameUpdate(String::trim);
      +   * builder.name("example name").nameUpdate(String::trim);
          * }
      * * @param nameUpdater operator applied to the current value; its result becomes the new value @@ -201,6 +213,120 @@ public GenericParameterDtoBuilder nameUpdate(UnaryOperator nameUpdater) return this; } + /** + * Adds a single element to upperBounds. + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + * @param element the element to add + * @return current instance of builder + */ + public GenericParameterDtoBuilder add2UpperBounds(TypeName element) { + List newCollection; + if (this.upperBounds.isSet()) { + newCollection = new ArrayList<>(this.upperBounds.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.upperBounds = changedValue(newCollection); + return this; + } + + /** + * Sets the value for upperBounds. + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + * @param upperBounds the replacement collection (not null) + * @return current instance of builder + */ + public GenericParameterDtoBuilder upperBounds(TypeName... upperBounds) { + this.upperBounds = changedValue(List.of(upperBounds)); + return this; + } + + /** + * Sets the value for upperBounds using a builder consumer that produces the value. + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + * @param upperBoundsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public GenericParameterDtoBuilder upperBounds( + Consumer> upperBoundsBuilderConsumer) { + ArrayListBuilder builder = + this.upperBounds.isSet() + ? new ArrayListBuilder(this.upperBounds.value()) + : new ArrayListBuilder(); + upperBoundsBuilderConsumer.accept(builder); + this.upperBounds = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for upperBounds by invoking the provided supplier. + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + * @param upperBoundsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public GenericParameterDtoBuilder upperBounds(Supplier> upperBoundsSupplier) { + this.upperBounds = changedValue(upperBoundsSupplier.get()); + return this; + } + + /** + * Sets the value for upperBounds. + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + * @param upperBounds the replacement collection (not null) + * @return current instance of builder + */ + public GenericParameterDtoBuilder upperBounds(List upperBounds) { + this.upperBounds = changedValue(upperBounds); + return this; + } + + /** + * Updates the current value of upperBounds in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). + * + *

      Generated from setter {@link GenericParameterDto#setUpperBounds(List) + * setUpperBounds(List upperBounds)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.upperBoundsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param upperBoundsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if upperBounds has not been set yet + */ + public GenericParameterDtoBuilder upperBoundsUpdate( + UnaryOperator> upperBoundsUpdater) { + if (!this.upperBounds.isSet()) { + throw new IllegalStateException("Cannot update 'upperBounds' before it is set"); + } + this.upperBounds = changedValue(upperBoundsUpdater.apply(this.upperBounds.value())); + return this; + } + /** * Conditionally applies builder modifications if the condition is true. * @@ -242,9 +368,11 @@ public GenericParameterDtoBuilder conditional( * GenericParameterDto result = builder.build(); * } */ + @Override public GenericParameterDto build() { GenericParameterDto result = new GenericParameterDto(); this.name.ifSet(result::setName); + this.upperBounds.ifSet(result::setUpperBounds); return result; } @@ -257,6 +385,7 @@ public GenericParameterDto build() { public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) .append("name", this.name) + .append("upperBounds", this.upperBounds) .toString(); } diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java index e2e15cb9..d999e41a 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java @@ -43,6 +43,30 @@ */ public class NestedTypeDto { + /** + * Replaces methods with a defensive copy; the DTO retains its own mutable collection. + * + * @param methods the replacement collection (not null) + * @throws NullPointerException if methods is null + */ + public void setMethods(List methods) { + List copy = new ArrayList<>(methods); + this.methods.clear(); + this.methods.addAll(copy); + } + + /** + * Replaces annotations with a defensive copy; the DTO retains its own mutable collection. + * + * @param annotations the replacement collection (not null) + * @throws NullPointerException if annotations is null + */ + public void setAnnotations(List annotations) { + List copy = new ArrayList<>(annotations); + this.annotations.clear(); + this.annotations.addAll(copy); + } + /** The simple name of the nested type (e.g., "With"). */ private String typeName; diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java index d809286e..f48166aa 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java @@ -21,12 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ + package org.javahelpers.codegen.model.type; import static org.javahelpers.simple.builders.core.util.TrackedValue.changedValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.initialValue; import static org.javahelpers.simple.builders.core.util.TrackedValue.unsetValue; +import java.util.ArrayList; +import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -34,8 +37,15 @@ import javax.annotation.processing.Generated; import org.apache.commons.lang3.builder.ToStringBuilder; import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; import org.javahelpers.codegen.model.javadoc.JavadocDto; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.simple.builders.core.annotations.BuilderImplementation; +import org.javahelpers.simple.builders.core.builders.ArrayListBuilderWithElementBuilders; +import org.javahelpers.simple.builders.core.interfaces.IBuilderBase; import org.javahelpers.simple.builders.core.util.BuilderToStringStyle; import org.javahelpers.simple.builders.core.util.TrackedValue; @@ -51,19 +61,35 @@ * *
      {@code
        * NestedTypeDto result = NestedTypeDtoBuilder.create()
      + *     .annotations(List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(() -> List.of(AnnotationDtoBuilder.create().build()))
      + *     .annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder))
      + *     .annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build())
      + *     .annotationsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Annotations(AnnotationDtoBuilder.create().build())
        *     .javadoc(new JavadocDto())
        *     .javadoc(JavadocDto::new)
        *     .javadoc(javadocDtoBuilder -> javadocDtoBuilder)
      - *     .typeName("example value")
      + *     .methods(List.of(MethodDtoBuilder.create().build()))
      + *     .methods(() -> List.of(MethodDtoBuilder.create().build()))
      + *     .methods(t -> t.add(methodDtoBuilder -> methodDtoBuilder))
      + *     .methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build())
      + *     .methodsUpdate(list -> list.stream().sorted().toList())
      + *     .add2Methods(MethodDtoBuilder.create().build())
      + *     .typeName("example typeName")
        *     .typeName("Hello %s", "World")
      - *     .typeName(() -> "example value")
      + *     .typeName(() -> "example typeName")
        *     .typeName(sb -> sb.append("text"))
        *     .typeNameUpdate(String::trim)
        *     .build();
        * }
      */ @Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") -public class NestedTypeDtoBuilder { +@BuilderImplementation(forClass = NestedTypeDto.class) +public class NestedTypeDtoBuilder implements IBuilderBase { + + /** Tracked value for annotations: the replacement collection (not null). */ + private TrackedValue> annotations = unsetValue(); /** Tracked value for javadoc: javadoc. */ private TrackedValue javadoc = unsetValue(); @@ -72,6 +98,9 @@ public class NestedTypeDtoBuilder { private TrackedValue kind = unsetValue(); + /** Tracked value for methods: the replacement collection (not null). */ + private TrackedValue> methods = unsetValue(); + /** Tracked value for typeName: typeName. */ private TrackedValue typeName = unsetValue(); @@ -88,8 +117,10 @@ public NestedTypeDtoBuilder() {} * @param instance object instance for initialisiation */ public NestedTypeDtoBuilder(NestedTypeDto instance) { + this.annotations = initialValue(instance.getAnnotations()); this.javadoc = initialValue(instance.getJavadoc()); this.kind = initialValue(instance.getKind()); + this.methods = initialValue(instance.getMethods()); this.typeName = initialValue(instance.getTypeName()); this.visibility = initialValue(instance.getVisibility()); } @@ -109,6 +140,155 @@ public static NestedTypeDtoBuilder create() { return new NestedTypeDtoBuilder(); } + /** + * Adds a single element to annotations. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Annotations(AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public NestedTypeDtoBuilder add2Annotations(AnnotationDto element) { + List newCollection; + if (this.annotations.isSet()) { + newCollection = new ArrayList<>(this.annotations.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.annotations = changedValue(newCollection); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(AnnotationDtoBuilder.create().build(), AnnotationDtoBuilder.create().build());
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder annotations(AnnotationDto... annotations) { + this.annotations = changedValue(List.of(annotations)); + return this; + } + + /** + * Sets the value for annotations using a builder consumer that produces the value. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
      +   * }
      + * + * @param annotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder annotations( + Consumer> + annotationsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.annotations.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.annotations.value(), AnnotationDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + AnnotationDtoBuilder::create); + annotationsBuilderConsumer.accept(builder); + this.annotations = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for annotations by invoking the provided supplier. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(() -> List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotationsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder annotations(Supplier> annotationsSupplier) { + this.annotations = changedValue(annotationsSupplier.get()); + return this; + } + + /** + * Sets the value for annotations. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()));
      +   * }
      + * + * @param annotations the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder annotations(List annotations) { + this.annotations = changedValue(annotations); + return this; + } + + /** + * Updates the current value of annotations in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #annotations(Consumer)}. + * + *

      Generated from setter {@link NestedTypeDto#setAnnotations(List) + * setAnnotations(List annotations)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.annotations(List.of(AnnotationDtoBuilder.create().build()))
      +   *     .annotationsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param annotationsUpdater operator applied to the current value; its result becomes the new + * value + * @return current instance of builder + * @throws IllegalStateException if annotations has not been set yet + */ + public NestedTypeDtoBuilder annotationsUpdate( + UnaryOperator> annotationsUpdater) { + if (!this.annotations.isSet()) { + throw new IllegalStateException("Cannot update 'annotations' before it is set"); + } + this.annotations = changedValue(annotationsUpdater.apply(this.annotations.value())); + return this; + } + /** * Sets the value for javadoc using a builder consumer that produces the value. * @@ -250,6 +430,152 @@ public NestedTypeDtoBuilder kindUpdate( return this; } + /** + * Adds a single element to methods. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.add2Methods(MethodDtoBuilder.create().build());
      +   * }
      + * + * @param element the element to add + * @return current instance of builder + */ + public NestedTypeDtoBuilder add2Methods(MethodDto element) { + List newCollection; + if (this.methods.isSet()) { + newCollection = new ArrayList<>(this.methods.value()); + } else { + newCollection = new ArrayList<>(); + } + newCollection.add(element); + this.methods = changedValue(newCollection); + return this; + } + + /** + * Sets the value for methods. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(MethodDtoBuilder.create().build(), MethodDtoBuilder.create().build());
      +   * }
      + * + * @param methods the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder methods(MethodDto... methods) { + this.methods = changedValue(List.of(methods)); + return this; + } + + /** + * Sets the value for methods using a builder consumer that produces the value. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(t -> t.add(methodDtoBuilder -> methodDtoBuilder));
      +   * }
      + * + * @param methodsBuilderConsumer consumer providing an instance of a builder for the replacement + * collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder methods( + Consumer> + methodsBuilderConsumer) { + ArrayListBuilderWithElementBuilders builder = + this.methods.isSet() + ? new ArrayListBuilderWithElementBuilders( + this.methods.value(), MethodDtoBuilder::create) + : new ArrayListBuilderWithElementBuilders( + MethodDtoBuilder::create); + methodsBuilderConsumer.accept(builder); + this.methods = changedValue(builder.build()); + return this; + } + + /** + * Sets the value for methods by invoking the provided supplier. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(() -> List.of(MethodDtoBuilder.create().build()));
      +   * }
      + * + * @param methodsSupplier supplier for the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder methods(Supplier> methodsSupplier) { + this.methods = changedValue(methodsSupplier.get()); + return this; + } + + /** + * Sets the value for methods. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(List.of(MethodDtoBuilder.create().build()));
      +   * }
      + * + * @param methods the replacement collection (not null) + * @return current instance of builder + */ + public NestedTypeDtoBuilder methods(List methods) { + this.methods = changedValue(methods); + return this; + } + + /** + * Updates the current value of methods in place by applying the given operator, + * instead of reading it out, changing it and setting it again. Useful for adjustments relative to + * the current value, e.g. trimming, upper-casing, clamping or incrementing, and in combination + * with the With copy-and-modify flow. The value must have been set before (directly + * or via an existing instance). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #methods(Consumer)}. + * + *

      Generated from setter {@link NestedTypeDto#setMethods(List) setMethods(List + * methods)} + * + *

      Example:

      + * + *
      {@code
      +   * builder.methods(List.of(MethodDtoBuilder.create().build())).methodsUpdate(list -> list.stream().sorted().toList());
      +   * }
      + * + * @param methodsUpdater operator applied to the current value; its result becomes the new value + * @return current instance of builder + * @throws IllegalStateException if methods has not been set yet + */ + public NestedTypeDtoBuilder methodsUpdate(UnaryOperator> methodsUpdater) { + if (!this.methods.isSet()) { + throw new IllegalStateException("Cannot update 'methods' before it is set"); + } + this.methods = changedValue(methodsUpdater.apply(this.methods.value())); + return this; + } + /** * Sets the value for typeName by executing the provided consumer. * @@ -279,7 +605,7 @@ public NestedTypeDtoBuilder typeName(Consumer typeNameStringBuild *

      Example:

      * *
      {@code
      -   * builder.typeName(() -> "example value");
      +   * builder.typeName(() -> "example typeName");
          * }
      * * @param typeNameSupplier supplier for typeName @@ -319,7 +645,7 @@ public NestedTypeDtoBuilder typeName(String format, Object... args) { *

      Example:

      * *
      {@code
      -   * builder.typeName("example value");
      +   * builder.typeName("example typeName");
          * }
      * * @param typeName typeName @@ -342,7 +668,7 @@ public NestedTypeDtoBuilder typeName(String typeName) { *

      Example:

      * *
      {@code
      -   * builder.typeName("example value").typeNameUpdate(String::trim);
      +   * builder.typeName("example typeName").typeNameUpdate(String::trim);
          * }
      * * @param typeNameUpdater operator applied to the current value; its result becomes the new value @@ -449,10 +775,13 @@ public NestedTypeDtoBuilder conditional( * NestedTypeDto result = builder.build(); * } */ + @Override public NestedTypeDto build() { NestedTypeDto result = new NestedTypeDto(); + this.annotations.ifSet(result::setAnnotations); this.javadoc.ifSet(result::setJavadoc); this.kind.ifSet(result::setKind); + this.methods.ifSet(result::setMethods); this.typeName.ifSet(result::setTypeName); this.visibility.ifSet(result::setVisibility); return result; @@ -466,8 +795,10 @@ public NestedTypeDto build() { @Override public String toString() { return new ToStringBuilder(this, BuilderToStringStyle.INSTANCE) + .append("annotations", this.annotations) .append("javadoc", this.javadoc) .append("kind", this.kind) + .append("methods", this.methods) .append("typeName", this.typeName) .append("visibility", this.visibility) .toString(); diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java new file mode 100644 index 00000000..fb0ea2d0 --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java @@ -0,0 +1,334 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.model.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.AnnotationDtoBuilder; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.imports.RegularImport; +import org.javahelpers.codegen.model.javadoc.JavadocCodeBlockDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; +import org.javahelpers.codegen.model.method.CodeTemplateDto; +import org.javahelpers.codegen.model.method.CodeTemplateDtoBuilder; +import org.javahelpers.codegen.model.method.ConstructorDto; +import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodeDto; +import org.javahelpers.codegen.model.method.MethodCodeDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodePlaceholder; +import org.javahelpers.codegen.model.method.MethodCodeStringPlaceholder; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodDtoBuilder; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.method.MethodParameterDtoBuilder; +import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDtoBuilder; +import org.javahelpers.codegen.model.type.NestedTypeDto; +import org.javahelpers.codegen.model.type.NestedTypeDtoBuilder; +import org.javahelpers.codegen.model.type.TypeName; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +/** Each committed builder constructs complete state, including collection properties. */ +class CodegenDtoBuildersTest { + private static final AnnotationDto ANNOTATION = + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(Deprecated.class)) + .members(Map.of("since", "\"1\"")) + .build(); + private static final ImportStatement IMPORT = new RegularImport(TypeName.of(List.class)); + private static final MethodCodePlaceholder ARGUMENT = + new MethodCodeStringPlaceholder("value", "message"); + + @Test + void buildsAnnotation() { + AnnotationDto dto = + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(Deprecated.class)) + .members(Map.of("since", "\"2\"")) + .build(); + assertEquals(TypeName.of(Deprecated.class), dto.getAnnotationType()); + assertEquals(Map.of("since", "\"2\""), dto.getMembers()); + } + + @Test + void buildsClassField() { + ClassFieldDto dto = + ClassFieldDtoBuilder.create() + .fieldName("names") + .fieldType(TypeName.of(List.class)) + .fieldTypeImports(Set.of(IMPORT)) + .build(); + assertEquals("names", dto.getFieldName()); + assertEquals(TypeName.of(List.class), dto.getFieldType()); + assertEquals(Set.of(IMPORT), dto.getFieldTypeImports()); + } + + @Test + void buildsParameter() { + MethodParameterDto dto = parameter(); + assertEquals("value", dto.getParameterName()); + assertEquals(TypeName.of(String.class), dto.getParameterType()); + assertEquals(List.of(ANNOTATION), dto.getAnnotations()); + } + + @Test + void buildsMethod() { + MethodParameterDto parameter = parameter(); + GenericParameterDto generic = generic(); + MethodCodeDto code = code(); + MethodDto dto = + MethodDtoBuilder.create() + .methodName("render") + .isStatic(true) + .parameters(List.of(parameter)) + .genericParameters(List.of(generic)) + .annotations(List.of(ANNOTATION)) + .methodCodeDto(code) + .build(); + assertEquals("render", dto.getMethodName()); + assertEquals(true, dto.isStatic()); + assertEquals(List.of(parameter), dto.getParameters()); + assertEquals(List.of(generic), dto.getGenericParameters()); + assertEquals(List.of(ANNOTATION), dto.getAnnotations()); + assertCode(dto.getMethodCodeDto()); + assertNotSame(code, dto.getMethodCodeDto()); + code.setCodeArguments(List.of()); + assertEquals(List.of(ARGUMENT), dto.getMethodCodeDto().getCodeArguments()); + } + + @Test + void buildsConstructor() { + MethodParameterDto parameter = parameter(); + MethodCodeDto code = code(); + ConstructorDto dto = + ConstructorDtoBuilder.create() + .parameters(List.of(parameter)) + .annotations(List.of(ANNOTATION)) + .methodCodeDto(code) + .build(); + assertEquals(List.of(parameter), dto.getParameters()); + assertEquals(List.of(ANNOTATION), dto.getAnnotations()); + assertCode(dto.getMethodCodeDto()); + } + + @Test + void buildsGenericParameter() { + GenericParameterDto dto = generic(); + assertEquals("T", dto.getName()); + assertEquals(List.of(TypeName.of(Number.class)), dto.getUpperBounds()); + } + + @Test + void buildsNestedType() { + MethodDto method = MethodDtoBuilder.create().methodName("apply").build(); + NestedTypeDto dto = + NestedTypeDtoBuilder.create() + .typeName("Factory") + .methods(List.of(method)) + .annotations(List.of(ANNOTATION)) + .build(); + assertEquals("Factory", dto.getTypeName()); + assertEquals(List.of(method), dto.getMethods()); + assertEquals(List.of(ANNOTATION), dto.getAnnotations()); + } + + @Test + void buildsJavadoc() { + JavadocTagDto tag = new JavadocTagDto("return", "a value"); + JavadocDto dto = + JavadocDtoBuilder.create().format("Summary").args(new Object[0]).tags(List.of(tag)).build(); + assertEquals("Summary", dto.getDescription()); + assertEquals(List.of(tag), dto.getTags()); + } + + @Test + void buildsCodeTemplate() { + assertCode( + CodeTemplateDtoBuilder.create() + .codeFormat("return $value:S;") + .codeArguments(List.of(ARGUMENT)) + .codeBlockImports(Set.of(IMPORT)) + .build()); + } + + @Test + void buildsMethodCode() { + assertCode(code()); + } + + @Test + void buildsJavadocCodeBlock() { + assertCode( + JavadocCodeBlockDtoBuilder.create() + .codeFormat("return $value:S;") + .codeArguments(List.of(ARGUMENT)) + .codeBlockImports(Set.of(IMPORT)) + .build()); + } + + @Test + void buildsGenerationTarget() { + ClassFieldDto field = ClassFieldDtoBuilder.create().fieldName("value").build(); + MethodDto method = MethodDtoBuilder.create().methodName("apply").build(); + ConstructorDto constructor = ConstructorDtoBuilder.create().build(); + GenericParameterDto generic = generic(); + NestedTypeDto nested = NestedTypeDtoBuilder.create().typeName("Factory").build(); + InterfaceName contract = new InterfaceName("java.lang", "Runnable"); + GenerationTargetClassDto dto = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("example", "Target")) + .classFields(List.of(field)) + .methods(List.of(method)) + .constructors(List.of(constructor)) + .generics(List.of(generic)) + .interfaces(Set.of(contract)) + .nestedTypes(List.of(nested)) + .classAnnotations(Set.of(ANNOTATION)) + .imports(Set.of(IMPORT)) + .build(); + assertEquals(new TypeName("example", "Target"), dto.getTypeName()); + assertEquals(List.of(field), dto.getClassFields()); + assertEquals(List.of(method), dto.getMethods()); + assertEquals(List.of(constructor), dto.getConstructors()); + assertEquals(List.of(generic), dto.getGenerics()); + assertEquals(Set.of(contract), dto.getInterfaces()); + assertEquals(List.of(nested), dto.getNestedTypes()); + assertEquals(Set.of(ANNOTATION), dto.getClassAnnotations()); + assertEquals(Set.of(IMPORT), dto.getImports()); + } + + @TestFactory + Stream collectionSettersCopyClearAndRejectNull() { + return Stream.of( + GenerationTargetClassDto.class, + ClassFieldDto.class, + MethodDto.class, + ConstructorDto.class, + MethodParameterDto.class, + CodeTemplateDto.class, + GenericParameterDto.class, + NestedTypeDto.class, + AnnotationDto.class, + JavadocDto.class) + .flatMap(type -> Arrays.stream(type.getDeclaredMethods())) + .filter(method -> method.getName().startsWith("set") && method.getParameterCount() == 1) + .filter( + method -> + Collection.class.isAssignableFrom(method.getParameterTypes()[0]) + || Map.class.isAssignableFrom(method.getParameterTypes()[0])) + .map( + setter -> + DynamicTest.dynamicTest( + setter.getDeclaringClass().getSimpleName() + "." + setter.getName(), + () -> assertCollectionContract(setter))); + } + + private static void assertCollectionContract(Method setter) throws Exception { + Object dto = setter.getDeclaringClass().getConstructor().newInstance(); + Method getter = setter.getDeclaringClass().getMethod("get" + setter.getName().substring(3)); + boolean map = Map.class.isAssignableFrom(setter.getParameterTypes()[0]); + boolean set = Set.class.isAssignableFrom(setter.getParameterTypes()[0]); + Object marker = new Object(); + Object input = + map + ? new LinkedHashMap<>(Map.of("key", marker)) + : set ? new LinkedHashSet<>(Set.of(marker)) : new ArrayList<>(List.of(marker)); + Object expected = map ? Map.of("key", marker) : set ? Set.of(marker) : List.of(marker); + setter.invoke(dto, input); + if (input instanceof Map values) { + values.clear(); + } else { + ((Collection) input).clear(); + } + assertEquals(expected, getter.invoke(dto)); + setter.invoke(dto, getter.invoke(dto)); + assertEquals(expected, getter.invoke(dto)); + InvocationTargetException failure = + assertThrows( + InvocationTargetException.class, () -> setter.invoke(dto, new Object[] {null})); + assertInstanceOf(NullPointerException.class, failure.getCause()); + assertEquals(expected, getter.invoke(dto)); + setter.invoke(dto, input); + assertEquals(input, getter.invoke(dto)); + } + + @Test + void structuredBodyRejectsNullAndSupportsSelfAssignment() { + MethodDto dto = MethodDtoBuilder.create().methodCodeDto(code()).build(); + assertThrows(NullPointerException.class, () -> dto.setMethodCodeDto(null)); + assertCode(dto.getMethodCodeDto()); + dto.setMethodCodeDto(dto.getMethodCodeDto()); + assertCode(dto.getMethodCodeDto()); + } + + private static MethodParameterDto parameter() { + return MethodParameterDtoBuilder.create() + .parameterName("value") + .parameterTypeName(TypeName.of(String.class)) + .annotations(List.of(ANNOTATION)) + .build(); + } + + private static GenericParameterDto generic() { + return GenericParameterDtoBuilder.create() + .name("T") + .upperBounds(List.of(TypeName.of(Number.class))) + .build(); + } + + private static MethodCodeDto code() { + return MethodCodeDtoBuilder.create() + .codeFormat("return $value:S;") + .codeArguments(List.of(ARGUMENT)) + .codeBlockImports(Set.of(IMPORT)) + .build(); + } + + private static void assertCode(CodeTemplateDto dto) { + assertEquals("return $value:S;", dto.getCodeFormat()); + assertEquals(List.of(ARGUMENT), dto.getCodeArguments()); + assertEquals(Set.of(IMPORT), dto.getCodeBlockImports()); + } +} diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java index 539cf80f..20c9961d 100644 --- a/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java @@ -102,8 +102,7 @@ void builderInitializedFromInstanceAppliesChanges() { @Test void methodDtoBuilderCoversIsStaticFlag() { - // MethodDto.setStatic resolves to property "static" (a Java keyword) and is ignored; the - // setIsStatic alias exposes the flag to the generated builder instead. + // The isStatic getter supplies a legal property name for the setStatic setter. MethodDto method = MethodDtoBuilder.create().methodName("m").isStatic(true).build(); assertEquals("m", method.getMethodName()); diff --git a/docs/CODEGEN_BUILDERS.md b/docs/CODEGEN_BUILDERS.md new file mode 100644 index 00000000..1a3eb3a1 --- /dev/null +++ b/docs/CODEGEN_BUILDERS.md @@ -0,0 +1,24 @@ +# Regenerating the codegen DTO builders + +The twelve `*DtoBuilder.java` files under `codegen-core/src/main/java` are +committed bootstrap sources: the processor itself depends on codegen-core. +Use Java 17 and run these commands from the repository root: + +```sh +mvn -pl processor -am install -Dmaven.test.skip=true +mvn -pl processor -Dtest=CodegenDtoBuilderRegenerationTest -Dcodegen.regenerate=true test +mvn -pl codegen-core fmt:format +git diff --exit-code -- 'codegen-core/src/main/java/**/*Builder.java' +``` + +The explicit regeneration test compiles the model sources and same-package +`@SimpleBuilderFor` holders with the current processor, asserts that exactly twelve +builders were emitted, and replaces only those committed builders. It is disabled +in ordinary builds. After intentional model or generator changes, review and +commit the regenerated files; otherwise the final command must report no changes. +Java CI runs regeneration after installing the reactor and rejects drift. + +Collection setters replace contents with a shallow defensive copy into each DTO's +own mutable collection. They reject null collections with `NullPointerException` +before modifying existing state. Empty collections clear the property, and passing +the DTO's own collection is supported. Existing `addX` methods remain available. diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java new file mode 100644 index 00000000..b3c26957 --- /dev/null +++ b/processor/src/test/java/org/javahelpers/simple/builders/processor/CodegenDtoBuilderRegenerationTest.java @@ -0,0 +1,126 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.simple.builders.processor; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.google.testing.compile.Compilation; +import com.google.testing.compile.JavaFileObjects; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.tools.JavaFileObject; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** Explicit regeneration entry point; ordinary builds never rewrite committed sources. */ +@EnabledIfSystemProperty(named = "codegen.regenerate", matches = "true") +class CodegenDtoBuilderRegenerationTest { + + @Test + void regenerateBuilders() throws Exception { + Path root = Path.of(System.getProperty("basedir")).getParent(); + Path sources = root.resolve("codegen-core/src/main/java"); + List inputs = new ArrayList<>(); + try (var paths = Files.walk(sources)) { + for (Path path : + paths + .filter(p -> p.toString().endsWith(".java")) + .filter(p -> !p.toString().endsWith("Builder.java")) + .sorted() + .toList()) { + String className = + sources.relativize(path).toString().replace('/', '.').replace(".java", ""); + inputs.add(JavaFileObjects.forSourceString(className, Files.readString(path))); + } + } + for (String group : + List.of( + "core:GenerationTargetClassDto,ClassFieldDto", + "method:MethodDto,ConstructorDto,MethodParameterDto,CodeTemplateDto,MethodCodeDto", + "type:GenericParameterDto,NestedTypeDto", + "annotation:AnnotationDto", + "javadoc:JavadocDto,JavadocCodeBlockDto")) { + String[] parts = group.split(":"); + String packageName = "org.javahelpers.codegen.model." + parts[0]; + String types = + java.util.Arrays.stream(parts[1].split(",")) + .map(name -> name + ".class") + .collect(java.util.stream.Collectors.joining(", ")); + inputs.add( + JavaFileObjects.forSourceString( + packageName + ".CodegenBuilders", + """ + package %s; + @org.javahelpers.simple.builders.core.annotations.SimpleBuilderFor({%s}) + class CodegenBuilders {} + """ + .formatted(packageName, types))); + } + + File codegenClasses = + new File( + GenerationTargetClassDto.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toURI()); + List classpath = + Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) + .map(File::new) + .filter(file -> !file.equals(codegenClasses)) + .toList(); + Compilation compilation = + ProcessorTestUtils.createCompiler() + .withClasspath(classpath) + .withOptions("-Asimplebuilder.strict=true") + .compile(inputs); + assertThat(compilation).succeeded(); + List builders = + compilation.generatedSourceFiles().stream() + .filter(file -> file.getName().endsWith("Builder.java")) + .toList(); + assertEquals(12, builders.size()); + String header = + "/*\n" + + Files.readAllLines(root.resolve("LICENSE.txt")).stream() + .map(line -> line.isEmpty() ? " *" : " * " + line) + .collect(java.util.stream.Collectors.joining("\n")) + + "\n */\n\n"; + for (JavaFileObject builder : builders) { + String source = builder.getCharContent(false).toString(); + String packageName = source.substring(source.indexOf("package ") + 8, source.indexOf(';')); + String fileName = Path.of(builder.toUri().getPath()).getFileName().toString(); + Files.writeString( + sources.resolve(packageName.replace('.', '/')).resolve(fileName), header + source); + } + } +} From d0abb334b05297c424d0d18052e98cd5586b1b41 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:00:08 +0000 Subject: [PATCH 15/15] Build conformance fixtures entirely with DTO builders --- .../testing/GeneratorConformanceTest.java | 257 ++++++++++-------- 1 file changed, 145 insertions(+), 112 deletions(-) diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java index 01aa8386..53d49622 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java @@ -31,7 +31,10 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.ServiceLoader; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -51,8 +54,13 @@ import org.javahelpers.codegen.model.core.ClassFieldDtoBuilder; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; import org.javahelpers.codegen.model.core.GenerationTargetClassDtoBuilder; +import org.javahelpers.codegen.model.imports.StaticImport; import org.javahelpers.codegen.model.javadoc.JavadocDtoBuilder; +import org.javahelpers.codegen.model.javadoc.JavadocTagDto; import org.javahelpers.codegen.model.method.ConstructorDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodeDtoBuilder; +import org.javahelpers.codegen.model.method.MethodCodeStringPlaceholder; +import org.javahelpers.codegen.model.method.MethodCodeTypePlaceholder; import org.javahelpers.codegen.model.method.MethodDto; import org.javahelpers.codegen.model.method.MethodDtoBuilder; import org.javahelpers.codegen.model.method.MethodParameterDto; @@ -111,24 +119,27 @@ static Stream backends() { @MethodSource("backends") void simpleClassWithFieldsMethodsAndConstructor_compiles(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("SimpleClass"); - - addField(classDef, "name", TypeName.of(String.class)); - addField(classDef, "age", TypeNamePrimitive.INT); - addField(classDef, "active", TypeNamePrimitive.BOOLEAN); - - var ctor = ConstructorDtoBuilder.create().visibility(AccessModifier.PUBLIC).build(); - ctor.getMethodCodeDto().setCodeFormat("this.name = name;"); - ctor.addParameter(param("name", TypeName.of(String.class))); - classDef.addConstructor(ctor); - - classDef.addMethod( - MethodDtoBuilder.create() - .methodName("describe") - .returnType(TypeName.of(String.class)) - .modifier(AccessModifier.PUBLIC) - .code("return name + \"#\" + age;") - .build()); + GenerationTargetClassDto classDef = + baseClass("SimpleClass") + .classFields( + field("name", TypeName.of(String.class)), + field("age", TypeNamePrimitive.INT), + field("active", TypeNamePrimitive.BOOLEAN)) + .constructors( + ConstructorDtoBuilder.create() + .visibility(AccessModifier.PUBLIC) + .methodCodeDto( + MethodCodeDtoBuilder.create().codeFormat("this.name = name;").build()) + .parameters(param("name", TypeName.of(String.class))) + .build()) + .methods( + MethodDtoBuilder.create() + .methodName("describe") + .returnType(TypeName.of(String.class)) + .modifier(AccessModifier.PUBLIC) + .code("return name + \"#\" + age;") + .build()) + .build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -152,11 +163,12 @@ public String describe() { @ParameterizedTest(name = "{0}") @MethodSource("backends") void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("GenericBox"); - var generic = GenericParameterDtoBuilder.create().name("T").build(); - generic.addUpperBound( - new TypeNameGeneric(TypeName.of(Comparable.class), new TypeNameVariable("T"))); - classDef.addGeneric(generic); + var generic = + GenericParameterDtoBuilder.create() + .name("T") + .upperBounds( + new TypeNameGeneric(TypeName.of(Comparable.class), new TypeNameVariable("T"))) + .build(); MethodDto method = MethodDtoBuilder.create() @@ -165,13 +177,17 @@ void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exc .modifier(AccessModifier.PUBLIC) .isStatic(true) .code("return first;") + .genericParameters( + GenericParameterDtoBuilder.create() + .name("R") + .upperBounds(TypeName.of(Number.class)) + .build()) + .parameters( + param("first", new TypeNameVariable("R")), + param("second", new TypeNameVariable("R"))) .build(); - var methodGeneric = GenericParameterDtoBuilder.create().name("R").build(); - methodGeneric.addUpperBound(TypeName.of(Number.class)); - method.addGenericParameter(methodGeneric); - method.addParameter(param("first", new TypeNameVariable("R"))); - method.addParameter(param("second", new TypeNameVariable("R"))); - classDef.addMethod(method); + GenerationTargetClassDto classDef = + baseClass("GenericBox").generics(generic).methods(method).build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -189,18 +205,19 @@ public static R pick(R first, R second) { @ParameterizedTest(name = "{0}") @MethodSource("backends") void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("ContainerClass"); - - addField(classDef, "names", new TypeNameGeneric(List.class, String.class)); - addField( - classDef, - "scores", - new TypeNameGeneric( - TypeName.of(java.util.Map.class), - TypeName.of(String.class), - TypeName.of(Integer.class))); - addField(classDef, "numbers", new TypeNameArray(TypeNamePrimitive.INT)); - addField(classDef, "nickname", new TypeNameGeneric(java.util.Optional.class, String.class)); + GenerationTargetClassDto classDef = + baseClass("ContainerClass") + .classFields( + field("names", new TypeNameGeneric(List.class, String.class)), + field( + "scores", + new TypeNameGeneric( + TypeName.of(java.util.Map.class), + TypeName.of(String.class), + TypeName.of(Integer.class))), + field("numbers", new TypeNameArray(TypeNamePrimitive.INT)), + field("nickname", new TypeNameGeneric(java.util.Optional.class, String.class))) + .build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -221,20 +238,21 @@ void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws @ParameterizedTest(name = "{0}") @MethodSource("backends") void collidingSimpleNames_areDisambiguated(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("CollidingDates"); - - addField(classDef, "utilDate", new TypeName("java.util", "Date")); - addField(classDef, "sqlDate", new TypeName("java.sql", "Date")); - MethodDto method = MethodDtoBuilder.create() .methodName("touch") .returnType(TypeNamePrimitive.VOID) .modifier(AccessModifier.PUBLIC) .code("if (when == null) { return; }") + .parameters(param("when", new TypeName("java.sql", "Date"))) + .build(); + GenerationTargetClassDto classDef = + baseClass("CollidingDates") + .classFields( + field("utilDate", new TypeName("java.util", "Date")), + field("sqlDate", new TypeName("java.sql", "Date"))) + .methods(method) .build(); - method.addParameter(param("when", new TypeName("java.sql", "Date"))); - classDef.addMethod(method); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -254,22 +272,20 @@ public void touch(java.sql.Date when) { @ParameterizedTest(name = "{0}") @MethodSource("backends") void nestedTypesWithMembers_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("OuterClass"); - NestedTypeDto nested = NestedTypeDtoBuilder.create() .typeName("Helper") .kind(NestedTypeDto.NestedTypeKind.CLASS) .visibility(AccessModifier.PUBLIC) + .methods( + MethodDtoBuilder.create() + .methodName("assist") + .returnType(TypeNamePrimitive.VOID) + .modifier(AccessModifier.PUBLIC) + .code("int touched = 0;") + .build()) .build(); - nested.addMethod( - MethodDtoBuilder.create() - .methodName("assist") - .returnType(TypeNamePrimitive.VOID) - .modifier(AccessModifier.PUBLIC) - .code("int touched = 0;") - .build()); - classDef.addNestedType(nested); + GenerationTargetClassDto classDef = baseClass("OuterClass").nestedTypes(nested).build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -287,29 +303,36 @@ public void assist() { @ParameterizedTest(name = "{0}") @MethodSource("backends") void annotationsOnClassMembersAndTypeUse_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("AnnotatedClass"); - AnnotationDto deprecated = - AnnotationDtoBuilder.create().annotationType(TypeName.of(Deprecated.class)).build(); - deprecated.addMember("since", "\"0.9\""); - deprecated.addMember("forRemoval", "true"); - classDef.addClassAnnotation(deprecated); + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(Deprecated.class)) + .members( + () -> + Stream.of(Map.entry("since", "\"0.9\""), Map.entry("forRemoval", "true")) + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (first, second) -> first, + LinkedHashMap::new))) + .build(); AnnotationDto generated = AnnotationDtoBuilder.create() .annotationType(new TypeName("javax.annotation.processing", "Generated")) + .members(Map.of("value", "\"conformance\"")) .build(); - generated.addMember("value", "\"conformance\""); - classDef.addClassAnnotation(generated); TypeName annotatedString = TypeName.of(String.class); - annotatedString - .getAnnotations() - .add( - AnnotationDtoBuilder.create() - .annotationType(TypeName.of(TestTypeUseAnnotation.class)) - .build()); - addField(classDef, "flagged", annotatedString); + annotatedString.addAnnotation( + AnnotationDtoBuilder.create() + .annotationType(TypeName.of(TestTypeUseAnnotation.class)) + .build()); + GenerationTargetClassDto classDef = + baseClass("AnnotatedClass") + .classAnnotations(new LinkedHashSet<>(List.of(deprecated, generated))) + .classFields(field("flagged", annotatedString)) + .build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -328,22 +351,22 @@ public class AnnotatedClass { @ParameterizedTest(name = "{0}") @MethodSource("backends") void codeTemplatePlaceholders_resolve(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("TemplateClass"); - MethodDto method = MethodDtoBuilder.create() .methodName("parse") .returnType(TypeNamePrimitive.LONG) .modifier(AccessModifier.PUBLIC) + .methodCodeDto( + MethodCodeDtoBuilder.create() + .codeFormat("int $l:L = 0;\n$b:B box = null;\nreturn $t:T.parseLong($s:S);") + .codeArguments( + new MethodCodeStringPlaceholder("l", "count"), + new MethodCodeTypePlaceholder("b", TypeNamePrimitive.INT), + new MethodCodeTypePlaceholder("t", TypeName.of(Long.class)), + new MethodCodeStringPlaceholder("s", "42")) + .build()) .build(); - method - .getMethodCodeDto() - .setCodeFormat("int $l:L = 0;\n$b:B box = null;\nreturn $t:T.parseLong($s:S);"); - method.getMethodCodeDto().addArgument("l", "count"); - method.getMethodCodeDto().addArgument("b", TypeNamePrimitive.INT); - method.getMethodCodeDto().addArgument("t", TypeName.of(Long.class)); - method.getMethodCodeDto().addArgument("s", "42"); - classDef.addMethod(method); + GenerationTargetClassDto classDef = baseClass("TemplateClass").methods(method).build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -361,10 +384,15 @@ public long parse() { @ParameterizedTest(name = "{0}") @MethodSource("backends") void superTypeAndInterfaces_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("DerivedClass"); - classDef.setSuperType(new TypeNameGeneric(java.util.ArrayList.class, String.class)); - classDef.addInterface(new InterfaceName("java.io", "Serializable")); - classDef.addInterface(new InterfaceName("java.lang", "Cloneable")); + GenerationTargetClassDto classDef = + baseClass("DerivedClass") + .superType(new TypeNameGeneric(java.util.ArrayList.class, String.class)) + .interfaces( + new LinkedHashSet<>( + List.of( + new InterfaceName("java.io", "Serializable"), + new InterfaceName("java.lang", "Cloneable")))) + .build(); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -379,9 +407,6 @@ public class DerivedClass extends ArrayList implements Serializable, Clo @ParameterizedTest(name = "{0}") @MethodSource("backends") void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("FactoryClass"); - classDef.addStaticImport(java.util.Collections.class, "emptyList"); - ClassFieldDto field = ClassFieldDtoBuilder.create() .fieldName("initial") @@ -389,7 +414,6 @@ void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws E .visibility(AccessModifier.PRIVATE) .literalInitializer("emptyList()") .build(); - classDef.addClassField(field); MethodDto factory = MethodDtoBuilder.create() @@ -398,9 +422,14 @@ void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws E .modifier(AccessModifier.PUBLIC) .isStatic(true) .code("return names.length;") + .parameters(param("names", new TypeNameArray(TypeName.of(String.class)))) + .build(); + GenerationTargetClassDto classDef = + baseClass("FactoryClass") + .imports(new StaticImport(TypeName.of(java.util.Collections.class), "emptyList")) + .classFields(field) + .methods(factory) .build(); - factory.addParameter(param("names", new TypeNameArray(TypeName.of(String.class)))); - classDef.addMethod(factory); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -422,13 +451,14 @@ public static int of(String... names) { @ParameterizedTest(name = "{0}") @MethodSource("backends") void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exception { - GenerationTargetClassDto classDef = baseClass("DocumentedClass"); - classDef.setClassJavadoc( - JavadocDtoBuilder.create().format("Documented conformance class.").args().build()); - - var javadoc = JavadocDtoBuilder.create().format("Echoes the value.").args().build(); - javadoc.addParam("value", "the input"); - javadoc.addReturn("the echoed value"); + var javadoc = + JavadocDtoBuilder.create() + .format("Echoes the value.") + .args() + .tags( + new JavadocTagDto("param", "value the input"), + new JavadocTagDto("return", "the echoed value")) + .build(); MethodDto method = MethodDtoBuilder.create() .methodName("echo") @@ -436,9 +466,14 @@ void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exce .modifier(AccessModifier.PUBLIC) .javadoc(javadoc) .code("return value;") + .parameters(param("value", TypeName.of(String.class))) + .build(); + GenerationTargetClassDto classDef = + baseClass("DocumentedClass") + .classJavadoc( + JavadocDtoBuilder.create().format("Documented conformance class.").args().build()) + .methods(method) .build(); - method.addParameter(param("value", TypeName.of(String.class))); - classDef.addMethod(method); String source = generate(backend, classDef); assertCompiles(classDef, source); @@ -514,21 +549,19 @@ private void assertCompiles(GenerationTargetClassDto classDef, String source) th } } - private static GenerationTargetClassDto baseClass(String simpleName) { + private static GenerationTargetClassDtoBuilder baseClass(String simpleName) { return GenerationTargetClassDtoBuilder.create() .typeName(new TypeName(PACKAGE, simpleName)) .classAccessModifier(AccessModifier.PUBLIC) - .formattingMode(FormattingMode.NONE) - .build(); + .formattingMode(FormattingMode.NONE); } - private static void addField(GenerationTargetClassDto classDef, String name, TypeName type) { - classDef.addClassField( - ClassFieldDtoBuilder.create() - .fieldName(name) - .fieldType(type) - .visibility(AccessModifier.PRIVATE) - .build()); + private static ClassFieldDto field(String name, TypeName type) { + return ClassFieldDtoBuilder.create() + .fieldName(name) + .fieldType(type) + .visibility(AccessModifier.PRIVATE) + .build(); } private static MethodParameterDto param(String name, TypeName type) {