diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index f42d933b2..a5e4c649b 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -80,6 +80,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/pom.xml b/codegen-core/pom.xml index 910bba1c4..f5389e8e5 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/AnnotationDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDto.java index 73bfc2a85..916c8211c 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 new file mode 100644 index 000000000..8e9a9a794 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/annotation/AnnotationDtoBuilder.java @@ -0,0 +1,366 @@ +/* + * 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.Map; +import java.util.Map.Entry; +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.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; + +/** + * 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. + * + *

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") +@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}. + */ + 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()); + this.members = initialValue(instance.getMembers()); + } + + /** + * 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; + } + + /** + * 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. + * + * @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();
+   * }
+ */ + @Override + public AnnotationDto build() { + AnnotationDto result = new AnnotationDto(); + this.annotationType.ifSet(result::setAnnotationType); + this.members.ifSet(result::setMembers); + 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) + .append("members", this.members) + .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/ClassFieldDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDto.java index 67fbf592b..0fe222718 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 new file mode 100644 index 000000000..7b3782b3b --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/ClassFieldDtoBuilder.java @@ -0,0 +1,776 @@ +/* + * 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.HashSet; +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.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; + +/** + * 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 fieldName")
+ *     .fieldName("Hello %s", "World")
+ *     .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 literalInitializer")
+ *     .literalInitializer("Hello %s", "World")
+ *     .literalInitializer(() -> "example literalInitializer")
+ *     .literalInitializer(sb -> sb.append("text"))
+ *     .literalInitializerUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@BuilderImplementation(forClass = ClassFieldDto.class) +public class ClassFieldDtoBuilder implements IBuilderBase { + + /** Tracked value for fieldName: fieldName. */ + private TrackedValue fieldName = unsetValue(); + + /** 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(); + + /** 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.fieldTypeImports = initialValue(instance.getFieldTypeImports()); + 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 fieldName");
+   * }
+ * + * @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 fieldName");
+   * }
+ * + * @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 fieldName").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; + } + + /** + * 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. + * + *

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 literalInitializer");
+   * }
+ * + * @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 literalInitializer");
+   * }
+ * + * @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 literalInitializer").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();
+   * }
+ */ + @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); + 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("fieldTypeImports", this.fieldTypeImports) + .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/GenerationTargetClassDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDto.java index f84636ceb..9d659dab0 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 new file mode 100644 index 000000000..a9caffc04 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilder.java @@ -0,0 +1,1759 @@ +/* + * 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.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.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; + +/** + * 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()
+ *     .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") +@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(); + + /** 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.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()); + } + + /** + * 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; + } + + /** + * Adds a single element to classAnnotations. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2ClassAnnotations(AnnotationDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + 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 classAnnotations. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.classAnnotations(t -> t.add(annotationDtoBuilder -> annotationDtoBuilder));
+   * }
+ * + * @param classAnnotationsBuilderConsumer consumer providing an instance of a builder for the + * replacement collection (not null) + * @return current instance of builder + */ + 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; + } + + /** + * Sets the value for classAnnotations by invoking the provided supplier. + * + *

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

Example:

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

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

Example:

+ * + *
{@code
+   * builder.classAnnotations(Set.of(AnnotationDtoBuilder.create().build()));
+   * }
+ * + * @param classAnnotations the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classAnnotations(Set classAnnotations) { + this.classAnnotations = changedValue(classAnnotations); + return this; + } + + /** + * 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). For changing multiple elements of a nested DTO, + * prefer the builder-consumer helper {@link #classAnnotations(Consumer)}. + * + *

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

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 classAnnotations has not been set yet + */ + public GenerationTargetClassDtoBuilder classAnnotationsUpdate( + UnaryOperator> classAnnotationsUpdater) { + if (!this.classAnnotations.isSet()) { + throw new IllegalStateException("Cannot update 'classAnnotations' before it is set"); + } + this.classAnnotations = + changedValue(classAnnotationsUpdater.apply(this.classAnnotations.value())); + return this; + } + + /** + * Adds a single element to classFields. + * + *

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

Example:

+ * + *
{@code
+   * builder.add2ClassFields(ClassFieldDtoBuilder.create().build());
+   * }
+ * + * @param element the element to add + * @return current instance of builder + */ + 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 classFields. + * + *

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

Example:

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

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

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 + */ + 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 classFields by invoking the provided supplier. + * + *

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

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 classFields( + Supplier> classFieldsSupplier) { + this.classFields = changedValue(classFieldsSupplier.get()); + return this; + } + + /** + * Sets the value for classFields. + * + *

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

Example:

+ * + *
{@code
+   * builder.classFields(List.of(ClassFieldDtoBuilder.create().build()));
+   * }
+ * + * @param classFields the replacement collection (not null) + * @return current instance of builder + */ + public GenerationTargetClassDtoBuilder classFields(List classFields) { + this.classFields = changedValue(classFields); + return this; + } + + /** + * 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). For changing multiple elements of a nested DTO, prefer the + * builder-consumer helper {@link #classFields(Consumer)}. + * + *

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

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 classFields has not been set yet + */ + public GenerationTargetClassDtoBuilder classFieldsUpdate( + UnaryOperator> classFieldsUpdater) { + if (!this.classFields.isSet()) { + throw new IllegalStateException("Cannot update 'classFields' before it is set"); + } + this.classFields = changedValue(classFieldsUpdater.apply(this.classFields.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; + } + + /** + * 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; + } + + /** + * 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("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(); + } + + /** 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 000000000..7a0fc9e3e --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocCodeBlockDtoBuilder.java @@ -0,0 +1,565 @@ +/* + * 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.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; + +/** + * 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()
+ *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
+ *     .codeBlockImportsUpdate(TreeSet::new)
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .codeFormatUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@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(); + + /** + * 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.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); + 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(); + } + + /** + * 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. + * + *

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 codeFormat");
+   * }
+ * + * @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 codeFormat");
+   * }
+ * + * @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 codeFormat").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();
+   * }
+ */ + @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; + } + + /** + * 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("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) + .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/JavadocDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDto.java index 51cb2224d..76aaf6ebd 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 new file mode 100644 index 000000000..fddd50d01 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/javadoc/JavadocDtoBuilder.java @@ -0,0 +1,617 @@ +/* + * 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.ArrayList; +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.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; + +/** + * 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 format")
+ *     .format("Hello %s", "World")
+ *     .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") +@BuilderImplementation(forClass = JavadocDto.class) +public class JavadocDtoBuilder implements IBuilderBase { + + /** 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(); + + /** 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() {} + + /** + * 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()); + this.tags = initialValue(instance.getTags()); + } + + /** + * 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 format");
+   * }
+ * + * @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 format");
+   * }
+ * + * @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 format").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; + } + + /** + * 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. + * + * @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();
+   * }
+ */ + @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; + } + + /** + * 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) + .append("tags", this.tags) + .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/CodeTemplateDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDto.java index 2b45684b5..5fc506b52 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 new file mode 100644 index 000000000..246be1f6e --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/CodeTemplateDtoBuilder.java @@ -0,0 +1,563 @@ +/* + * 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.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; + +/** + * 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()
+ *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
+ *     .codeBlockImportsUpdate(TreeSet::new)
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .codeFormatUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@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(); + + /** + * 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.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); + 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(); + } + + /** + * 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. + * + *

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 codeFormat");
+   * }
+ * + * @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 codeFormat");
+   * }
+ * + * @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 codeFormat").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();
+   * }
+ */ + @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; + } + + /** + * 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("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) + .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/ConstructorDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDto.java index 936d453f2..0aad92c84 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 new file mode 100644 index 000000000..19a97b904 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/ConstructorDtoBuilder.java @@ -0,0 +1,771 @@ +/* + * 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.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.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; + +/** + * 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()
+ *     .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") +@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(); + + /** 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(); + + /** + * 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.annotations = initialValue(instance.getAnnotations()); + this.javadoc = initialValue(instance.getJavadoc()); + this.methodCodeDto = initialValue(instance.getMethodCodeDto()); + this.parameters = initialValue(instance.getParameters()); + 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(); + } + + /** + * 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. + * + *

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; + } + + /** + * 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. + * + *

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();
+   * }
+ */ + @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; + } + + /** + * 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("annotations", this.annotations) + .append("javadoc", this.javadoc) + .append("methodCodeDto", this.methodCodeDto) + .append("parameters", this.parameters) + .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 000000000..4363c1d54 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodCodeDtoBuilder.java @@ -0,0 +1,562 @@ +/* + * 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.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; + +/** + * 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()
+ *     .codeArgumentsUpdate(list -> list.stream().sorted().toList())
+ *     .codeBlockImportsUpdate(TreeSet::new)
+ *     .codeFormat("example codeFormat")
+ *     .codeFormat("Hello %s", "World")
+ *     .codeFormat(() -> "example codeFormat")
+ *     .codeFormat(sb -> sb.append("text"))
+ *     .codeFormatUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@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(); + + /** + * 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.codeArguments = initialValue(instance.getCodeArguments()); + this.codeBlockImports = initialValue(instance.getCodeBlockImports()); + 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(); + } + + /** + * 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. + * + *

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 codeFormat");
+   * }
+ * + * @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 codeFormat");
+   * }
+ * + * @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 codeFormat").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();
+   * }
+ */ + @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; + } + + /** + * 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("codeArguments", this.codeArguments) + .append("codeBlockImports", this.codeBlockImports) + .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/MethodDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDto.java index cb6c456a6..545875f90 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 new file mode 100644 index 000000000..c61ad0110 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodDtoBuilder.java @@ -0,0 +1,1311 @@ +/* + * 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.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.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; + +/** + * 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 methodName")
+ *     .methodName("Hello %s", "World")
+ *     .methodName(() -> "example methodName")
+ *     .methodName(sb -> sb.append("text"))
+ *     .methodNameUpdate(String::trim)
+ *     .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 code")
+ *     .code(sb -> sb.append("text"))
+ *     .codeUpdate(String::trim)
+ *     .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") +@BuilderImplementation(forClass = MethodDto.class) +public class MethodDtoBuilder implements IBuilderBase { + + /** Tracked value for methodName: methodName. */ + private TrackedValue methodName = unsetValue(); + + /** 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 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() {} + + /** + * 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.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()); + } + + /** + * 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(); + } + + /** + * 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. + * + *

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 code");
+   * }
+ * + * @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 code");
+   * }
+ * + * @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 code").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; + } + + /** + * 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. + * + *

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 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. + * + *

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 methodName");
+   * }
+ * + * @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 methodName");
+   * }
+ * + * @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 methodName").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; + } + + /** + * 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. + * + *

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();
+   * }
+ */ + @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.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; + } + + /** + * 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("annotations", this.annotations) + .append("code", this.code) + .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(); + } + + /** 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/MethodParameterDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDto.java index dcd3d6691..c02d4395d 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 new file mode 100644 index 000000000..79d30daba --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/method/MethodParameterDtoBuilder.java @@ -0,0 +1,536 @@ +/* + * 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.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; + +/** + * 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()
+ *     .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 parameterName")
+ *     .parameterName(sb -> sb.append("text"))
+ *     .parameterNameUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@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(); + + /** 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.annotations = initialValue(instance.getAnnotations()); + 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(); + } + + /** + * 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. + * + *

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 parameterName");
+   * }
+ * + * @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 parameterName");
+   * }
+ * + * @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 parameterName").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();
+   * }
+ */ + @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; + } + + /** + * 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("annotations", this.annotations) + .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/GenericParameterDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDto.java index d6b4565a7..350c5c96e 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 new file mode 100644 index 000000000..12829199d --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/GenericParameterDtoBuilder.java @@ -0,0 +1,429 @@ +/* + * 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.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; + +/** + * 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 name")
+ *     .name("Hello %s", "World")
+ *     .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") +@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}. + */ + 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()); + this.upperBounds = initialValue(instance.getUpperBounds()); + } + + /** + * 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 name");
+   * }
+ * + * @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 name");
+   * }
+ * + * @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 name").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; + } + + /** + * 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. + * + * @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();
+   * }
+ */ + @Override + public GenericParameterDto build() { + GenericParameterDto result = new GenericParameterDto(); + this.name.ifSet(result::setName); + this.upperBounds.ifSet(result::setUpperBounds); + 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) + .append("upperBounds", this.upperBounds) + .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/NestedTypeDto.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDto.java index e2e15cb93..d999e41ac 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 new file mode 100644 index 000000000..f48166aa5 --- /dev/null +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/NestedTypeDtoBuilder.java @@ -0,0 +1,844 @@ +/* + * 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.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.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; + +/** + * 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()
+ *     .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)
+ *     .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 typeName")
+ *     .typeName(sb -> sb.append("text"))
+ *     .typeNameUpdate(String::trim)
+ *     .build();
+ * }
+ */ +@Generated("Generated by org.javahelpers.simple.builders.processor.BuilderProcessor") +@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(); + + /** Tracked value for kind: kind. */ + 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(); + + /** 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.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()); + } + + /** + * 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(); + } + + /** + * 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. + * + *

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; + } + + /** + * 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. + * + *

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 typeName");
+   * }
+ * + * @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 typeName");
+   * }
+ * + * @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 typeName").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();
+   * }
+ */ + @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; + } + + /** + * 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("annotations", this.annotations) + .append("javadoc", this.javadoc) + .append("kind", this.kind) + .append("methods", this.methods) + .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/main/java/org/javahelpers/codegen/util/ImportCollector.java b/codegen-core/src/main/java/org/javahelpers/codegen/util/ImportCollector.java index 5a3f42422..c2f626860 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 @@ -88,6 +88,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/core/CodegenDtoBuildersTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/CodegenDtoBuildersTest.java new file mode 100644 index 000000000..fb0ea2d0d --- /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 new file mode 100644 index 000000000..20c9961d8 --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/model/core/GenerationTargetClassDtoBuilderTest.java @@ -0,0 +1,111 @@ +/* + * 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() { + // 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()); + 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 b4a7f31a9..546818d8c 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 @@ -33,11 +33,15 @@ import java.util.Set; import java.util.stream.Collectors; 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.CodeTemplateDto; 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.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNameWildcard; @@ -94,16 +98,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 @@ -141,10 +140,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/pom.xml b/codegen-roaster/pom.xml index 886f27afb..6f40ac6a8 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/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index 10d42bb7c..36a104ec5 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 f6777256f..daecbb6a2 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 @@ -33,16 +33,25 @@ 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.JavadocCodeBlockDto; 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.TypeNameArray; import org.javahelpers.codegen.model.type.TypeNameGeneric; @@ -169,10 +178,12 @@ 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()); } @@ -323,16 +334,21 @@ public String x() { @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); @@ -352,27 +368,36 @@ 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"); - generic.addUpperBound(TypeName.of(Number.class)); + GenerationTargetClassDto classDef = + GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName("test", "GenericBuilder")) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE) + .build(); + GenericParameterDto generic = + GenericParameterDtoBuilder.create() + .name("T") + .upperBounds(TypeName.of(Number.class)) + .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( @@ -478,25 +503,31 @@ public abstract void onDone() { @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); @@ -515,19 +546,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); @@ -548,25 +587,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( @@ -612,33 +659,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 1684f0350..552ddce4f 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 @@ -30,8 +30,10 @@ import java.util.List; import java.util.Set; 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; @@ -125,8 +127,8 @@ void mapType_rendersNestedGenericQualified() { @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, Set.of())); } @@ -151,15 +153,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, Set.of())); } @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, Set.of())); @@ -167,14 +169,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, Set.of())); } @@ -192,8 +196,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, Set.of())); } @@ -215,8 +219,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)); @@ -229,9 +235,12 @@ 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, Set.of())); @@ -239,8 +248,7 @@ void resolveCodeTemplate_rewritesTrackedValueFactoryNames() { @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, Set.of())); 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 000000000..ffe818245 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterTestBackendProvider.java @@ -0,0 +1,53 @@ +/* + * 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, RoasterSourceFormatter.DEFAULT_FORMATTER_PROFILE_RESOURCE); + } + + @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 000000000..f265fa8e7 --- /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/pom.xml b/codegen-testing/pom.xml index 4b5bfca61..dd147c83c 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 new file mode 100644 index 000000000..8d8b47b66 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/GeneratorConformanceTest.java @@ -0,0 +1,571 @@ +/* + * 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.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; +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.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; +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 #364) 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 — exact declarations and blocks, ignoring whitespace + *
+ * + *

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(ServiceLoader.Provider::get) + .map(provider -> Arguments.of(Named.of(provider.name(), provider))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void simpleClassWithFieldsMethodsAndConstructor_compiles(TestBackendProvider backend) + throws Exception { + 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); + assertContaining( + 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}") + @MethodSource("backends") + void genericClassAndMethodBounds_compile(TestBackendProvider backend) throws Exception { + var generic = + GenericParameterDtoBuilder.create() + .name("T") + .upperBounds( + new TypeNameGeneric(TypeName.of(Comparable.class), new TypeNameVariable("T"))) + .build(); + + MethodDto method = + MethodDtoBuilder.create() + .methodName("pick") + .returnType(new TypeNameVariable("R")) + .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(); + GenerationTargetClassDto classDef = + baseClass("GenericBox").generics(generic).methods(method).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, + """ + public class GenericBox> { + public static R pick(R first, R second) { + return first; + } + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void collectionArrayAndOptionalTypes_compile(TestBackendProvider backend) throws Exception { + 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); + assertContaining( + source, + """ + private List names; + private Map scores; + private int[] numbers; + private 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 { + 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(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + // The colliding type that wins the import renders by simple name; the loser stays qualified. + assertContaining( + source, + """ + private java.util.Date utilDate; + private Date sqlDate; + public void touch(java.sql.Date when) { + if (when == null) { + return; + } + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void nestedTypesWithMembers_compile(TestBackendProvider backend) throws Exception { + 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(); + GenerationTargetClassDto classDef = baseClass("OuterClass").nestedTypes(nested).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, + """ + public class Helper { + public void assist() { + int touched = 0; + } + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void annotationsOnClassMembersAndTypeUse_compile(TestBackendProvider backend) throws Exception { + AnnotationDto 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(); + + TypeName annotatedString = TypeName.of(String.class); + 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); + assertContaining( + source, + """ + @Deprecated(since = "0.9", forRemoval = true) + @Generated("conformance") + public class AnnotatedClass { + @TestTypeUseAnnotation + private String flagged; + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void codeTemplatePlaceholders_resolve(TestBackendProvider backend) throws Exception { + 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(); + GenerationTargetClassDto classDef = baseClass("TemplateClass").methods(method).build(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, + """ + public long parse() { + int count = 0; + Integer box = null; + return Long.parseLong("42"); + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void superTypeAndInterfaces_compile(TestBackendProvider backend) throws Exception { + 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); + assertContaining( + source, + """ + public class DerivedClass extends ArrayList implements Serializable, Cloneable { + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void staticImportsAndStaticFactory_compile(TestBackendProvider backend) throws Exception { + ClassFieldDto field = + ClassFieldDtoBuilder.create() + .fieldName("initial") + .fieldType(new TypeNameGeneric(List.class, String.class)) + .visibility(AccessModifier.PRIVATE) + .literalInitializer("emptyList()") + .build(); + + MethodDto factory = + MethodDtoBuilder.create() + .methodName("of") + .returnType(TypeNamePrimitive.INT) + .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(); + + String source = generate(backend, classDef); + assertCompiles(classDef, source); + assertContaining( + source, + """ + import static java.util.Collections.emptyList; + """, + """ + private List initial = emptyList(); + """, + """ + public static int of(String... names) { + return names.length; + } + """); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("backends") + void javadocIsEmittedForClassAndMembers(TestBackendProvider backend) throws Exception { + 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") + .returnType(TypeName.of(String.class)) + .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(); + + String source = generate(backend, classDef); + 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. */ + 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 GenerationTargetClassDtoBuilder baseClass(String simpleName) { + return GenerationTargetClassDtoBuilder.create() + .typeName(new TypeName(PACKAGE, simpleName)) + .classAccessModifier(AccessModifier.PUBLIC) + .formattingMode(FormattingMode.NONE); + } + + 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) { + 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 000000000..dc264a63e --- /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 #364) 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 000000000..36ffa8136 --- /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 {} diff --git a/docs/CODEGEN_BUILDERS.md b/docs/CODEGEN_BUILDERS.md new file mode 100644 index 000000000..1a3eb3a10 --- /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/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java b/example/generated-example-builder/org/javahelpers/simple/builders/example/BookDtoBuilder.java index 3de32abff..504dbf11f 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 metadata", "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 metadata", "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 7c8de9c9a..dbbaee356 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 7e7671f0a..af8ba15f6 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 51089eb77..119bf279b 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 d0c1e671f..1890737fb 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 327027f07..7d0366f30 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 9316d7fc8..eb83a499f 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 84c9f5362..6d350b6c2 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 74ae41adb..8ec1f9425 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 94fdf114d..fedb2c4d0 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 3d5d65406..809553026 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 @@ -198,7 +198,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 5daae4c92..801156ed0 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 98ff52e72..3414eebf5 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 32ae11048..637cbd361 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 @@ -164,7 +164,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); } @@ -190,12 +191,19 @@ 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, 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 c1eeabaab..15dbed584 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 @@ -117,7 +117,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 7f90f1a55..33e620744 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 @@ -155,7 +155,8 @@ public List generateMethods( Map.of(), builderType, context); - addExampleToSetConsumerWithSimpleValue(method, elementType, context::resolveBuilderType); + addExampleToSetConsumerWithSimpleValue( + method, elementType, field.getOriginalFieldName(), context::resolveBuilderType); return List.of(method); } @@ -180,12 +181,19 @@ 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, 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 7440fc775..2296a6e63 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 b68a7b9ea..d80ddd660 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 3a256f99b..94bd74bba 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 @@ -171,11 +171,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 @@ -184,6 +190,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 dec68d219..a02c79035 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; @@ -47,6 +48,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 +102,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 @@ -113,17 +117,21 @@ private JavadocExampleValues() { *
* * @param typeName the type name to get an example value for + * @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 */ public static Optional getExampleValue( - TypeName typeName, Function> builderResolver) { + 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 +144,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(); } @@ -154,11 +164,17 @@ 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, + String fieldName, Function> builderResolver) { - return getExampleValue(collectionType.getElementType(), builderResolver) + return getExampleValue(collectionType.getElementType(), fieldName, builderResolver) .or( () -> builderResolver @@ -167,10 +183,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 +197,12 @@ private static Optional resolveArray( } private static Optional resolveMap( - TypeNameMap mapType, Function> builderResolver) { - Optional keyExample = getExampleValue(mapType.getKeyType(), builderResolver); - Optional valueExample = getExampleValue(mapType.getValueType(), builderResolver); + TypeNameMap mapType, + String fieldName, + Function> builderResolver) { + Optional keyExample = getExampleValue(mapType.getKeyType(), fieldName, builderResolver); + Optional valueExample = + getExampleValue(mapType.getValueType(), fieldName, builderResolver); if (keyExample.isPresent() && valueExample.isPresent()) { return Optional.of("Map.of(" + keyExample.get() + ", " + valueExample.get() + ")"); } @@ -189,11 +210,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 +230,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 (StringUtils.isBlank(fieldName)) { + 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 fb6f10876..d44ae9732 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,13 +464,16 @@ 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 + * @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, TypeName fieldType, + String fieldName, Function> builderResolver) { addExampleChainFragmentTemplate( - methodDto, "#{methodName}(#{exampleValue})", fieldType, builderResolver); + methodDto, "#{methodName}(#{exampleValue})", fieldType, fieldName, builderResolver); } /** @@ -486,13 +489,20 @@ 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 + * @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, TypeName elementType, + String fieldName, Function> builderResolver) { addExampleChainFragmentTemplate( - methodDto, "#{methodName}(#{exampleValue}, #{exampleValue})", elementType, builderResolver); + methodDto, + "#{methodName}(#{exampleValue}, #{exampleValue})", + elementType, + fieldName, + builderResolver); } /** @@ -508,17 +518,20 @@ 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 + * @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, 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); } } @@ -540,17 +553,20 @@ 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}) + * @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, 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 d6daa2466..cea81976e 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 587b04691..f46278dda 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 @@ -608,7 +608,7 @@ public static MyDtoBuilder create() { *

Example:

* *
{@code
-           * builder.name("example value");
+           * builder.name("example name");
            * }
* * @param name name @@ -630,7 +630,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 c093d3ec8..1c862528b 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 c64887810..5e3ed1992 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( @@ -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( @@ -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/BuilderProcessorTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/BuilderProcessorTest.java
index 1244101a0..a49d67b66 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 static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -240,6 +241,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
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 000000000..b3c26957c
--- /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);
+    }
+  }
+}
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 a055d4894..b33249f21 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 metadata", "example metadata"))
+         *     .metadata(() -> Map.of("example metadata", "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 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 value"));
+           * 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 value")).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 @@ -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 beb42e36d..b44f08c02 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/JavadocExampleValuesTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/JavadocExampleValuesTest.java new file mode 100644 index 000000000..db0c8e1f9 --- /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())); + } +} 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 c35909d76..e63000e99 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()"); 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 a2345289f..ef7be6dae 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; }